Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery with Rabbit MQ Virtual Host not accepting tasks from app.tasks.py in Django
Help needed! PS: I have already created Virtual Hosts using this link Celery and Vhosts settings.py CELERY_BROKER_URL = 'amqp://flash:flash_education@localhost:5672/flash' celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery( 'flash_education', namespace='CELERY', ) app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app1.tasks.py import datetime import json from celery import shared_task @shared_task(name="ping") def ping(): print("pong") Attaching images from my terminal, one of of the worker instance other is of the shell from which I am firing the tasks. Note: I started both after settings and all but it does not seem to work Worker terminal Screenshot shell instance firing the request RabbitMQ, Celery==4.4.2 Django==3.0.4 Please help! -
Django filter records depending on associations
I am building a Django site and I want to filter the records depending on what option the user chooses. For example, if the user picked python then all subjects related to python (Pandas, Django) should be displayed. At the moment it shows all the records in the subject database irrelevant of what option I pick. If the user picks python it will show pandas, Django, Angular, Sprint etc. I have added my views, models and URLs page to this git gist https://gist.github.com/gentaro87/f49983178c7f01648f1f457eaf749678 Additionally, I have also tried to change subject_menu @login_required def subject_menu(request, topic): topics_ids = Profile.objects.all().values_list('topic', flat=True).distinct() topics = Subject.objects.filter(topic__id__in=topics_ids) return render(request, "skills/subject_menu.html", { 'topics': topics }) to this topics = Subject.objects.filter(profiles__topic_set__name__slug=topic) but also no luck -
Deleting Objects with Django Delete
I have an issue deleting just a single object from my database, I have a code that gets a list of RDS hostnames from AWS and then compares the rds hostnames stored in my Database to that returned by AWS, if the rds hostname is stored in my DB and not returned by AWS it should be removed from my database, but my code eventually ends up removing all the RDS hostnames stored in my DB Here is my models class AwsAssets(BaseModel): aws_access_token = models.CharField(max_length=512, blank=True, null=True) aws_secret_token = models.CharField(max_length=512, blank=True, null=True) rds_count = models.IntegerField(blank=True, null=True) def __str__(self): return '{} - {}'.format( self.client_aws_access_token, self.client_aws_secret_token ) class Meta: verbose_name_plural = "Aws Assets" class AwsRdsNames(BaseModel): host = models.CharField(max_length=300, null=True, blank=True) port = models.IntegerField(null=True, blank=True) asset_link = models.ForeignKey(AwsAssets, null=True, blank=True, related_name="rds_endpoints", on_delete=models.CASCADE ) region = models.CharField(max_length=56, null=True, blank=True) scan_status = models.NullBooleanField(default=None) last_scan = models.DateTimeField(null=True, blank=True) def __str__(self): return "{}:{}".format(self.host, self.port) class Meta: db_table = 'aws_rds_names' ordering = ['-id'] and then here is the block of code responsible for deleting the rds hostnames all_stored_rds = AwsRdsNames.objects.all() stored_rds = all_stored_rds.filter(asset_link=self.asset) #This returns all the stored rds hosts in db aws_rds = get_rds() #This returns a list of rds hostname from aws for rds in stored_rds: … -
Cannot Redirect to other page
I am writing a view that retrieve an answer from game2.html, if the answer is correct, the view will redirect user to correct.html, if the answer is incorrect, then user will be redirected to incorrect.html. The problem now is after clicking the submit button, user won't be redirected. How do I solve it? morse_logs/views.py @login_required() def game2(request): """The Game2 page""" if request.user and not request.user.is_anonymous: user = request.user user_score, created = userScore.objects.get_or_create(user=user) ans1 = request.GET.get('ans1', '') if ans1 == '': ans1 = 0 if ans1 == 4: #user's score declared in model increase 5points #display correct and 5 points added to user user_score.score += 5 user_score.save() return redirect('morse_logs:correct.html') else: #user's score declared in model has no point #display incorrect and 0 point added to user return redirect('morse_logs:incorrect.html') return render(request, 'morse_logs/game2.html') @login_required() def correct(request): """The answer correct page""" return render(request, 'morse_logs/correct.html') @login_required() def incorrect(request): """The answer incorrect page""" return render(request, 'morse_logs/incorrect.html') game2.html {% extends "morse_logs/base.html" %} {% block content %} <title>GAME 2</title> <div> <h1>GAME 2</h1> <h2>2 + 2 = ?</h2> <form action="" method="get" > <input type="number" id="ans1" name="ans1"/><br><br> <input type="submit" name="game1Answer"/> </form> </div> {% endblock content %} -
I want to reverse these items in the context
I want my items to be displayed in the reverse order in the template here is my views.py @login_required(login_url='/customer/login/') def myorders(request): orders = OrderModel.objects.filter(cid = request.user.id) items = {} i = 0 for item in OrderModel.objects.filter(cid = request.user.id): items[item.id] = { "ordered_items" : item.items, "price":item.price, "address":AddressModel.objects.filter(userid = request.user.id)[i].address, "approval_status":item.approval_status } i = i + 1; context = {'items' : items} return render(request,"gupsupapp/myorders.html",context) -
Nested Loops in Django
I have in my models Projects and Tasks. I'd like to display on the template: Project 1 Task 1:1 Task 1:2 Task 1:n Project 2 Task 2:1 Task 2:n Project n Here's the model class Projects(models.Model): slug_project = models.CharField(max_length=200) project_name = models.CharField(max_length=200) project_due_date = models.DateTimeField() project_lead_time = models.IntegerField() project_assignee = models.CharField(max_length=200) project_status = models.CharField(max_length=200) def __str__(self): return self.project_name class Tasks(models.Model): slug_task = models.CharField(max_length=200) task_name = models.CharField(max_length=200) task_desc = models.TextField(null=True) task_channel = models.CharField(max_length=200) task_id = models.ForeignKey(Projects, on_delete=models.CASCADE) task_due_date = models.DateTimeField('Due Date') task_lead_time = models.IntegerField() task_assignee = models.CharField(max_length=200) def __str__(self): return self.task_name I'm not sure how to construct the view properly but here's my code: class mainPage(generic.ListView): template_name = 'dashboard/index.html' context_object_name = 'project_object' def get_queryset(self): """Return the last five published Coupons.""" return Projects.objects.order_by('project_name') def get_context_data(self, **kwargs): context = super(somePage, self).get_context_data(**kwargs) # context['tasks'] = Tasks.objects.order_by('task_name') #this would display ALL tasks context.update({ 'all_project': Projects.objects.all(), 'all_tasks': Tasks.objects.filter(task__id=self.object), }) return context And I'm also not confident how construct the template: {% if project_object %} {% for project_name in project_object %} <div class="card_row_h1"> <a href="{% url 'dashboard:task_list' project_name.id %}"> {{ project_name }} </a> </div> {% if all_tasks %} {% for task_name in tasks %} <div class="card_row_h2" style="width: 100%; padding-left: 30px;"> <small>{{ task_name }}</small> </div> {% endfor %} … -
Django admin page autocomplete doesn't work
I have models like this: Models class Customer(models.Model): customer_ref = models.CharField(unique=True, max_length=50) name = models.CharField(null=False, max_length=80) country = models.CharField(null=True, max_length=50) class Assortment(models.Model): name = models.CharField(null=False, max_length=50) customers = models.ManyToManyField(Customer, related_name='assortments', blank=True) products = models.ManyToManyField(Product, related_name='assortments', blank=True) class Subsidiary(models.Model): subsidiary_ref = models.CharField(unique=True, max_length=50) name = models.CharField(null=False, max_length=80) address = models.TextField(null=True) city = models.CharField(null=True, max_length=50) coordinates_x = models.DecimalField(null=True, decimal_places=2, max_digits=6) coordinates_y = models.DecimalField(null=True, decimal_places=2, max_digits=6) phone_number = models.CharField(null=True, max_length=50) frequency = models.ForeignKey(Frequency, on_delete=models.SET_NULL, null=True) channel = models.CharField(null=True, blank=True, max_length=50) subchannel = models.CharField(null=True, blank=True, max_length=50) user = models.ForeignKey(User, related_name='subsidiaries', on_delete=models.SET_NULL, null=True) day_planned = models.BooleanField(default=False) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='subsidiaries') class Asset(models.Model): identification = models.CharField(unique=True, max_length=50) serial = models.CharField(max_length=50) name = models.CharField(null=True, max_length=50) subsidiary = models.ForeignKey(Subsidiary, related_name='assets', null=True, blank=True, on_delete=models.DO_NOTHING) Admin @admin.register(Customer) class CustomerAdmin(admin.ModelAdmin): list_display = ['customer_ref', 'name', 'country'] list_filter = ['country'] autocomplete_fields = ['assortments'] @admin.register(Subsidiary) class SubsidiaryAdmin(admin.ModelAdmin): exclude = ['day_planned'] list_display = ['subsidiary_ref', 'customer', 'name', 'address', 'phone_number', 'frequency', 'user'] list_editable = ['frequency', 'user'] list_filter = ['frequency', 'user'] search_fields = ['subsidiary_ref', 'customer__name', 'name'] autocomplete_fields = ['assets'] CustomerAdmin is 'working' without error but field 'assortments' is not visible. SubsidiaryAdmin throws error : <class 'mobileapp.admin.SubsidiaryAdmin'>: (admin.E038) The value of 'autocomplete_fields[0]' must be a foreign key or a many-to-many field. witch is weird because I don't see … -
List of operation model is storing empty
enter image description here model.py enter image description hereack.imgur.com/rG6eW.png serlizer.py view.py postman respose -
Django. URLconfs. How can I refer to my view function in URLconfs with argument in a template
What is the correct way to create a link in a template to my view function. The parameter x_variable="12345" is a variable. urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls.i18n import i18n_patterns from .decorators import check_recaptcha app_name = 'rsf' urlpatterns = [ .... re_path(r'^quotation/([0-9])/$', views.quotation, name='quotation'), .... ] template.html {% extends 'base.html' %} {% load i18n %} the link to the inquiry is: <a href = {% url 'rsf:quotaion/12345/' %}>LINK</a>. the link to the inquiry is: <a href = {% url 'rsf:quotaion/{{x_variable}}' %}>LINK</a>. ... I have tried both ways as above and have no other ideas. Thank you -
union of django querysets duplicates item
I'm creating a union of QuerySets and something doesn't add up. For some reason, one element gets duplicated. I'm printing: print(len(one), len(two), len(one | two), len((one | two).distinct())) I get: 8 42 51 50 How is that possible!? -
NoReverseMatch at /accounts/login/ Dajngo 3.0
I get the this error while developing my django 3.0 app, but only when I try to login with the superuser. NoReverseMatch at /accounts/login/ Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. Exception Location: /Users/project/ven/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 676 Python Executable: /Users/project/ven/bin/python Python Version: 3.7.1 I have looked up these answers but they did not solved my question: NoReverseMatch at /account/login/ django-registration - NoReverseMatch at /accounts/login/at /accounts/login/ -
How can one securely deploy a django app on-premise?
As the title says, I'm building a python web app (django inside docker + postgresql docker) for a company that I deployed on their server. Now one of their clients asks them if they can run it on his own server (for data privacy issues). So the company asks if it's possible to do that without giving him access to the source code? The problem being that python code is not compiled and is plain text that anyone can read. Is there any solution to this ? Thank you ! -
How do I migrate in Heroku?
so I have a Django application and completed all the deployment with Heroku. However I realized that all the data from my database weren't migrated. When I go into /admin in my heroku application, I do see the models are there, but empty. I've done the heroku run python manage.py migrate command, but it got me an error that says: bash: manage.py: command not found. What is the problem? -
How to solve filer and sites dependencies problem in my project
Currently I have started working on Django project given by me for learning purpose. I have done all kind of necessary setup in my virtualenv and when running migrate command on my project I am getting below kind of dependencies problems as below. I have tried to find solution online and django doc but clueless. Traceback Traceback (most recent call last): File "manage.py", line 40, in <module> execute_from_command_line(sys.argv) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 306, in build_graph _reraise_missing_dependency(migration, parent, e) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 276, in _reraise_missing_dependency raise exc File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/loader.py", line 302, in build_graph self.graph.add_dependency(migration, key, parent) File "/home/moon/production/remax/remax_env/lib/python3.6/site-packages/django/db/migrations/graph.py", line 126, in add_dependency parent django.db.migrations.exceptions.NodeNotFoundError: Migration core.0002_auto_20200408_0215 dependencies reference nonexistent parent node ('filer', '0008_auto_20200408_0215') Snippet from migration file as below. 0002_auto_20200408_0215.py class Migration(migrations.Migration): dependencies = [ ('filer', '0008_auto_20200408_0215'), ('sites', '0003_auto_20200408_0215'), ('core', '0001_initial'), ] I have thought to comment dependencies lines from 0002_auto_20200408_0215.py files but my … -
Question regarding Form, View and dynamic queryset
Hey guys I have a question regarding form and queryset: Im creating a form where I select a faction from a list of factions. After the form is created, im redirect to another form where I can add soldiers to this list, but I see every soldiers of every factions in this form, I would like to be able to see ONLY soldiers of the faction I selected on the previous form. Can you help please on this please ? Im a bit lost on what to search for... My models: class Faction(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) race = models.ForeignKey(Race, on_delete=models.CASCADE,default=None, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) format_points = models.IntegerField() description = models.CharField(max_length=30) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class Soldier(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) points = models.IntegerField() factions = models.ManyToManyField(Faction) def __str__(self): return self.title class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) My views: class ListCreateFormView(CreateView): template_name = 'armybuilder_list_create.html' model = List form_class = CreateListForm def form_valid(self, form): form.instance.author = self.request.user form.instance.race = "toto" return super().form_valid(form) … -
How to test my business logic using Django and DRF without creating additional models that are used as references
I want to make bug-less code. I do the registration for applicants and application form that is divided by 3 blocks - personal data, application statement and admission documents. For each step there are additional requirements, for example if applicant didn't fill up personal info questionnaire the status of his application should "Without personal data" else "Awaits verification", on registration if applicant graduated school and wants to apply to Bachelor degree I have to check if there are admission campaign with bachelor preparation level and registration opened from 1 June til 1 July. If applicant applies earlier or later that period of time etc. The application forms are big and there should be some pre-populated data that applications refer to. This is how my test module looks like: import json import datetime as dt from rest_framework.test import APITestCase from organizations.models import Organization from portal_users.models import PhoneType from .models import * class ApplicantTestCase(APITestCase): # OBJ_RANGE - how many objects (records) to create (store at test DB) OBJ_RANGE = range(1, 7) # some refs must have dates and periods today = f'{dt.date.today()}' period = f'{dt.date.today() + dt.timedelta(days=365)}' def setup_refs(self): # Setting up reference models for questionnaire and application # in create_or_update there … -
Add a formatter (beautifier) to django-html files in Visual Studio Code
I'm using the Django extension for intellisense and syntax highlighting on Jinja templates (VS Code) but cannot figure out how to use my default formatter (HookyQR Beautify) to beautify/format my django-html files. Would that be possible? -
How can i run Django channels on production?
I deployed a simple Django app to a VPS, here is my environment: virtualenv gunicorn nginx systemd Everything works perfectly, i can see my template loading. I also added a small Django Channels feature, but that part doesn't work; so while i can use it on WSGI without any problem, if i try to reach a Consumer, i will get an error. So my question is: how can i run Channels too in production? Here is what i currently did: /etc/nginx/sites-available/myproject server { listen 80; server_name 54.39.20.155; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { include proxy_params; proxy_pass http://unix:/WaitingRoomVenv/WaitingRoomEnv.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/WaitingRoomVenv/WaitingRoomEnv.sock WR.wsgi:application [Install] WantedBy=multi-user.target To start gunicorn: sudo systemctl start gunicorn To start nginx: sudo systemctl restart nginx -
Add argument to all views without having to edit them all to include variable in Django
What I need I'm developing a Pull Notification System to an existing Django Project. With there begin over 100+ views I'm looking to find a way to incorporate a argument(notification queryset) into all the views, as this is rendered to my base.html which I can do by passing it into a view's arguments dictionary. Problem I want to do this without editing all of the views as this would take a long time and would be required for all future views to include this variable. What I've tried Creating a template filter and pass in request.user as variable to return notification for that user. This works, however when the user selects a 'New' notification I want to send a signal back to the server to both redirect them to the notification link and change the status of viewed to 'True' (POST or AJAX). Which would required that specific view to know how to handle that particular request. What I've considered • Editing the very core 'View' in Django. I've tried my best to explain the issue, but if further info is required feel free to ask. Thanks! -
TinyMCE GET 404
I installed TinyMCE and it was working fine on the local server. I deploy the site to Heroku and host the static files on Amazon S3 and now TinyMCE is not working. Other static files are served correctly. This is the Heroku log. 2020-04-15T07:19:17.547578+00:00 app[web.1]: - [15/Apr/2020:07:19:17 +0000] "GET /static/tiny_mce/tiny_mce.js HTTP/1.1" 404 3012 "https://...herokuapp.com/.../" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.39 Safari/537.36" This is the folder structure of my site: . ├── Procfile ├── db.sqlite3 ├── mysite │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media │ ├── images │ └── js ├── requirements.txt ├── runtime.txt ├── static │ └── readme.txt ├── staticfiles │ └── readme.txt └── myapp ├── __init__.py ├── __pycache__ ├── admin.py ├── apps.py ├── forms.py ├── migrations ├── models.py ├── static └── myapp └── tiny_mce ├── templates ├── tests.py ├── urls.py └── views.py This is my URL configs: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TINYMCE_JS_URL = os.path.join(STATIC_URL, "tiny_mce/tiny_mce.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tiny_mce") TINYMCE_DEFAULT_CONFIG = { 'theme': 'advanced', 'relative_urls': False, 'theme_advanced_buttons1': 'bold,italic,underline,bullist,numlist,link,unlink,styleselect,fontselect,fontsizeselect', } Any ideas? Thank you! -
Control object creation flow in Django inheritance models
I have been read some Django document about inheritance models and parent_link. Suppose that I have these models: class Parent(models.Model): #Some field goes here! class Child(Parent): #Some field goes here! I have 3 questions about this pattern: What should I do if I want to create new child object and pass id of existing parent to that? What should I do if I want to create just new child object and after a while create parent object for that child? Also I din't understand this document about parent_link: OneToOneField.parent_link When True and used in a model which inherits from another concrete model, indicates that this field should be used as the link back to the parent class, rather than the extra OneToOneField which would normally be implicitly created by subclassing. Thanks for your help! -
I'm trying to save django form in json format in mongodb without using models & model forms. My form is working, but I am stuck how to save the form
I want to save the form data submitted by the user in JSON format in mongo database. My form is getting submitted when I submit the form but I couldn't understand how to store the submitted form in MongoDB JSON format. Kindly do help with the supporting code. forms.py class appointment(forms.Form): name = forms.CharField(max_length=100, label="Name") gender = forms.ChoiceField(widget=forms.RadioSelect, choices=G_CHOICES) age = forms.CharField() phone_number = forms.CharField() email_id = forms.EmailField(max_length=250) country = CountryField().formfield() department = forms.ChoiceField(choices=D_CHOICES) reports = forms.ImageField() views.py def appointmentform(request): if request.method == "POST": form = appointment(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data) print(form.cleaned_data.get("name")) print(form.cleaned_data.get("gender")) print(form.cleaned_data.get("age")) print(form.cleaned_data.get("phone_number")) print(form.cleaned_data.get("country")) print(form.cleaned_data.get("department")) print(form.cleaned_data.get("reports")) form = appointment return render(request, "appointment.html", {"form": form}) -
Perform JOIN in tables django
Perform JOIN on in django fetching related date in reverse relationship. There are three models. Following is code for models class Question(models.Model): title = models.CharField(max_length=255 ) description = models.TextField(max_length=300) class Quiz(models.Model): name = models.CharField(max_length=225,blank=False ) quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0) questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category') class QuestionQuiz(models.Model): quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) correct =models.DecimalField(max_digits=4, decimal_places=3) incorrect= models.DecimalField(max_digits=4, decimal_places=3) class Meta: unique_together = ('quiz','question') In this the questions are added to the quiz using model Question Quiz. Here , QuizQuestion has foreign key relationship with the question. I need to fetch all from question JOIN and records from QuestionQuiz with a particular quiz_id. Suppose quiz_id =3 Then I will fetch all questions with correct and incorrect. if that quiz id is added to the question then it will display correct incorrect else these would be blank. question_id | title|description|correct|incorrect|quesquizid 1 | Q1 |Q1desc |2 | -2 | 1 2 | Q2 |Q2desc | | | ques_id =1 added to quiz_id=3 .ques_id=2 not added to quiz_id=3.So, correct incorrect are blank. I tried following but it fetches all question and related quizes scores irrespective of their occurrence in current quiz : Question.objects.prefetch_related('questionquiz_set').all() The result should be similar to following query Select * … -
how to send data in GET request header using react and axios to Django rest framework?
i am new to react and axios and i want to know how to send data in my headers using get request i tried this but it didn't work ** i observed that the request type changed to options in django terminal window ** export const getUserOrders=(userID)=>{ return dispatch=>{ dispatch(getUserOrdersStart()) axios.defaults.headers={ 'Content-Type':'application/json', id:userID } axios.get('http://127.0.0.1:8000/admindashboard/userorders/') .then(res=>{ const order=res.data dispatch(getUserOrdersSuccess(order)) }).catch(err=>{ getUserOrdersFail(err) }) } } -
ERD Diagram for a school management system automatically generated using postgresql as my dbms
I'm currently building a school management system with modules that include: admin, students, parents, teachers and fees management. I am using django for my back-end development for my app. I've already created these models on my models.py file in my app and configured my postgresql into my settings.py file. How can i generate an automatic ERD Diagram without having to draw it myself?