Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.2 aws beanstalk can't load static file
I have website on aws beanstalk with nginx . When i push my code i can't load css and js .I have this erreur MIME (« text/html ») incorrect (X-Content-Type-Options: nosniff) i follow this tuto Deploying a Django application to Elastic Beanstalk on my code i have this STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) else: STATIC_ROOT = os.path.join(BASE_DIR, "static") and i run before push on prod python manage.py collectstatic for my beanstalk conf WSGIPath:mysite.wsgi:application DJANGO_SETTINGS_MODULE:mysite.settings -
Executing Python script on dropdown change in Django?
I have a simple Python script, simple_script.py that simply prints a string with the current datetime: import datetime print(f"Current time is: {datetime.datetime.now()}") The script file is placed in a folder called scripts in the django projet's main folder. On the site, I merely have a dropdown field (<select>) and a button. I want to have this script run every time the user changes the dropdown field, i.e. without the need to press the button (the button won't even be necessary - it's only here for demonstration purposes). I managed to implement the version where running the script depends on pressing the button. My home.html: <form action="/external/" method="post"> {% csrf_token %} <select> <option>---</option> <option>1</option> <option>2</option> <option>3</option> </select><br><br> {{data1}}<br><br> <input type="submit" value="Execute Custom Py Script"> </form> My views.py: import sys from django.shortcuts import render from subprocess import run, PIPE def external(request): out = run([sys.executable, "scripts/simple_script.py"], shell=False, stdout=PIPE) return render(request, 'appName/home.html', {'data1': out.stdout.decode('utf-8')}) And I added the following path declaration to my url.py: path('external/', views.external, name='external'), Right now, upon pressing the button, the {{data1}} tag gets filled up with the string returned from simple_script.py. To get to my goal, I realize I likely need JavaScript, so I added an onChange attribute to the … -
Django test validation isdigit
How to test ValidationError when User inserts Text for my zip code example? This is my validation in my models.py file: def validate_zip_code(value): zip = str(value) if not zip.isdigit(): raise ValidationError('Please enter a valid zip code.') And my test file in test_models.py class TestPLZ(TestCase): def test_zip_code_digit(self): self.assertRaises(ValidationError, validate_zip_code, 'Random Text') Running python.manage.py test I get no Errors, but when I run coverage html I can tell that this function has not been tested properly. -
Django Button to Update 'status' / BooleanField on Database
i have this model in order apps class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='items', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='items', on_delete=models.CASCADE) vendor_paid = models.BooleanField(default = False) price = models.DecimalField(max_digits=16, decimal_places=0) quantity = models.IntegerField(default=1) def __str__(self): return '%s' % self.id def get_total_price(self): return self.price * self.quantity i have this button in vendor apps in vendor_admin.html <a href="{% url 'status_update' %}" class="button is-success is-uppercase">Confirm</a> i want to update the vendor_paid = models.BooleanField(default = False) from false to true when i click that button. the problem is i dont know what to write inside def in vendor views.py @login_required def status_update(request): ? return redirect('vendor_admin') -
Using UUID in View_Detail page in Django
I have an app that is working fine, but i just changed the ID to UUIDm and the route no longer work. I have the following route: path("documents/uuid:uuid/",views.document_show, name="document_show"), and the following view: def document_show(request, id): student_list = DocumentAttachment.objects.all() for student in student_list: print("we are printing the list of imaged uploaded :", student.attachment) context = {} try: context["data"] = Document.objects.get(id=id) except Document.DoesNotExist: raise Http404('Book does not exist') return render(request, "documents/show.html", context) With the architecture: template/documents/show.html May I ask what is the right way to setup the routes please? -
Django Q Tasks - putting Q_CLUSTER outside settings file
Hi/I am new in this useful library. What I need to do is using Q_CLUSTER dictionary values outside of (let's say) plain old settings.py (Because of a necessity to change these values in demand in different setting files) . The problem is 'C:\Python38\Lib\site-packages\django_q\conf.py' is being loaded long before the application is being executed and inside this conf.py file there are q_cluster assignments to settings.py such as : class Conf: """ Configuration class """ try: conf = settings.Q_CLUSTER except AttributeError: conf = {} Does anyone have idea how I can manage this task without changing site packages? Thanks in advance for help -
Why is django getting stuck on loading a template that doesn't exist?
I've made some changes to my website's theme and have come across an issue. My previous landing page was called home.html. It worked fine. I have since changed it, retired the old pages (moved them to another folder), and put a new set of pages in my template/app/ folder. The new landing page is index.html. I have changed it in urls.py, and in views.py. I come across this error, Django still wants to access or load main/home.html. I don't understand why, even after changing it to return a HttpResponse, it still wants to render a template? What's going on? Environment: Request Method: GET Request URL: https://website.com Django Version: 3.1.4 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/admin/templates/main/home.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.6/dist-packages/django/contrib/auth/templates/main/home.html (Source does not exist) * django.template.loaders.app_directories.Loader: /var/www/app/main/templates/main/home.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/app/main/views.py", line 103, in homepage return HttpResponse("well?") File "/usr/local/lib/python3.6/dist-packages/django/shortcuts.py", … -
Use FactoryBoy's Maybe declaration without a "decider" model field
Is it possible to use FactoryBoy.Maybe where the "decider" does not map to an actual model field? Consider the following model: class MyModel(models.Model): is_heavy = models.BooleanField() weight = models.PositiveIntegerField() This factory works: class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel is_heavy = factory.Faker("boolean", chance_of_getting_true=50) weight = factory.Maybe( "is_heavy", yes_declaration=factory.Faker("pyint", min_value=0, max_value="10"), no_declaration=factory.Faker("pyint", min_value=10, max_value="20"), ) But what if I don't want the "decider" to map to an actual field of MyModel? Something like: class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel is_heavy = factory.Faker("boolean", chance_of_getting_true=50) weight = factory.Maybe( factory.Faker("boolean", chance_of_getting_true=50), yes_declaration=factory.Faker("pyint", min_value=0, max_value="10"), no_declaration=factory.Faker("pyint", min_value=10, max_value="20"), ) That factory doesn't work. (Note that it used to work prior to this version and this PR.) -
Using BeautifulSoup for web scraping: ValueError obtained
This is my first time asking a question on this platform. I have the following error: ValueError at /scrape/ dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://localhost:8000/scrape/ Django Version: 2.2.17 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 1; 2 is required Exception Location: c:\Users\toshiba\Desktop\newsscraper\news\views.py in scrape, line 32 Python Executable: C:\Users\toshiba\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.2 Python Path: ['c:\Users\toshiba\Desktop\newsscraper', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\win32', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\win32\lib', 'C:\Users\toshiba\AppData\Local\Programs\Python\Python37\lib\site-packages\Pythonwin'] I am trying to scrape news articles from guardian.ng, but it seems to keep giving me an error. This is my views.py file: # import all necessary modules import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup as BSoup from news.models import Headline requests.packages.urllib3.disable_warnings() # new function news_list() def news_list(request): headlines = Headline.objects.all()[::-1] context = { 'object_list': headlines, } return render(request, "news/home.html", context) # the view function scrape() def scrape(request): session = requests.Session() session.headers = {"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"} # This HTTP header will tell the server information about the client. We are using Google bots for that purpose. # # When our client requests anything on the server, the server sees our request coming as a Google bot. url … -
How to update model's property value in Django's shell?
I have a such a model: class Territory(models.Model): voivodeship = models.IntegerField(null=True, blank=True) powiat = models.IntegerField(null=True, blank=True) gmina = models.IntegerField(null=True, blank=True) type = models.IntegerField(null=True, blank=True) name = models.CharField(max_length=500) type_name = models.CharField(max_length=100) comparison_group = models.ForeignKey(ComparisonGroup, on_delete=models.SET_NULL, related_name='territories', null=True, blank=True) partnership = models.ForeignKey(Partnership, on_delete=models.SET_NULL, related_name='member_territories', null=True, blank=True) class Meta: unique_together = ('voivodeship', 'powiat', 'gmina', 'type') verbose_name = 'Jednostka terytorialna' verbose_name_plural = 'Jednostki terytorialne' def __str__(self): return f'{self.name} - {self.type_name} ({self.code})' @property def code(self): if self.voivodeship and self.powiat and self.gmina and self.type: return f'{self.voivodeship:02}{self.powiat:02}{self.gmina:02}{self.type}' return '--' And now some of those Territories have code attribute as --, because self.gmina and self.type were NULL in the DB. Then I updated some rows -- added values for self.gmina and self.type for some of the territories units and I want to update their code attributes. I tried: territories = Territory.objects.filter(type_name='some type name') for t in territories: t.code = <some calculated value> but I get an error kind of: Traceback (most recent call last): File "<console>", line 3, in <module> AttributeError: can't set attribute How can I make Django recalculate this code value for all items in Territory model? -
Trying to upload a file via api
I want to programmatically upload a pdf file to an APP via API, from a Python + Django APP. Their documentation says: “In order to upload an invoice you must do a POST as from.data with key type “file” and value fiscal_document that refers to the file you are attaching.” curl -X POST https://api.mercadolibre.com/packs/$PACK_ID/fiscal_documents -H 'Content-Type: multipart/form-data' \ -H 'Authorization: Bearer $ACCESS_TOKEN' \ -F 'fiscal_document=@/home/user/.../Factura_adjunta.pdf' I´m trying to achieve this using requests as follows: response = requests.request("POST", url, headers=headers, files={'fiscal_document': my_file_url}).json() But I get the following response { "message": "File cannot be empty", "error": "bad_request", "status": 400, "cause": [] } Is my request call ok? In the example there is a local path declared, but I need to get the file from an URL. Should I keep the “@” in the -F 'fiscal_document=@/home/user/.../Factura_adjunta.pdf'? Should I upload a byte type? And clues welcome. Thanks in advance. -
Postman giving "Invalid pk \"1\" - object does not exist."
I'm making a post request to a django server using Postman. But i'm getting the following error [ { "question": [ "Invalid pk \"1\" - object does not exist." ] } ] The object exists with pk = 1. I don't know why postman adds the " in the request and maybe that what causes this. Can you please tell me how to take off the "\ from it. Here is my request : {"user":1,"form":2,"completed_at":"2018-09-04T00:00:00+0100","device_id":5,"responses":[{"resourcetype":"ShortTextResponse","question":1}]} -
AttributeError: module 'users_data.models' has no attribute 'random_string'
When I try to change function name it shows me the error in the command line: AttributeError: module 'users_data.models' has no attribute 'random_string'enter image description here -
Passing foreign key through url with Django
I'm building an app using django in the backend and vuejs in the frontend. I'm stuck with the following: After showing the categories, if the user clicks on one category, I want to display all the extras and menus related to the choosen category. I have declared category_id as a foreign key within the Product model as shown here: from django.db import models from django.contrib.auth.models import * class Category(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) category_des = models.CharField(max_length=250) class Type(models.Model): type_des = models.CharField(max_length=250) class Product(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) type_id = models.ForeignKey(Type, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_price = models.FloatField() The views: from rest_framework import generics from .import models from .import serializers class CategoryList(generics.ListCreateAPIView): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class CategoryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer class MenuList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=1) serializer_class = serializers.ProductSerializer class MenuDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=1) serializer_class = serializers.ProductSerializer class ExtraList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=2) serializer_class = serializers.ProductSerializer class ExtraDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=2) serializer_class = serializers.ProductSerializer urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from fastfood_app import views urlpatterns = [ path('Menu/', views.MenuList.as_view()), path('Menu/<int:pk>/', views.MenuDetail.as_view()), path('Extra/', views.ExtraList.as_view()), path('Extra/<int:pk>/', views.ExtraDetail.as_view()), path('Category/', views.CategoryList.as_view()), path('Category/<int:pk>/', views.CategoryDetail.as_view()), ] Here is the vue page in the frontend: <template> <div … -
Data not passed when using HttpResponseRedirect in DJANGO
i am using Django redirect , currently it is redirecting to the page , but am not able to pass the data from views --> template . i tried different methods checking youtube and stackoverflow questions but nothing worked , below is my code def Dashboard(request): status = output['status'] if(status == 'success'): msg = output['id'] else: msg = output['error'] return HttpResponseRedirect(reverse('AllOrders', kwargs={'status':status,'msg':msg})) and here is how i fetch it in template: div class="col-span-12 mt-8"> {% if kwargs.status == "success" %} <div class="alert alert-outline-success alert-dismissible show flex items-center mb-2" role="alert"> {{kwargs.status}}</div> {% endif %} and this shows me INTERNAL SERVER ERROR , but if i remove passing arguments , everything works fine , Can anyone help me in this -
pull audio file from django backend in vuejs
I am trying to build an app that would transfer recorder audios from the vuejs front end to my django back end and get them back. However I have troubles with both ways: front -> backend : my audios recordings are 'blobs' format. Should I 'send' in vue to django the entire blob and django would store it or would I juste create an url and vue would store the file on the server ? backend -> front : I try to display an audio by putting in the url of where I stored them, however I keep having 404 errors... Here is my django audio models.py: class Audio(models.Model): id = models.SlugField(max_length = 6, primary_key = True, unique = True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room = models.ForeignKey(settings.AUTH_ROOM_MODEL, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, help_text="timestamp of the audio") audiofile = models.FileField(upload_to='recordings/%Y/%m/%d') def __str__(self): return str(self.audiofile) def __str__(self): return f"{self.id} ({self.user})" Here is my vue, where I want to display audios: onResult() { var div = document.getElementById("audiosContainer"); var link = document.createElement("link"); link.rel = "stylesheet"; link.href = this.audios[0].audiofile; // here http://localhost:8000/files/recordings/2021/05/04/file_example_MP3 div.innerHTML += '<audio controls name="media"><source src="' + link.href + '" type="audio/wav"></audio>'; }, my django python view: class AudioView(APIView): def get(self, request): all_audios = Audio.objects.all().order_by("id") … -
How to use function of order_set if I am using filter instead of get?
When I use get instead of filter in views.py, I get error saying customer object isn't iterable, which I understand. But using filter instead of get doesn't allow me to user 'order_set' function (also in views.py), showing up with an error message: 'QuerySet' object has no attribute 'order_set'. How can I workaround this? views.py def customer(request, pk): customer = Customer.objects.filter(id=pk) order = customer.order_set.all() context = {'customer': customer, 'order':order} return render(request, 'accounts/customer.html', context) customer.html <table> <tr> <th>Email</th> <th>Phone</th> </tr> {% for i in customer %} <tr> <th> {{i.email}}</th> <th> {{i.phone}}</th> </tr> {% endfor %} </table> <table class="table table-sm"> <tr> <th>Product</th> <th>Category</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {%for order in order%} <tr> <td>{{order.product}}</td> <td>{{order.product.category}}</td> <!-- the above is chaining --> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a href="">Update</a></td> <td><a href="">Remove</a></td> </tr> {% endfor %} </table> urls.py urlpatterns = [ path('', views.home), path('products/', views.products), path('customer/<str:pk>', views.customer) ] -
Django pass context to a nested ModelSerializer
I have a Foo serializer inside a Bar serializer. I want to pass the context request to Foo serializer so I can make a valid url of Foo object. class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() def to_internal_value(self, data): # Save depending on name foo = Foo.objects.get(name=data) return {'foo': foo} def to_representation(self, instance): request = self.context.get('request') # Get request from BarSerializer name = instance.foo.name link = request.build_absolute_uri( '/apps/foo/{}'.format(instance.foo.id)) return {'name': name, 'link': link} class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') How do I pass the context request from one serializer to another? -
Mark all duplications in annotations
I have a model: class Order(models.Model): data = models.TextField() sessionid = models.CharField(max_length=40) I need to get queryset where every unique sessionid will be masked as name or something. For example if I have 3 objects { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "foo" }, { "data": "...", "session_id": "bar" } query should annotate each unique session_id to return: { "data": "...", "name": "A" }, { "data": "...", "name": "A" }, { "data": "...", "name": "B" } How could I make this query? Thanks! -
how to join 3 tbales with django?
i need to join 3 tables using django , here is my problem a super user can create a Project and assign users to it a Project contains a Tasks each user have specific tasks under a projects thanks a lot ! class Project(models.Model): name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=50, choices=CATEGORY, null=True) users = models.ManyToManyField(User,db_table='users_to_mission') superuser = models.ForeignKey(User,on_delete=models.CASCADE, related_name='created_by') def __str__(self): return f'{self.name}' class TaskList (models.Model): title =models.CharField(max_length=1000, null=True) def __str__(self): return f'{self.titre}' class Tasks (models.Model): titre = models.ManyToManyField(TaskList) project = models.ForeignKey(Project , on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user') def __str__(self): return f'{self.titre}' -
Test Concurrent Clients in Django's TestCase
I want to test the performance of Django when a number of clients making requests concurrently. I had no luck using Python's multiprocessing package in a TransactionTestCase case but got it to work using threading, like this: class UserRegisterTestCase(TransactionTestCase): NUM_PROCS = 5 @staticmethod def register(): email = '{}@test.com'.format(threading.get_ident()) c = Client() c.post(reverse('my_login'), {'action': 'register', 'email': email, 'password_1': '12345', 'password_2': '12345'}) connection.close() def test_register(self): threads = [] for i in range(self.NUM_PROCS): threads.append(threading.Thread(target=self.register)) for t in threads: t.start() for t in threads: t.join() self.assertEqual(MyClients.objects.count(), self.NUM_PROCS) The test passed, but I wonder with Python's GIL, is it true that 5 concurrent clients are trying to register at the same time, or is it just some syntactic sugar in that under the hood, Django sees and handles one client request at a time? If latter is the case, what's the right way to test for concurrent clients? Thanks. -
django: FOREIGN KEY constraint failed
In my django project when I'm trying to add a faculty it throws a "FOREIGN KEY constraint failed" error. Here I'm trying to save the faculty under the institute and all the roles have a user login which is linked with a one to one field models.py : class CustomUser(AbstractBaseUser): is_admin = models.BooleanField(default=False) is_institute = models.BooleanField(default=False) is_faculty = models.BooleanField(default=False) is_student = models.BooleanField(default=False) user_email = models.EmailField(verbose_name='Email',primary_key=True,unique=True) date_created = models.DateTimeField(verbose_name='date created', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) user_image = models.ImageField(upload_to='profile_images',null=True,blank=True) USERNAME_FIELD = 'user_email' class Institute(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) institute_name = models.CharField(max_length=75,verbose_name="Institute Name",null=True,blank=True) institute_address = models.TextField(max_length=100,verbose_name="Address",null=True,blank=True) institute_number = models.PositiveBigIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute_id = models.IntegerField(unique=True,verbose_name="Institute Id",null=True,blank=True) class Faculty(models.Model): user = models.OneToOneField('CustomUser',primary_key=True,on_delete=models.CASCADE) faculty_id = models.CharField(max_length=75,verbose_name="Faculty Id",null=True,blank=True) first_name = models.CharField(max_length=75,verbose_name="First Name",null=True,blank=True) last_name = models.CharField(max_length=75,verbose_name="Last Name",null=True,blank=True) faculty_number = models.PositiveIntegerField(verbose_name="Mobile Number",null=True,blank=True) institute = models.ForeignKey('Institute',on_delete=models.CASCADE) class Meta: unique_together = [['faculty_id','institute']] views.py add faculty function: def addFaculty(request): if request.method == "POST": user = CustomUser.objects.create_user(user_email=request.POST.get('user_email'),role="faculty",password=request.POST.get('password')) user.save() Faculty.objects.create(user=user,faculty_id=request.POST.get('faculty_id'),faculty_number=request.POST.get('faculty_number'),first_name=request.POST.get('first_name'),last_name=request.POST.get('last_name'),institute=Institute(user=request.user)).save() return redirect('dashboard') else: extraFields = [ { 'label':"First Name", 'name':'first_name', 'type':'text' }, { 'label':"Last Name", 'name':'last_name', 'type':'text' }, { 'label':"Faculty Id", 'name':'faculty_id', 'type':'number' }, { 'label':"Faculty Number", 'name':'faculty_number', 'type':'number' } ] return render(request,'learnerApp/addUser.html',context={'extraFields':extraFields}) -
Django Dynamic MySQL Table Creation
How to create Dynamic MySQL Database Table in Django? Suppose I create a table 'surveys'. Enter a survey 'Student Survey' which has id '1' in 'surveys' table. I want to create 'response_1' table for saving the responses. Enter a survey 'Employee Survey' which has id '2' in 'surveys' table. 'response_2' table for saving the responses. Enter a survey 'Job Survey' which has id '3' in 'surveys' table. 'response_3' table for saving the responses. And so on.. Please help.. Thank you. -
Python unittest and coverage missing not working
I have the following function: def edge_delete_check(id: str) -> bool: queryset = NsRequestRegistry.objects.filter( **{ 'nsr_insd__constituent-isd__contains': [ {'id': id} ] } ) if not queryset: return True else: return False And when I run my tests, coverage tells me that i'm missing on return False. So I've been trying to run a test that tests the False condition on my function above. class HelperTests(unittest.TestCase): """Tests helper functions""" def test_edge_delete_check_false(self): result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd') self.assertTrue(result, False) The given id should return a False for result = edge_delete_check('e932bb55-44cb-4ec4-a0cb-1749fe51e5fd'), which it does, which means the given id can not be deleted as queryset in the function above returned a non-empty result. But doing a self.assertFalse(result, False) throws an AssertionError: True is not false : False. If I change my assert to: self.assertTrue(result, False) the test passes but the coverage report still says that my return False on my function is missing. So the two questions I have are: How should I write my test to test the return false statement on my function above? How can I get coverage to report that it has tested the return false statement and is no longer missing? Thanks for any help. -
How to handle patch method in AJAX?
How to handle the patch method from AJAX. My backend is written in Django rest API.Im using model viewsets.Backend view as below: class ProductAPI(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = ProductTbl.objects.all() @action(detail=False, methods=['PATCH']) def get_object(self,*args,**kwargs): return get_object_or_404(**kwargs) def update_product(self,request,pk): try: product_obj = self.get_obj(pk=pk) serializer = self.serializer_class(product_obj,data = request.data, partial = True) if serializer.is_valid(): serializer.save() return Response({},status = 200) return Response(serializer.errors,status = 400) except Exception as e: return Response({},status = 500) urls.py path('product/edit/<int:pk>/', ProductAPI.as_view({'patch': 'update_product'}), name='update_products'), my ajax code as follows: var form = new FormData($("#update_form")[0]) $.ajax({ type:"PATCH", url : "/product/edit/1", data:form, success:function(data){ }, error:function(data){ } }) Still, I'm getting error 405.Method not allowed...