Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have Django Rest Framework serializer return same format as Django core serializer
Using Django Rest Framework I'm trying to return my queryset with the data nested under the model's primary key. This is the default format if using an http request with Django's core serializer and JsonResponse. I'm trying to get my DRF ModelSerializer to return in the same format. I've looked through the docs but don't see anything about altering the output format. Django's core serializer returns the queryset nested below a primary key. @csrf_exempt @api_view(['POST']) def search_foods_http(request): post_data = request.data['params']# 'Params' from axios request print(post_data) search_qry = post_data['search_qry'].lower() food_type_grp = post_data['food_type_grp'] search_results = Foods.objects.filter(food_description__contains=search_qry,food_type_grp__in=food_type_grp) return JsonResponse(core.serializers.serialize('json',search_results), safe=False) results: "[{\"model\": \"food.foods\", \"pk\": 329246, \"fields\": {\"food_description\": \"builder's bar - crunchy peanut butter\", ... Whereas a Django Rest Framework ModelSerializer response @api_view(['POST']) def search_foods(request): post_data = request.data['params'] # 'Params' from axios request search_qry = post_data['search_qry'].lower() food_type_grp = post_data['food_type_grp'] search_results = Foods.objects.filter(food_description__contains=search_qry,food_type_grp__in=food_type_grp) serializer = FoodModelSerializer(search_results, many=True) return Response(serializer.data) returns data without the primary key. [ { "food_key": 329246, "food_description": "builder's bar - crunchy peanut butter", ... Does anyone know if there's specify to do this? I don't want to iterate through the queryset in View. -
How to solve blocked access to XMLHttpRequest at 'URL' by CORS policy?
I suddenly got the following error when working with AJAX in my virtualenv to make API calls AND already studied a bunch of SO threads about similar issues: Access to XMLHttpRequest at 'http://www.api-football.com/demo/api/v2/teams/team/77/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I run the latest Python + Django and Google Chrome Versions. What I've already tried: cleared my browsers cache installed cors app, included it in Apps, included middleware accordingly set CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_CREDENTIALS = True tried a different API, same error installed and activated the google chrome CORS extension, same error changed DataType to jsonp, error gone BUT then i end up with the following error: jquery.min.js:2 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.footystats.org/league-teams?key=example&include=stats&league_id=1625&callback=jQuery34101697774297755965_1570102531537&_=1570102531538 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. My settings.py ALLOWED_HOSTS = ['127.0.0.1'] SILENCED_SYSTEM_CHECKS = [ 'admin.E408', 'admin.E409', 'admin.E410', ] DEBUG = 'TRUE' #Rooting ROOT_URLCONF = 'dasocc_site.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") #Applications CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
id the field is required - error in Django formset
I am using Django 2.2. My models are class Group(models.Model): group_name = models.CharField(max_length=100) def __str__(self): return self.group_name class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) board = models.CharField(choices=board_options,max_length=1,null=True) group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True) class Subject(models.Model): subject_name = models.CharField(max_length=50) subject_category = models.ForeignKey(Category, on_delete=models.CASCADE) subject_photo = models.ImageField(null=True,blank=True) def __str__(self): return self.subject_name class Subject_Assignment(models.Model): board = models.CharField(choices=board_options,max_length=1,null=True) group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True) Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class Mark_Survey(models.Model): survey_name = models.CharField(max_length=50) opens_at = models.DateField() ends_at = models.DateField() class Survey_Mark(models.Model): mark_survey = models.ForeignKey(Mark_Survey,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks = models.IntegerField() Here am creating a formset for Survey_Mark and my form should get marks of all Subject. By using Subject_Assignment i can get all the subjects of the particular user.The following view works for the get method but throws error in post method. def postsurvey(request,pk): #post = get_object_or_404(Mark_Survey, pk=pk) SurveyFormSet = modelformset_factory(Survey_Mark, fields=('marks','Subject'),extra=0) if request.method == "POST": formset = SurveyFormSet(request.POST,request.FILES) print(formset.data) print(formset.errors) if formset.is_valid(): post = formset.save(commit=False) post.mark_survey=pk post.user=request.user post.save() html = "<html><body>Success</body></html>" % now return HttpResponse(html) else: print("failure") html = "<html><body>failure </body></html>" return HttpResponse(html) else: user=request.user profile = get_object_or_404(Profile,user_id=user.id) formset = SurveyFormSet(queryset=Subject_Assignment.objects.filter(Q(board=profile.board) & Q(group=profile.group))) return render(request, 'subject_assignment_detail.html', {'formset': formset}) Am getting id the field is required error. … -
Do id primary key have to be explicitly defined in Django models generated from inspectdb against an existing database?
I have an existing MySQL database with several tables already populated with data. I created and configured a Django project with an application. Communication between Django and the database works as expected. I have generated a 'models.py' using 'inspectdb' command to create all my application models: python manage.py inspectdb > myapp/models.py My issue is that none of my models shows any 'id' field in 'models.py'. All existing MySQL tables having an 'id' column as primary key (auto increment being enabled for those) it seems weird. I wonder if I need to explicitly add 'id' primary keys fields in all model classes created with inspectdb or if it is not needed (it would be implicit in that case). Why 'id' primary key is missing from Django models definitions and should I add this field to the models classes? -
mysql query filter LIKE not working properly
i have a column campaign_name. and user might type and look for incase sensitive string keyword. for example they entered "adopt a patient". but inside my table the campaign_name: i have "adopt-a-patient +---------------- |campaign_name | +---------------- |adopt-a-patient| ----------------- select * from campaign where campaign_name LIKE '%ADOPT A PATIENT%'; return ZERO result my campaign_name collation already set to utf8_general_ci.but if users entered exactly the word "adopt-a-patient" the result returned as expected. any help would be much appreciated. anyway im implementing it on django app. im just debug it inside HeidiSQL. -
Soft-coding values to a yaml file for loaddata option
I have the following model: class Plan(TimeStampedModel): name = models.CharField(_("Plan name"), max_length=50, null=False, blank=False, unique=True) The TimeStampedModel it inherits from has created and changed dates: class TimeStampedModel(models.Model): """Reusable template to add created/last updated timestamps to a model""" created_at = models.DateTimeField(_("Created"), auto_now_add=True) changed_at = models.DateTimeField(_("Last changed"), auto_now=True) class Meta: abstract = True Now I run a loaddate from yaml files looking like this: - model: plans.Plan pk: 1 fields: name: Basic plan This gives me an error because the load complains that I haven't defined the timestamp data. What I would like to do, rather than just setting a default timestamp (which I can if it becomes necessary), is just pass the current tiemstamp for the date/time I am running loaddata, which will then get applied to all the yaml files. Running python manage.py testserver demo_data/fixtures/plans.yaml bypasses the DB constraints, and the auto_add options as far as I can see, so the way these fields would normally be set isn't applied. Is there a way of doing this? I can't find anything, not even a similar question, in my searches. -
Django Haystack Scoring seems incorrect
The scoring that im seeing in my search results seems incorrect to me, im not sure if I need to do anything to improve the accuracy of score. in the below example using 'ches', Chester should score high but its scored less than Chelmsford for some reason? query = 'ches' sqs = SearchQuerySet().filter(content=AutoQuery(query)) paginator = Paginator(sqs, 10) page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) >>> for i in results.object_list: ... i.score, i.text ... (7.616099, 'STR-CHEL-RTR-02\n') (7.5457063, 'STR-CHEL-NVR\n') (7.290444, 'STR-CHES-NVR\n') (6.81494, 'Chester\n65001\nCH1 ABC') (6.6442084, 'STR-CHEL-RTR-01\n') (6.493678, 'STR-CHES-RTR-02\n') (6.357569, 'STR-CHES-SW-03\n') (6.357569, 'STR-CHES-RTR-01\n') (5.7965107, 'Chelmsford\n65002\nCM1 ABC') indexes if relevant class DeviceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) def get_model(self): return Device def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all().select_related('site') class SiteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) def get_model(self): return Site def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() and search texts device_text.txt {{ object.hostname }} site_text.txt {{ object.location }} {{ object.bgp_as}} {{ object.postcode }} -
How can I restrict access to a view to only super users in Django
On a site I am developing in Django, I want to restrict access to views so only superusers can access them. I could use @login_required or the LoginRequiredMixin, however I already have a login system for the average person, so that would let any logged in user access the view. I've tried something that I thought would work SuperUserRequired as a mixin, however this obviously didn't work. This has to be able to work in a CBV, as that's what I am using for this view. Here is the relevant view I want to apply this restriction to. class CreatePostView(LoginRequiredMixin,CreateView): redirect_field_name = 'posts/post_detail.html' form_class = PostForm model = Post def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) Thanks for any help you can give :) -
How to pass a variable from a script in a template to a model
I my template, I compute the variable area from a polygon drawn in a map. I would like to pass this value to the database when the user will complete a form. So once the user is on the page, i would like him to complete the form and to draw a polygon on a map. When this polygon is draw I would like the field area of the from(and the table fertisatdb) to update. How can I do this ? script in template.html mapboxgl.accessToken = var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/satellite-streets-v10', center: [-7.60,33.57], zoom: 5, bearing: 0 }); var draw = new MapboxDraw({ displayControlsDefault: true }); map.addControl(draw); map.on('draw.create', updateArea); map.on('draw.delete', updateArea); map.on('draw.update', updateArea); function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var area = turf.area(data); // restrict to area to 2 decimal points var rounded_area = Math.round(area*100)/100; answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'; var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); document.getElementById('export').setAttribute('href', 'data:' + convertedData); document.getElementById('export').setAttribute('download','data.geojson'); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); } } models.py from django.db import models as db_models from django.contrib.auth.models import User from … -
Django Channels send group message from Celery task. Asyncio event loop stopping before all async tasks finished
I'm currently stuck on a particularly tricky problem, I'll try my best to explain it. I have a Django project and it's main purpose is to execute queued tasks from a DB rapidly. I use Celery and Celerybeat to achieve this with Django channels to update my templates with the responses in real time. The Celery worker is a gevent worker pool with a decent number of threads. My Task(Simplified version): @shared_task def exec_task(action_id): # execute the action action = Action.objects.get(pk=action_id) response = post_request(action) # update action status if response.status_code == 200: action.status = 'completed' else: action.status = 'failed' # save the action to the DB action.save() channel_layer = get_channel_layer() status_data = {'id': action.id, 'status': action.status} status_data = json.dumps(status_data) try: async_to_sync(channel_layer.group_send)('channel_group', {'type': 'propergate_status', 'data': status_data}) except: event_loop = asyncio.get_running_loop() future = asyncio.run_coroutine_threadsafe(channel_layer.group_send('channel_group', {'type': 'propergate_status', 'data': status_data}), event_loop) result = future.result() My Error: [2019-10-03 18:47:59,990: WARNING/MainProcess] actions queued: 25 [2019-10-03 18:48:02,206: WARNING/MainProcess] c:\users\jack\documents\github\mcr-admin\venv\lib\site-packages\gevent_socket3.py:123: RuntimeWarning: coroutine 'AsyncToSync.main_wrap' was never awaited self._read_event = io_class(fileno, 1) RuntimeWarning: Enable tracemalloc to get the object allocation traceback [2019-10-03 18:48:02,212: WARNING/MainProcess] c:\users\jack\documents\github\mcr-admin\venv\lib\site-packages\gevent_socket3.py:123: RuntimeWarning: coroutine 'BaseEventLoop.shutdown_asyncgens' was never awaited self._read_event = io_class(fileno, 1) RuntimeWarning: Originally after I saved the action to the DB I just called: async_to_sync(channel_layer.group_send)('channel_group', {'type': … -
What is the best way to deliver django project as a full installation file (setup.exe) to be user-friendly and not revealing your whole scripts?
I have a django project which is working fine. However, this question can be related to any django project. Django works in a way that after running python manage.py runserver the project is accessible at localhost:8000. But when you deliver the project to the customer you cannot expect them to open command windows every time, then run python manage.py runserver, then open a browser, then type localhost:8000 and etc. I have heard docker might be a solution to this. But docker will need the scripts available in the local machine. I am talking about making a full installation file like when you buy a video game and the scripts are not accessible easily (seems there are binary files). The real question is how can we protect our code and scripts and be sure they cannot be accessed easily after we have installed them in a customer's computer? -
How to convert my current django app to REST API?
I need to convert my current django app which is a UserCreationForm with email and phone numbers validation to a REST API. But first I need to register the text fields to the django admin site to have the phonenumber, email and password fields. However in my admin.py at "admin.site.register(UserRegisterForm)", when I run python manage.py makemigrations, an error occurred and it states TypeError: 'ModelFormMetaclass' object is not iterable. I'm not sure if maybe the admin.site does not accept the fields in any UserForms and they only accept models. Here is my code: /* forms.py */ import re import phonenumbers from phonenumbers import carrier from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email # from django.db import models # from django_countries.fields import CountryField, countries # from phonenumber_field.formfields import PhoneNumberField class UserRegisterForm(UserCreationForm): email = forms.EmailField() # phone_number = PhoneNumberField() phone_number = forms.CharField(max_length=100) # country = CountryField(blank_label='Select Country').formfield() country = forms.CharField(max_length=2) class Meta: model = User fields = ['username', 'email', 'country', 'phone_number'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, check_mx=True, verify=True): raise forms.ValidationError("Invalid email") return email def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") clean_number = re.sub("[^0-9&^+]", "", phone_number) # alpha_2 = self.cleaned_data.get("country") alpha_2 = self.cleaned_data.get("country") z = … -
Django background task is locked when there are too many task at the same time
On my server when the user upload multiple files, the python code will be run to process it. I can upload 100 files successfully, But if the files is over than that the task will be lock(I look in Django Admin page) and no more files can be process. Here is the code @background(schedule=datetime.timedelta(seconds=1)) def reflect_upload_data(): . . . But If I comment the @background line out, The problem will not occur. How can I make Django Background Task work in this situation? -
Hello, I'm using python and have the following error: local variable 'my_total' referenced before assignment
UnboundLocalError at /products/forms/ local variable 'my_total' referenced before assignment -
Save the username of the loggedin user in the database instead of the userid
I would like to save the username of the loggedin user in the database. But only the userid shows up in the databse, and i can't seem to work out how to change it to the username. Can you help me get this ? Thanks Here is my code models.py from django.db import models as db_models from django.contrib.auth.models import User from django.contrib.gis.db import models class Fertidb(models.Model): user = db_models.ForeignKey(User, on_delete=models.CASCADE) culture = models.CharField(max_length=50) area = models.IntegerField() plot = models.FileField(upload_to='KML_FILES', blank=True) def __str__(self): return f' Parcelles de {self.user.username}' Forms.py from django import forms from django.contrib.auth.models import User from .models import Fertidb class FertidbForm(forms.ModelForm): class Meta: model = Fertidb labels = { "plot": "Importez votre fichier KML" } fields = ['culture', 'area', 'plot'] views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import FertidbForm from django.contrib.auth.models import User title = 'FERTISAT' @login_required def fertisatmap(request): if request.method == "POST": o_form = FertidbForm(request.POST, request.FILES) if o_form.is_valid(self, o_form): o_form.save(commit=False) fertidb.user = request.user # o_form.user = request.user.username() username = fertidb.cleaned_data.get('username') fertidb.save() messages.success(request, f'Vos informations ont été envoyées') return redirect('fertisat-map') else: o_form = FertidbForm() context = {'title': title, 'o_form': o_form} return render(request, 'fertisat/fertisatmap.html ', context) -
How to do filtering in Django Rest ModelViewset
I have signup api. I'm adding signup details, data adding fine but I don't want to add same data multiple time.For example username="abc", email= "abc@example.com", phone_no="1234567890" data already present in database but its adding same data again and again. I'm trying to avoid this. How to do that modes.py class Signup(models.Model): email = models.EmailField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=12, blank=True, null=True) username = models.CharField(max_length=300, blank=True, null=True) password = models.CharField(max_length=50, blank=True, null=True) serializers.py class SignupSerializer(serializers.ModelSerializer): class Meta: model = Signup fields = '__all__' views.py class SignupViews(viewsets.ModelViewSet): queryset = Signup.objects.all() serializer_class = SignupSerializer urls.py router = routers.DefaultRouter() router.register('api/signup', views.SignupViews) urlpatterns = [ path('', include(router.urls)) ] -
How to access client camera for Face recognition using openCV in Django?
I'm trying to build a website using Django, I have a concept of integrating face login for my website and It's perfectly working on the server computer and when I try to access the same from the client computer, the camera pop-ups in server computer rather in the client computer. I couldn't able to understand how I can access the client camera and pass it to my face recognition code? I have written Django code for face signup using the basic OpenCV concept for face recognition. And Its perfectly working on the server computer and when I access from the client the camera pop-ups from the server computer. All I used on my code is a simple signup form and OpenCV for face recognition. What should I need to pass for the object VideoCapture( ) in order to access the client camera and can anyone suggest me any other possible ways to build a face login module. -
No matching distribution found for Django pip3
I am using Ubuntu 16.04.i have installed python 3 when i run following commands python --version Python 2.7.12 python3 --version Python 3.5.2 pip3 -V pip 8.1.1 from /usr/lib/python3/dist-packages (python 3.5) when i try to install Django pip3 install --user Django Got following error Could not find a version that satisfies the requirement Django (from versions: ) No matching distribution found for Django even i mentioned django version pip3 install --user Django=2.2 Since i am new to python.i have searched and tried many threads but not use -
Python convert DOCX to PDF after modifying document and export PDF to download (DJANGO)
I have a Django app that reads a document template (DOCX) and modifies it. The program is working well, but it is returning to download a DOCX document (as expected). So, I want to edit the download file format to PDF. I thought of converting the DOCX file to PDF but I couldn't find a working way to do that. My actual code looks like this: f = io.BytesIO() document.write(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + formular.name + '.docx' response['Content-Length'] = length return response I want to find a working method of converting the DOCX file f to a PDF file before returning that as response. -
ValueError: Missing staticfiles manifest entry for 'favicon.png' when DEBUG = False
raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'favicon.png' when DEBUG = False I only get this error when DEBUG = False, I do not get any error when DEBUG = True To fix this issue while keeping DEBUG = False, I must add back in favicon.png (which I had deleted a while back) to the static_root folder and then run python manage.py collectstatic I checked all my files and all my html documents have the link favicon.png line commented out, so that is not the issue. settings.py has the following: STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static_root'), ] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'static/') urls.py has following: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to add placeholder text to a Django Admin field
I'd like to add placeholder text to a field in the Django Admin change form. In a regular ModelForm you can do this by overriding the field's widget or by modifying self.fields['my_field'].widget in the ModelForm __init__() method. How do I do something similar for a Django Admin? -
DRF ignoring permission classes for owner
I implemented BasePermission class in project but when I am going to retrieve logged user with his token it says You don't have a permission to perform this action permissions.py class IsLoggedInOrAdmin(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.user == request.user or request.user.is_staff class IsAdminUser(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_staff def has_object_permission(self, request, view, obj): return request.user and request.user.is_staff and my views file looks like this class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [AllowAny] elif self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update': permission_classes = [IsLoggedInOrAdmin] elif self.action == 'destroy' or self.action == 'list': permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] here what i have done so far. I created simple user and took token If I send GET request in Postman I am getting a detail error but it works fine with superuser's token but not owner. Where Am I making mistake? Any help please? Thanks in advance! -
Django using icontains filter with multiple values from dictionary
Hi i'm trying to run a model search query through a dictionary data which i got like so: { "city":5, "direction":"ne", ..other data that can be dynamic... "address__icontains" = ["word1", "word2", "word3"], } My search query: Models.objects.filter(**query_dict) since the other data are dynamic that why i use filter with dictionary.And i'm using __icontains to search up field address(string value) that contains those 3 words in that string, so the problem right now is since __icontains doesn't accept array like so in the query set: Models.objects.filter(other keys and values from dictionary, address__icontains= ["word1", "word2", "word3"]) How would i make this work with the dictionary filter search ? I also tried changing the dictionary to "address__icontains" = "word1 word2 word3" but it also doesn't work Thank for reading -
Django update_or_create results in a duplicated row
I'am trying to update or create an entry. Here are my relevent codes: Models.py class Comment(SafeDeleteModel): id = models.AutoField(primary_key=True) content1 = models.TextField() content2 = models.TextField() fieldA = models.ForeignKey('A') fieldB = models.ForeignKey('B') views.py class CommentViewSet(viewsets.ModelViewSet): def post(self, request): comment, created = Comment.objects.update_or_create( fieldA =request.data.fieldB, fieldB =request.data.fieldB, defaults={ 'content1': request.data.content1, 'content2': request.data.content1, } ) return Response(comment, created) At this point, every time i'm trying to edit a comment where fieldA and fieldB already exist, i got a duplicated row. I sure tried to add unique_together unique_together = (('fieldA', 'fieldB', ),) I now get an integrity error, saying fieldA and fieldB have to be a unique set. Looks like my post class is ignored. Any help would be greatly appreciated. Thanks -
How to have a ModelChoiceField show only one attribute of the class?
I have a model that uses a bunch of foreign keys. That model has its own form and view which works perfectly fine. But one field in the form needs to call only one attribute from the foreign key's class in models. At the moment the dropdown field on the form shows ALL of the info from that model Models: class Book(models.Model): book = models.Charfield(max_lenght=255) author = models.Charfield(max_lenght=255) summary = models.TextField() def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) class BookInventory(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) serial_number = models.CharField(max_length=255) Form: class BookInventoryForm(forms.ModelForm): book_title = forms.ModelChoiceField(queryset=Book.objects.all()) # book_title field should only list books author = forms.ModelChoiceField(queryset=Book.objects.all()) # author field should only show authors summary = forms.TextField() serial_number = forms.CharField(max_length=255) supplier_name = forms.ModelChoiceField(queryset=Supplier.objects.all()) location_name = forms.ModelChoiceField(queryset=Location.objects.all()) class Meta: model = BookInventory fields = ["book_title", "author", "serial_number", "supplier_name", "location_name"] View: def book_inventory(request): if request.method == "POST": form = BookInventoryForm(request.POST) if form.is_valid(): form.save() return redirect("index") else: form = BookInventoryForm return render(request, "add_book_inventory.html", {"form" : form}) So on the add_book_inventory.html page's form there will be two dropdowns, one for author and one for title. At the moment the book title drop …