Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict view in Django based on permission(s) provided to the user?
I have a Django project wherein I want to show the user the data based on the following options. There are three different listings for a user (show_own_data. show_own_users_data, show_all_users_data) Basically the user(s) will have read permission in this view and the data will be shown according to the choices.(the data is for the modules and sub-modules the user has purchased) if choice = show_own_data, the user can only see his data for various modules and sub modules if choice = show_own_users_data, the user can see the data's for the user's created by the user for various modules and sub modules if choice = show_all_users_data, the user can see all user's data for various modules and sub modules #Permissions.py class Permissions(models.Model): perm_show_own_data = models.BooleanField(default=False) perm_show_own_users_data = models.BooleanField(default=False) perm_show_all_data = models.BooleanField(default=False) #check_permissions.py def has_perm_show_own_users_data(self, show_own_users_data: dict): perm_show_own_users_data = False if self.permissions: qs = Permissions.objects.filter(**show_own_users_data, user=self) if qs.exists(): perm_show_own_users_data = True return perm_show_own_users_data i don't know if the steps are correct or even how to proceed further. Can anyone help please. Can anyone also explain what is show_own_users_data: dict in function has_perm_show_own_users_data(self, show_own_users_data: dict) -
When I log in to 'contact-profile.html' it does not show me the data stored in admin do not know where my mistake is?
fjjndjhvs dabjhdnbsaujhdhjs dshgsbdjnmgaB ``` (models.py) from django.db import models # Create your models here. class contact(models.Model): full_name = models.CharField(max_length= 500) relationship = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=100) def __str__(self): return self.full_name ``` bjhfgdfjkmdbskjfmhdsjkmhas ``` (views.py) from django.shortcuts import render, redirect from .models import contact from django.shortcuts import render, redirect from .models import contact # Create your views here. def index(request): contacts = contact.objects.all() return render(request, 'index.html', {'contacts': contacts}) def addContact(request): if request.method == 'POST': new_contact = contact( full_name = request.POST['fullname'], relationship = request.POST['relationship'], email = request.POST['email'], phone_number = request.POST['phone-number'], address = request.POST['address'], ) new_contact.save() return redirect('/') return render(request, 'new.html' ) def ContactProfile(request, pk): Contact = contact.objects.get(id=pk) return render(request, 'contact-profile.html', {'contact': contact}) def EditContact(request, pk): Contact = contact.objects.get(id=pk) return render(request, 'edit.html', {'contact': contact}) ``` bdjhsnbdjhnmgbsahjmdgbsuj ``` (urls.py) from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name ='index'), path('add-contact/', views.addContact, name='add-contact'), path('profile/<str:pk>', views.ContactProfile, name='profile'), path('edit-contact/<str:pk>', views.EditContact, name='edit-contact'), ] ``` (contact-profile.html) {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'style-profile.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/6b20b1c14d.js" crossorigin="anonymous"></script> <title>Contact Profile</title> </head> <body> <div class="container"> <header class="hero"> … -
Is there any way to retrive choice field text using sql query?
I am writing a script in python to retrieve data from the Postgres database. And, I'm getting data of choice field as an integer value, Is there any way to retrieve text format of choice field using SQL query only. -
Django class-based view to return HttpResponse such as HttpResponseBadRequest
I have a custom Django view class that inherits from the generic DetailView. The generic DetailView class sequentially calls its methods get_queryset, get_object, and others to generate an object to pass for a Django template. Moreover, the generic DetailView class raises Http404 exception within these methods to deal with erroneous situations #. except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) What I am trying to do is simple: I want to return other HTTP status codes to the client if an error is found within these methods. However, because Http404 is the only Django HttpResponse that has a form of exception, it seems like this cannot be achieved easily. Because HttpResponse is not an exception, I have to return it instead of raising it. Therefore, the customized method becomes the following form. def get_object(self, queryset=None): ... try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: return HttpResponseBadRequest("Bad request.") However, above code does not send HttpResponseBadRequest to the client. Instead, it returns HttpResponseBadRequest as an object for a Django template. The client gets 200 status code with an invalid object for the template. The only possible solution to think is writing … -
django cors headers giving 'WSGIRequest' object has no attribute 'host' error
Hi I am trying to use the built in signal to check if the host exists in the database but i get this following error 'WSGIRequest' object has no attribute 'host' My code def cors_allow_sites(sender, request, **kwargs): return ConsumerURLModel.objects.filter(url=request.host).exists() check_request_enabled.connect(cors_allow_sites) My middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] -
Error installing libraries on heroku django app
I am trying to deploy django app on heroku and error happends while heroku installs from requirements.txt: requests==2.25.1 asgiref==3.3.4 beautifulsoup4==4.9.3 certifi==2020.12.5 chardet==4.0.0 Django==3.2 djangorestframework==3.12.4 idna==2.10 pytz==2021.1 soupsieve==2.2.1 sqlparse==0.4.1 urllib3==1.26.4 2captcha-python==1.1.0 The last library needs requests to be installed. It works perfectly on local machine if i just put requests before 2captcha, but on heroku it returns erorr ModuleNotFoundError: No module named 'requests' I tried switch places for requests and 2captcha but it didn't help -
Show ISO date values in string form
So I was trying to get what months that an insurer filed a claim. However, the values were in ISO Form. I was trying to show it in string form. Instead of showing 2021-01-01, show January; 2021-01-02, show February Here's the sample get data Data in image form { "Month": [ "2021-04-01T00:00:00+08:00", "2021-02-01T00:00:00+08:00", "2021-03-01T00:00:00+08:00" ], "Claim(s)": { "": 18, "Bank Transfer": 5, "CAR": 1, "home": 5, "Credit": 7, "Energy": 1, "health": 38, "\"health\"": 5 } } I'd like to change the ISO date form into string form instead. Here is my code in Views class GetClaimsCompare_year(APIView): def get_claim_count(self, claims_data, claim_type): claims_count = claims_data.filter(claim_type = claim_type).count() return claims_count def get_claims_type(self, claim_per_month): return claim_per_month.claim_type def get(self, request): today = datetime.now() claims_data = Claims.objects.filter(modified_at__year =today.year) claim_per_month = claims_data.annotate(month = TruncMonth('modified_at')).values('month').annotate(claim_type=Count('id')) labels = [] claims_type = list(set(map(self.get_claims_type, claims_data))) final = {} for claims in claim_per_month: labels.append(claims['month']) for claim_type in claims_type: final[claim_type] = self.get_claim_count(claims_data, claim_type) context = { 'Month':labels, 'Claim(s)':final } return Response(context) -
How to send request with CSRF cookie using fetch in React
I send post request to Django api server but I don't know how to send csrf cookie. sending the post request from React . upload.js import Cookies from 'universal-cookie'; const cookies = new Cookies(); cookies.set('csrftoken', 'sth', { path: '/' }); const fileUpload = (e) =>{ e.preventDefault(); const fileForm = document.getElementById.fileForm; const formData = new FormData(fileForm); fetch('http://192.168.0.1:8000/upload/', { method:'POST', headers: { 'content-type': 'multipart/form-data', 'X-CSRFToken':'sth' }, credentials: 'same-origin', body:formData }) ... } Django Response Reason given for failure: CSRF cookie not set. -
How to solve could not convert string to float error in Django?
I am doing currency conversion in my Django project. Users choose the currency and enter the credit_limit, and I convert the input entered by the user into a float in the backend and convert it according to the entered currency. There is no problem when the user enters numbers such as 10, 20 in the credit limit field, but this error appears when numbers such as 1000000 are entered. how can I solve this? ValueError at /customer could not convert string to float: '1,000,000.00' views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = NewCustomerForm(request.POST) # Check if the form is valid: if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') cred_limit = newCustomer.usd_credit_limit value = str(cred_limit)[1:] float_str = float(value) newCustomer.credit_limit = float_str newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('CAD', 'CAD'), ...] customer_name = models.CharField(max_length=100) ... currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) credit_limit = models.FloatField(default=0, null=True) usd_credit_limit … -
CharField not holding formatting
I have a form that stores a Field with a Textarea widget to a CharField, I would like for it to not clean out line breaks and other formatting information such as tabs and multiple spaces. Is there a way to go about doing this? special_instructions = forms.CharField( label = "Special Instructions", widget=forms.Textarea( attrs={ 'id': 'textarea-ed95', 'class':'u-border-1 u-border-grey-30 u-input u-input-rectangle', 'placeholder':'Special Instructions' } ) ) -
Kendo UI filter "contains/doesnotcontain" filters working OK but other filters not working with Django objects
Kendo UI filter "contains/doesnotcontain" filters working OK but other filters not working with Django objects Hello, I have a html table declared and populate the cell values() using Django object as mentioned below. <div class=""> {% if object_list %} <table id="gridentries" class="table table-striped table-border"> <thead class="thead-light" role="rowgroup"> <tr role="row"> <th style="width: 19%">{% trans 'Field1_hdr' %}</th> <th style="width: 19%">{% trans 'Field2_hdr' %}</th> </tr> </thead> <tbody role="rowgroup"> {% for entry in object_list %} <tr> <td> {{ entry.field1 }} </td> <td> {{ entry.field2 }} </td> {% endfor %} </tbody> </table> . . Now I have a Kendo grid declared where I am referring above table structure and defined all filters possible. Filters "contains/doesnotcontain" works perfectly OK, but other filters like "startswith"(for eg) is not working OK for the grid. I was thinking django object entries {{ entry.field1 }} is not exactly treated as a string in HTML(might be some unknown characters are prefixed/suffixed and hence "startswith") and hence tried to convert to an HTML var (and HTML strings) but that didn't work either. Can anyone please help? Where am I going wrong? <script> $(document).ready(function () { $("#gridentries").kendoGrid({ height: 1500, sortable: true, pageable: { pageSize: 20 }, filterable: { messages: { and: "{% trans … -
pickle.load() sometimes can't working in my environment(ubuntu16.04,python3.5)
Today I start a Django project which can run properly yesterday. But now, it gets a problem. When I debug with Pycharm, I find that after pickle.loads(a_bytes) a return is still a_bytes. not a string. -
Django channels database access method returns coroutine object
I'm trying to access some data in the database in my consumers.py file like this: @database_sync_to_async async def get_project(self, email): client = await Account.objects.get(email=email) return await Project.objects.filter(client=client).last() And if I print what this method returns I get this: <coroutine object SyncToAsync.__call__ at 0x7fa6129eaf40> So there for when I try to send this object back to the channels_layer group I get this error: TypeError: Object of type coroutine is not JSON serializable Even if I try to access one of the children of this object, for example description I'll get: AttributeError: 'coroutine' object has no attribute 'description' So how can I access this object from database? -
How do I pass an instance to a view?
I'm not able to understand the complaint that the system is returning. Here is the view for the system def AddMarksView(request): class_name = request.session.get('class_name') subject = Subject.objects.filter(name='Maths') exam = Exam.objects.filter(name='Endterm') students = Students.objects.filter(school=request.user.school,klass__name = class_name,stream__name='South') if request.method == 'POST': for student in students: marks = int(request.POST['marks']) marks_object = Marks.objects.create(student=student,marks=marks,subject=subject,exam=exam) else: return render(request,'feed_marks.html') return redirect('search_m') The error returned is Cannot assign "<QuerySet [<Exam: Endterm>]>": "Marks.exam" must be a "Exam" instance. The model for Marks odel is class Marks(models.Model): exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True,blank=True) subject = models.ForeignKey(Subject,on_delete=models.SET_NULL,null=True,blank=True) student = models.ForeignKey(Students,on_delete=models.SET_NULL,null=True,blank=True) marks = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100),] ,null=True,blank=True) How can I format the view so tha it returns no error? -
How to calculate the points based on the price of the total purchase in django models?
I am trying to create points earned by users after buying something and placed an order from the frontend. Also, I need to save the points on the database because users later use that points to buy something. The points system looks like this. Point System for % of the total purchase Upto 10,000 = 1 % 10k to 50k =2.75% 50K plus = 5% I haven't saved the price in DB, I just used it as a property so that it remains safe and cant be changed by anyone. It calculates whenever the get or post API is called. class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): # abc = sum([_.price for _ in self.order_items.all()]) # print(abc) return sum([_.price for _ in self.order_items.all()]) def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property … -
How to link two Django models created by a logged in user?
For my web application, people who are registered as authenticated users are able to create one Trainer object and as a trainer, upload many different Pokemon. So on Django admin, if I check the data entries for the Trainer and Pokemon objects, I am able to tell that different users have successfully uploaded their own Pokemon to the database. However, I'm having trouble establishing the relationship between the Trainer and Pokemon objects. This also means that my HTML template to view each Trainer and their Pokemon is messed up. Here's what I have so far: # pokeweb/models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User # Create your models here. class Trainer(models.Model): '''Represents a trainer with a Pokeweb account''' #data attributes: user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) last_name = models.TextField(blank=True) first_name = models.TextField(blank=True) email = models.TextField(blank=True) birthday = models.DateField(blank=True) region = models.TextField(blank=True) image_url = models.URLField(blank=True) def __str__(self): '''Return a string representation of this trainer''' return f'{self.first_name} {self.last_name}, {self.region}' def get_pokemons(self): ''' Return pokemon of trainer via object manager''' return Pokemon.objects.filter(trainer=self) def get_absolute_url(self): ''' Provide a url to show trainer object''' return reverse('show_trainer', kwargs={'pk':self.pk}) class Pokemon(models.Model): '''Represents a Pokemon that belongs to a user''' #data attributes: name = … -
Is there any other way to save and load keras models?
I was deploying a tf.keras model to a django app on shared hosting. I have saved it as a .h5 file and it works. Here is the problem, when it loads on the browser for the fist time it takes too much time to import tensorflow and gives a 403 error. It only works after that. Is there any other way to load the model faster? Thanks in advance for your help. -
How does Heroku Django picks up settings file during production? Multiple settings
It's my first time deploying so I just want to make sure that I understand. Basically, how does heroku django determine which setting file to choose when its deployed? Are there any command that I can type in order to check which setting file its currently using? like if its a prod or dev. ^^ To answer the above question on my own, you set myproject.settings.prod in wsgi file and heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings.prod to tell it to choose your prod settings for production/deploymnent. Am I correct in my understanding? Thanks in advance. Any advice or feedback would be apprecated! -
403 Forbidden nginx/1.18.0 (Ubuntu) for Django 3.1, facing issue in media files and admin css
I have django 3.1 installed on digitalocean ubuntu 20.04 and nginx/1.18.0 (Ubuntu) and using rest api Following are my static and media files settings. STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / 'static_in_env' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Following is my Digital Ocean Nginx Conf location /static/ { root /home/username/backend/src; } location /media { root /home/username/backend/src; } it's giving me forbidden on even files less than 100kb. -
Django Deployment Failure in Pythonanywhere
Getting this error in my error logs when deploying my site 2021-04-23 16:20:38,663: Error running WSGI application 2021-04-23 16:20:38,676: django.core.exceptions.ImproperlyConfigured: The app module <module 'tracker' (namespace)> has multiple filesystem locations (['/home/jpf911/COVID19-Vaccination-Tracker/COVID19-Vaccination-Tracker/vaccination_tracker/tracker', './tracker']); you must configure this app with an AppConfig subclass with a 'path' class attribute. 2021-04-23 16:20:38,676: File "/var/www/jpf911_pythonanywhere_com_wsgi.py", line 14, in <module> 2021-04-23 16:20:38,677: application = get_wsgi_application() 2021-04-23 16:20:38,677: 2021-04-23 16:20:38,677: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-04-23 16:20:38,677: django.setup(set_prefix=False) 2021-04-23 16:20:38,678: 2021-04-23 16:20:38,678: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2021-04-23 16:20:38,678: apps.populate(settings.INSTALLED_APPS) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2021-04-23 16:20:38,679: app_config = AppConfig.create(entry) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 255, in create 2021-04-23 16:20:38,679: return app_config_class(app_name, app_module) 2021-04-23 16:20:38,679: 2021-04-23 16:20:38,679: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 49, in __init__ 2021-04-23 16:20:38,679: self.path = self._path_from_module(app_module) 2021-04-23 16:20:38,680: 2021-04-23 16:20:38,680: File "/home/jpf911/.virtualenvs/vaccinationvenv/lib/python3.8/site-packages/django/apps/config.py", line 88, in _path_from_module 2021-04-23 16:20:38,680: raise ImproperlyConfigured( Here are my Configurations: Code: Source Code & Working Directory.jpeg Wsgi Configurations: Wsgi config.jpeg Virtual Environmet: Virtual env.jpeg Static Files & Security: Static_Files & Security.jpeg Settings.py: Settings 1.jpeg Settings 2.jpeg Console: Console.jpeg -
Call a javascript function of base template from another template in django
in my base.html template, I write a function. Can I call it from another template? I tried like this. It doesn't work. base.html: <!-- ...code... --> <script> function registration(){ if(document.getElementById("registration").className==='hide'){ document.getElementById("registration").className='show' }else{ document.getElementById("registration").className='hide' } } </script> another template {% extends 'base.html' %} {% block body %} <script> //if i re write the function here, it works registration() </script> {% endblock body %} -
Using Celery, execute a list of URLs in a single celery task. Is it Possible?
views.py urls=["https//:.....com,https//:.....com,etc.."] for i in urls: r=process.delay(i) When I'm calling the celery task it execute separate task. How to execute the set of lists in a single celery task? tasks.py @app.task def process(url): r = requests.get(url, allow_redirects=True) return r -
Django returning dictionary from front end?
I'm passing a dictionary from the front end to the back end in one of my Django views. The setup is something like this: $.ajax({ type: "POST", url: '/my/url', data: { 'patients': '{{ appointments.appointments.items }}' }, dataType: 'json', async: false, success: function (data) { console.log("yay") } }); which is passing back an dictionary of names, etc. and I'm then retrieving this on the python backend, like so: if request.method == "POST": patients = request.POST.get("patients", None) print("patients are", patients) However, when I do this and print out the patients dict() instead of getting an actual dictionary, I get a string like this: dict_items([(153, {&#x27;person&#x27;: &#x27;Samuel&#x27;, &#x27;time&#x27;: datetime.datetime(2021, 4, 22, 17, 0, tzinfo=&lt;UTC&gt;), &#x27;number&#x27;: &#x27;First&#x27;})]) that doesn't follow the dictionary format/even really allow for json parsing etc. Is there something I'm doing wrong here? The {{appointments.appointments.items}} is just passed into my HTML template page from the backend during the get request and I'm accessing it with JavaScript in the same file. Any advice here would be appreciated. -
How to access serialize method from another model?
I'm trying to show on my DOM the number of followers and following, I have made a new model called Profile, I want to send JSON data from my views function using the serialize method in the Profile model, but how can I access the method in the Profile model from the User model? In my views.py (display_profile function) I'm trying to send JSON data, How can I access the serialize method in Profile Model, from the User model? models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def serialize(self): return { "id": self.id, "poster": self.poster.username, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) following = models.ManyToManyField(User, blank=True, related_name="following") followers = models.ManyToManyField(User, blank=True, related_name="followers") def serialize(self): return { "profileID": self.user.id, "following": int(self.following.all().count()), "followers": int(self.followers.all().count()), } views.py def display_profile(request, profile): try: profile_to_display = User.objects.get(username=profile) profile_to_display_id = User.objects.get(pk=profile_to_display.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) # Return profile contents if request.method == "GET": return JsonResponse(profile_to_display.serialize(), safe=False) else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) index.js function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; … -
How to add a row to a database only if certain constraints are satisfied
I have a question bank and an application that can create tests. The application allows adding questions from the question bank to a test (make a copy from the question bank to a test) or adding (creating) a question directly in the test. Multiple people can add questions to a given test. I want to ensure the following: The number of questions in a test do not cross a given fixed limit. No duplicate questions are added from the question bank to a test. There are tables for the following: Questions of the question bank Questions that are in a test (has a reference to the question in the bank) Tests How can I ensure the constraints? I am trying to do this in Django and MySQL. And I will not be abe to add a unique_together constraint for the parent_question_id and test_id (due to certain limitations that I can add if and when required to answer this question)