Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add multiple Emails in one field
I'm trying to create a Company class with an email field who can contains One or Multiple email adresses. I know that there's the EmailField type who can take one email as parameters, but in my case I need to extend it to multiple email. class Client(models.Model): company_name = models.CharField(max_length=100, unique=True) project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL) email_list = models.EmailField(max_length=70) How can I achieved the result to extend this email_list field to take in parameters the multiple email I need ? tx ! -
DRF: GET returns TypeError (500) instead of 405
I have a ModelViewSet that uses @list_route to handle POSTs to a given endpoint. urls.py router.register(r'my-view-set', MyViewSet, 'my-view-set') views.py class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer @list_route(methods=['post'], url_path='validate') def validate(self, request): # validate model return Response({'success': 'Validated'}, status.HTTP_200_OK) When this endpoint is accessed using HTTP GET through curl or wget I get a proper 405 status code as expected: curl: {"detail":"Method \"GET\" not allowed."} wget: 2019-07-09 15:06:48 ERROR 405: Method Not Allowed. However, if I use chrome to browse to the endpoint, I get a 500 error: TypeError at /myapp/api/v1/my-view-set/validate/ __init__() missing 1 required positional argument: 'instance' How do I convince django to return a 405 to a browser instead of a 500 when calling this endpoint with GET instead of POST? Django==1.10.5 djangorestframework==3.5.3 -
Getting GitHub details of a particular user by entering the username dynamically
I am trying to get the GitHub details of a particular user by entering the username dynamically using django. But I am not getting the details,when i click the view button in my index.html code, it is returning that "not found". here is my code forms.py class GithubInfo(forms.ModelForm): class Meta(): model = Github fields = ['name'] views.py from django.shortcuts import render from .forms import UserForm,UserProfileInfoForm,GithubInfo from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse def index(request): form = GithubInfo(request.POST) if form.is_valid(): form.save() return render(request,'signupapp/index.html',{'form':form}) index.html <h2>Github repos</h2> <form action="{% url 'signupapp:index' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <a href="https://api.github.com/users/{{form.name}}/"> <input type="button" value="view"/> </a> </form> can anyone help me to achieve this -
Why FieldFile returns different relative and absolute paths for .doc and .docx files?
I want to convert .doc to .docx if a POSTed (in Django admin page) file has .doc extention. When POSTed file has .docx extention nothing wrong happens: Django uploads document.docx into media/documents/document.docx and I can read it. But if a POSTed file has .doc extention I have strange Django behavior: It doesn't uploads document.doc into media/documents/document.doc! Instead of this Django make relational path for this file like 'document.doc' ('documents/document.docx' for the .docx file) and full path is wrong too: /home/steppenhorde/project/app/media/document.doc (/home/steppenhorde/project/app/media/documents/document.docx for the .docx file). So I get an exeption like "Package not found at '/home/steppenhorde/project/app/media/documents/document.docx'" # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') in the settings.py # file = models.FileField(upload_to='documents/') in the models.py # filepath = Model.file if filepath.path.endswith('.doc'): doc_filepath = filepath print(doc_filepath) # document.doc print(doc_filepath.path) # /home/steppenhorde/project/app/media/document.doc os.system(f'antiword {doc_filepath} > {docx_filepath}') else: docx_filepath = filepath print(docx_filepath) # documents/document.docx print(docx_filepath.path) # /home/steppenhorde/project/app/media/documents/document.docx I tried to make paths by myself like: doc_filepath = filepath splitted_doc_filepath = doc_filepath.path.split('/') doc_file_name = splitted_doc_filepath[-1] docx_filepath = f'{MEDIA_ROOT}/documents/{doc_file_name}x' But I still get an exeption like "Package not found at '/home/steppenhorde/project/app/media/documents/document.docx'" because of Django doesn't uploads document.doc into media/documents/document.doc -
Django admin, many-to-many, saving to and retrieving from DB
I have a rather simple relationship between two models: a Person and cities that the person has visited (City). class Person(models.Model): ... cities = models.ManyToManyField(City) I am writing an admin page for this, and I have a separate form class for Person which doesn't mention cities at all, and I have a class inheriting from admin.ModelAdmin, which does. I need to call a function, passing the completely saved instance of Person, with all of the fields properly updated and saved to the db, including the cities. However, whichever of the save... methods I override, I can get the Person instance to get saved and can read the new values from the db, however, I can't get the updated cities from the db. The ones that I have tried are save_m2m and _save_m2m in the form, save_form, save_related in the ModelAdmin. In each of these locations I call super().<the method> and then check person.cities.all(). Each time I get the old value (the one that was in the db before the update, and not the new value from the form). Is there a location I can tap into to get the actual saved and commited value of the many-to-many field? Is there … -
Which Django model fields won't raise IntegrityError if no input is given?
My initial thought was that if for any field null=False, then if the program does not specify a value for the field, IntegrityError will be raised for violating the NOT NULL constraint. I knew some fields such as CharField are an exception, but I tested this by adding a FileField to a model as test = models.FileField(), and not giving it any input. Saving the model did not raise any error. So my question is, which model fields allow the program to save the model when no value or default is specified and null=False? I can't seem to find any comprehensive list online. -
How to Update Django Object
I want to update an object based on various user input. I am getting the id of the object through the url: www.website/new_opportunity/new_opportunity_review?id=2. I have a nearly identical function which works perfectly fine, so I am wondering why the object is not updated upon submission using this function. views.py def new_opportunity_create(request): id = request.POST.get('id') presales_engineer = request.POST.get('presales_engineer') form_class = AssignOpportunityForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): try: obj = Opportunity.objects.get(id=id) obj.presalesEngineer = presales_engineer obj.save() except Opportunity.DoesNotExist: obj = None # Email template = get_template('new_opportunity_assign.txt') context = { 'id': id, 'presales_engineer': presales_engineer } return render(request, 'website/new_opportunity_create.html', context) new_opportunity_review.html <form action="{% url 'new_opportunity_create' %}" method="post" name="newOpportunityForm" id="newOpportunityForm" data-location-url="{% url 'new_opportunity_location' %}" data-contact-url="{% url 'new_opportunity_contact' %}"> {% csrf_token %} <div class="field"> <label class="label">Presales Engineer:</label> <div class="select"> <select name="presales_engineer" id="presales_engineer"> <option value="{{ presales_engineer_id }}">{{ presales_engineer }}</option> </div> </div> -
Save a choice from verbose_name to actual value
I want to save a CharField using the choices argument from a form sent by axios. The value sent is the verbose_name of the choice. Can I match my verbose_name with the actual value, without retyping an if/else statement which is repeating my choices tuple. Example: class Ball(models.Model): color_choices = ( ('b', 'blue'), ('g', 'green'), ... ) The POST request from axios send the value blue. So in the view, I can do this: if request.method == 'POST': data = json.loads(request.body) if data['color'] == 'blue': color = 'b' elif data['color'] == 'green': color = 'g' ... Is there a more DRYest way? -
How to access django development server onVM virtual box from actual computer?
I have my actual laptop which has virtual box installed. I am running ubuntu 18.04 as a virtual machine and I installed django on the virtual machine and am testing my app so I did python manage.py runserver and I can access the app by visiting 127.0.0.1:8000 from my VM, however, If I go to 127.0.0.1:8000 from the actual computer (not the VM), it says 'chrome could not connect to 127.0.0.1:8000'. If I did manage.py runserver 192.0.2.15:8000 on vm where 192.0.2.15 is ip address of vm, it gives error :that ip address can't be assigned to. Any idea how to fix it? Please help me. -
use if condition inside html tag using jinja tag
i made a header for my site project and it has some sections... i want to change the section color name on header using jinja but i can't the template already rendered without error but section name doesn't change and in pycharm this message shows up :Tag start is not closed <ul class='menu'> <li {% if section == "dashboard" %}class="selected"{% endif %}> <a href="{% url 'dashboard' %}">My dashboard</a> </li> <li {% if section == "images" %}class="selected"{% endif %}> <a href="#">Images</a> </li> <li {% if section == "people" %}class="selected"{% endif %}> <a href="#">People</a> </li> </ul> -
Using Two Databases in Django (one read-only)
I am using two databases, one to read data from and then write data to another. Below is my Router class and my changes to settings but am very new to this concept, can someone with more experience in this area confirm that it should work or help make edits? The application is named "myapp", the read-only database I have named "readonly_db" and the database I want to write to is the "default" database. class MyappRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp': return 'readonly_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp' return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == obj2._meta.app_label: return True else: return False return None def allow_migrate(self, db, **hints): if db == 'default': return True elif db == 'readonly_db': return False return None DATABASE_ROUTERS = ['<path to>.myapprouter.py'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myapp' , 'USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': 'LOCALHOST', 'PORT': '5432' } 'readonly_db': { 'ENGINE': 'django_postgres_readonly' 'NAME': 'READONLY' 'USER': 'USER' 'PASSWORD': 'PASSWORD' 'HOST': 'LOCALHOST' 'PORT': '5432' } -
How to transfer one mongodb database from one computer to another
I am using django 2.2 and mongodb as database for backend. i have inserted all data in my application.I am also using Robo3T for seeing collections of mongodb database.My database name is CIS_FYP_db. In my computer everything is going perfect but i want to transfer that project into another computer while i am transferring the project which also contains data\db file with many collections.wt files but when i am running that project in other computer it is showing me that database is blank.No data were present there and mongodb is making new database with the same name CIS_FYP_db with no collections.Please help me to solve this problem that how can i transfer my mongodb database into other computer so i can use it into my application which is already made for that database.Thanks in advance setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'CIS_FYP_db', } } -
Why django doesnt upload files which contain specific characters to s3?
I have a Django App, which allows users to upload csv files on an AWS S3 Bucket. Lets assume that I want to upload a file called myfile.csv to an s3 bucket, then I am able to upload it on my bucket with no problems. Despite that, if I rename the exact same file to myfile(1).csv, then for some reason the file does not get uploaded to the bucket anymore. Does anyone have an idea as to why this happens? Here is my code: forms.py class CsvForm(forms.ModelForm): csv_file = forms.FileField(widget=forms.FileInput( attrs= { 'class': 'form-group', } )) class Meta: model = CSVUpload fields = ('csv_file', ) def save(self): csvfile = super(CsvForm, self).save() return csvfile def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file'] if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith('.csv'): return uploaded_csv_file else: raise forms.ValidationError("File must be csv") else: return uploaded_csv_file models.py from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone import time class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) def __str__(self): return self.csv_file storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings import boto3 import time class CsvStorage(S3Boto3Storage): location = settings.AWS_CSV_LOCATION file_overwrite = False views.py def csvtojson(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(about) else: form = … -
lookup was already seen with a different queryset
I sort the list of credits by ajax request. The first time everything goes well, I get sorted list of credits and update the cache. But when I try to sort again, I get an error. 'creditpayments' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. If the cache is not to update, then there will be no error. But I need to update it... models class Credit(models.Model): pass class CreditPayment(models.Model): credit = models.ForeignKey(Credit, on_delete=models.CASCADE, related_name='creditpayments') rate = models.DecimalField(_('rate'), max_digits=7, decimal_places=2) views class SortedCreditsList(ListView): def get(self, *args, **kwargs): if self.request.is_ajax(): credits = cache.get('credits') prefetch = Prefetch('creditpayments', CreditPayment.objects.all()) credits = credits.prefetch_related(prefetch).annotate(min_rate=Min('creditpayments__rate')) credits = credits.order_by('min_rate') cache.set('credits', credits) credits = credits.filter(best=False, hot=False) template_ajax = render_to_string( template_name='credits/includes/credits_filter_result.html', context={ 'credits': credits, }) return JsonResponse({'success': True, 'template': template_ajax}) Traceback ValueError at /sorted_kredit/ 'creditpayments' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. Traceback: File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/m0nte-cr1st0/work_projects/startup/finbee/credits/views.py" in get 555. cache.set('credits', credits) File … -
Raspberry Pi django server ImportError cannot import name 'etree'
I'm trying to setup Django project on Raspberry Pi to serve a framework on a local network. I have succesfuly installed Django, it is starting with apache2 and all computers on network can see default Django "It worked" page. After I load my app, I'm getting the web page with error: ImportError cannot import name 'etree' at location /home/pi/Django/Ponude/lib/python3.6/site-packages/docx/opc/oxml.py in <module>, line 12 I have installed with pip all necessery modules, here is all from pip freeze: Django==2.2.3 lxml==3.6.0 Pillow==6.1.0 python-docx==0.8.10 pytz==2019.1 sqlparse==0.3.0 When I try to import modules manually in shell, there is no problem importing, only when starting django. I have tried uninstalling and installing all modules, but no help. I also searched Stack Overflow, but found nothing similar or nothing that helped. Can somebody please help me? Is it maybe about permissions or apache2 config? I'n case it helps, here is my apache2 config: <VirtualHost *:80> ServerName www.example.com ServerAdmin webmaster@localhost Alias /static /home/pi/Django/Ponude/Ponude/static <Directory /home/pi/Django/Ponude/Ponude/static> Require all granted </Directory> <Directory /home/pi/Django/Ponude/Ponude/Ponude> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Ponude python-path=/home/pi/Django/Ponude/Ponude:/home/pi/Django/Ponude/lib/python3.6/site-packages WSGIProcessGroup Ponude WSGIScriptAlias / /home/pi/Django/Ponude/Ponude/Ponude/wsgi.py </VirtualHost> Thank you -
AttributeError: 'function' object has no attribute 'as_view'
I've got this error but I don't understand with it occurs. I've another Django project and it works fine (url was with id, now it is pk, might have an error here?). error: path('/delete/', views.item_deleteView.as_view(), name='delete_item'), AttributeError: 'function' object has no attribute 'as_view' views.py: from django.views.generic import DeleteView Delete a product tree item class item_deleteView(DeleteView): template_name = 'product_tree/pt_delete_item.html' def get_object(self): pk_ = self.kwargs.get("pk") return get_object_or_404(ProductItem, pk=pk_) def get_success_url(self): return reverse('db_books:db_list') urls.py: from . import views app_name = 'product_tree' urlpatterns = [ ... path('/delete/', views.item_deleteView.as_view(), name='delete_item'), ... ] -
Django 2.2.3 How list all pages of project and associated its in choicefield models
I have faced in difficulty is that i have a model now in my models i have choicefield. I want that user create slider and associate this slider to existed page url. That's my utils.py (Url of source code) contains: from django.conf import settings from django.urls import get_resolver, URLPattern, URLResolver urlconf = __import__(settings.ROOT_URLCONF, {}, {}, ['']) def list_urls(lis, acc=None): if acc is None: acc = [] if not lis: return l = lis[0] if isinstance(l, URLPattern): yield acc + [str(l.pattern)] elif isinstance(l, URLResolver): yield from list_urls(l.url_patterns, acc + [str(l.pattern)]) yield from list_urls(lis[1:], acc) def get_list_urls(): RESOLVERS_LIST = list() i = 0 for u in list_urls(urlconf.urlpatterns): value = ''.join(u), str(''.join(u)).upper() RESOLVERS_LIST.append(value) return RESOLVERS_LIST My models: @python_2_unicode_compatible class Slider(models.Model): LIST_PAGES_URLS = get_list_urls() master_start = models.IntegerField(default=1000, blank=True) master_end = models.IntegerField(default=5000, blank=False, null=True) view_to_add = models.CharField(_("Assoc page url ?"), max_length=100, choices=LIST_PAGES_URLS) def __str__(self): return self.get_view_to_add_display() class Meta: verbose_name = _("Slider") My main problem is that when i try to import my model class in admin.py. *Server return me ImportError: cannot import name 'Slider'* I use Python 3.7 and Django 2.2.3... Please help ! -
how to prevent input type file from accepting some inputs on change function
I'm working on a project and I need the user to upload only pdf files. I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do? function changeName(elem) { $("input[type='file']"). elem.on("change", function() { var fileName = elem.val().split("\\").pop(); var fileExtension = elem.val().split(".").pop(); if (fileExtension === "pdf") { elem.siblings(".Syllabus").text(fileName); } else { elem.siblings(".Syllabus").val(''); elem.siblings(".Syllabus").text('...'); alert('Only PDF files are accepted'); } }); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="Syllabus fileReset">...</label> <input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" /> -
Looking for a model example in Django
i just finished an online Django course and i am working on my first project. I want to make a sub model under AbstractUser model which the user could edit manually. I don’t know where to start to look for it (I tried to do that in github and didn't found one), i would be happy if somebody could share some example or video or something like that sub model. When i mean edit manually is that he could choose fields and fields type and name them , so i as the web admin could manipulate them. Thanks! -
2 Slug in url path
I want the url like this example.com/lol/tournament/tournament-slug/match/match-slug i did it However, is it the right approach to use it like this? Is there a better way? code: leagueoflegendsgame=game[0] views.py def lolmatch_detail(request, tournamentslug, lolslug): lolmatch=get_object_or_404(LeagueOfLegendsGame, lol_slug=lolslug) game=LeagueOfLegendsGame.objects.filter(lol_slug=lolslug) tournamentslug = get_object_or_404(Tournament, tournament_slug=tournamentslug, leagueoflegendsgame=game[0]) urls.py path('lol/tournament/<str:tournamentslug>/match/<str:lolslug>', lolmatch_detail, name='lol_match_detail'), models.py class LeagueOfLegendsGame(Game): name=models.CharField(max_length=255,blank=True,null=True) lol_slug=models.SlugField(unique=True,max_length=255) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True, blank=True) match=models.ManyToManyField(Match)... class Tournament(models.Model): name=models.CharField(max_length=255) tournament_slug=models.SlugField(unique=True,max_length=255) -
How to count queryset from ManyToManyField in django?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) hot_league = models.ManyToManyField('HotLeague', blank=True) class HotLeague(models.Model): user = models.ManyToManyField(User, blank=True) price_pool = models.IntegerField() winner = models.IntegerField() In views: match = Match.objects.filter(user=request.user) hot_league = match.hot_league.filter(user=request.user).count() Here in views count() is not working. How can I count the hot_league which situated in match ?? -
Django Mysql: MigrationSchemaMissing Error Windows
SO has a lot of questions on this error, but I am unabble to get rid of it. I am trying to connect my Django app to a MySQL database, but keep getting this error: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1064, "pa rse sql 'CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL)' error: syntax error at position 8 near create")) I have initialised a new project and just changed settings.py to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'enigma', 'HOST': '10.5.245.137', 'PORT': '3306', # 'USER': '', # 'PASSWORD': '', 'OPTIONS': { # 'sql_mode': 'traditional', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } I have removed Options, but it does not work. I have used different Django versions and mySqlClient versions, but still can't get it to work. My current Django and mysqlclient are the latest versions, i.e. mysqlclient-1.4.2.post1 and django-2.2.3. -
How Can i Create a UI using nested database table fields in Python Using REST API?
I want to Create a tree structure for categories and subcategories in UI. Data should be retrieve from database entries. I have to Use REST API to get the data from backend & authentication for REST API as well UI 1. Create a tree structure for categories and subcategories view. 2. Subcategories can be up to N level Database: 1. Create database and required tables for managing tree structure 2.Use test entries to display on UI Backend: 1. Write Python code to fetch and display data 2. Use Authenticated REST API as a middleware -
Is there a way of accessing other table using foreign key
I am making a job-portal and I needed to access user field of Vacancy model using VacancyApply model. model.py class Vacancy(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) jobcategory=models.IntegerField(choices=( (1,'IT/Telecomunication'), (2,'Engineering'), (3,'Medical'), )) title=models.CharField(max_length=50) date_added=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) deadline=models.DateField(default=datetime.now() + timedelta(days=15)) description=RichTextField() def __str__(self): return(self.title) class VacancyApply(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) vacancy=models.ForeignKey(Vacancy,on_delete=models.CASCADE) applieddate=models.DateField(auto_now=True) status=models.IntegerField(choices=status_choices,default=1) -
Direct assignment to the forward side of a many-to-many set is prohibited
I'm trying to write a script that will fill database from json file. It looks like this: class Command(BaseCommand): def handle(self, *args, **options): categories = load_from_json('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(**category) new_category.save() restaurants = load_from_json('restaurants') Restaurant.objects.all().delete() for restaurant in restaurants: category_name = restaurant['category'] _category = ProductCategory.objects.get(name=category_name) restaurant['category'] = _category new_restaurant = Restaurant(**restaurant) new_restaurant.save() When i run it, django throws an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. My models looks like this: class ProductCategory(models.Model): name = models.CharField(verbose_name='наименование категории', max_length=64, unique=True) image = models.ImageField(upload_to='category_images', blank=True) description = models.TextField(verbose_name='описание категории', blank=True) def __str__(self): return self.name class Restaurant(models.Model): name = models.CharField(verbose_name='наименование ресторана', max_length=64, unique=True) description = models.TextField(verbose_name='описание категории', blank=True) image = models.ImageField(upload_to='restaurant_images', blank=True) category = models.ManyToManyField(ProductCategory) def __str__(self): return self.name Looks like many people have encountered with this problem, but i struggle with finding a solution to this.