0

I created two models:

class Country(models.Model):
    name = models.CharField(max_length=50)

class City(models.Model):
    name = models.CharField(max_length=50)
    country = models.ManyToManyField(Country)
    image = models.ImageField('New photos', upload_to='img/newphotos', blank=True)

I want add new cities through template so i created:

views.py

def newcity(request):
    if request.method == "POST":
        form = CityForm(request.POST)
        if form.is_valid():
            city = form.save(commit=False)
            city.save()
            form.save_m2m()
            return redirect('city.views.detailcity', pk=city.pk)
    else:
        form = CityForm()
    return render(request, 'city/editcity.html', {'form': form})

forms.py:

class CityForm(forms.ModelForm):

    class Meta:
        model = City
        fields = ('name', 'country', 'image',)

Everything is ok but when I add image there is nothing happens - image is chosen but when I click save button new city is added without image (in admin panel it works). What must I add to my code? And how can i make possibility to add to one city few images? When i will add first image there should appear button to add second etc. Now I have place only for one.

znawca
  • 279
  • 5
  • 15

1 Answers1

1

Add request.FILES in your views

form = CityForm(request.POST, request.FILES)

and make sure you have enctype="multipart/form-data" and method="post" in your template

<form method="post" enctype="multipart/form-data">{% csrf_token %}
</form>

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.FILES

madzohan
  • 11,488
  • 9
  • 40
  • 67
  • thanks :) maybe you know how can I add few images to one city? – znawca Jun 24 '15 at 14:40
  • yes, but it is another question :D ... declare CityImage(models.Model) and add two fields to it: your image and city = models.ForeignKey('City') ... now you will have relation - many city images to one city ... in your views use formsets (here is how I do usually http://stackoverflow.com/a/26669428/3033586 ) good luck! =) – madzohan Jun 24 '15 at 15:32