Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django server refused connection on localhost
Hi guys I have a brand new Django setup on my computer, I ran the command runserver, and I get an ERR_CONNECTION_REFUSED in chrome, localhost is added to allowed_hosts and I get no error in django, when I check for the port it is not active, I am running Django in wsl and accessing chrome from windows on the same machine I have tried adding to my IP, changing browser, adding to allowed hosts, I initially had this issue in another project and I set up this new project to see if the problem would resolve, it didn't and the new project is completely clean no way something could be messed up there any help would be greatly appreciated thanks in advance edit: I tried running the server in windows and finally got an error Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions -
Why is my CSS file is not loading (Django)
So my directory is CLASSMGMTSYS/classMgmt/static/classMgmt/css/indexCss.css ----------------------/templates/index.html When I run the server it says: "GET /static/classMgmt/css/index.css HTTP/1.1" 404 1695 Not Found: /favicon.ico index.html {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'classMgmt/css/index.css' %}"> <title>Index Page</title> </head> <body> <div> {% if class_list %} <ul> {% for class in class_list %} <h1> <a href="{% url 'classMgmt:class_details' class.id %}">{{ class.name }}<a/> </h1> {% endfor %} </ul> {% else %} <p>No class are available at the moment. Try again later.</p> {% endif %} </div> <div> <button type='button'><a href='{% url "classMgmt:add_class" %}'>Add Class</a></button> </div> </body> </html> static/Mgmt/css/index.css li a { color: green; } -
Python (django) call two management commands at the same time
I'm writing unit tests for my management commands. I would like to run my two management commands meanwhile by using call_command() function. How can I do that? I need to run them at the same time because they do work together, one creates data and the other uses that data. -
Django: query caching not working as expected
I'm working on optimizing my Django app. Some of the caching behavior from at least one of the queries is not working as expected and I am running out of ideas. For ease, this is a simplified example. Suppose I have 3 models: User, FriendsList, Gender. User serves as Foreign Key to each, FriendsList (as user_id and befriended_user_id) and Gender (as user_id). The tables are fully normalized. The goal is to display a User's Friendslist, with entries sorted by Gender. I wanted to minimize the number of database hits by optimally utilizing query caching. in views.py: 1 female_friends = [] 2 male_friends = [] 3 4 gender_query = Gender.objects.select_related().all() 5 # no hits to database 6 7 friendslist_query = FriendsList.objects.filter(user_id = request.user.id).select_related().all() 8 # 2 hits to database 9 10 for friendslist in friendslist_query: 11 # 1 hit to database (total for all entries) 12 13 friend_entry = friendslist.befriended_user_id.id 14 # no hits to database 15 16 gender = gender_query.get(user_id = friends_entry) 17 # 1 hit to database (for each time friendslist_query is iterated over) 18 19 gender_type = gender.gender_type 20 # no hits to database 21 22 if gender_type == 'True': 23 female_friends.append(friendslist) 24 # no hits to database … -
No module names urls
Error: Importerror Python version: 2.7 Django version: 1.8.4 Whenever i start my localhost server, i get this error, the error is pointing towards from django.urls import re_path in grapelli/urls.py, code provided in the end. *** **ImportError at / No module named urls Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.8.4 Exception Type: ImportError Exception Value: No module named urls Exception Location: /mnt/c/users/verma/desktop/opine/env/local/lib/python2.7/site- packages/grappelli/urls.py in <module>, line 3 Python Executable: /mnt/c/users/verma/desktop/opine/env/bin/python Python Version: 2.7.17 Python Path: ['/mnt/c/users/verma/desktop/opine', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7/plat-x86_64-linux-gnu', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7/lib-tk', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7/lib-old', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/mnt/c/users/verma/desktop/opine/env/local/lib/python2.7/site-packages', '/mnt/c/users/verma/desktop/opine/env/lib/python2.7/site-packages']*** Server time: Wed, 6 Jan 2021 03:07:09 +0530** /mnt/c/users/verma/desktop/opine/env/local/lib/python2.7/site-packages/grappelli/urls.py in grappelli/urls.py : I have used grappelli in my project for admin access. ** # coding: utf-8 from django.urls import re_path from .views.related import AutocompleteLookup, M2MLookup, RelatedLookup from .views.switch import switch_user urlpatterns = [ # FOREIGNKEY & GENERIC LOOKUP re_path(r'^lookup/related/$', RelatedLookup.as_view(), name="grp_related_lookup"), re_path(r'^lookup/m2m/$', M2MLookup.as_view(), name="grp_m2m_lookup"), re_path(r'^lookup/autocomplete/$', AutocompleteLookup.as_view(), name="grp_autocomplete_lookup"), # SWITCH USER re_path(r'^switch/user/(?P<object_id>\d+)/$', switch_user, name="grp_switch_user"), ] ** Error in line no. 1: from django.urls import re_path How do I fix this, because URLs is not another module created by me, it's an inbuilt one in Django. -
Django - Use Ajax to filter and display projects per category
I would like to use Ajax in my project in order to filter projects per category and display them in my template. I read a couple of articles but unfortunately i cannot figure out a way of how to implement it. Any help is appreciated. views.py class CategoryDetailView(ListView): model = Category context_object_name = 'projects_categ' template_name = 'work/work.html' def get_queryset(self): self.category = get_object_or_404(Category, pk=self.kwargs['pk']) return Project.objects.filter(category=self.category).order_by('-id') def get_context_data(self, **kwargs): context = super(CategoryDetailView, self).get_context_data(**kwargs) return context urls.py path('category/<int:pk>/<slug:slug>', CategoryDetailView.as_view(), name='category-list'), work.html <div class="filterings"> <div class="filtering-wrap"> <div class="filtering"> <div class="selector"></div> {% for category in categories %} <button type="button" data-filter="brand" data="branding" value="branding" class="filter-category"> <a href="#">{{ category.title }}</a> </button> {% endfor %} </div> </div> </div> -
Django pagination, ordered and search
I've a question about what is the proper way to implement a pganiation with a search and possibility to reorder on column on a table in Django. What trigger me is thatt keep pagination true with the right data I duplicate three times all my HTML pagination with different data to keep the "state" of my pagination + order/searchTerm. This is what I've done so far : Search.py def searchProjects(request,user): querySearch = request.GET.get("q") queryOrderBy = request.GET.get("orderby") if querySearch: projects = Project.objects.filter( Q(reference__icontains=querySearch) | Q(name__icontains=querySearch) ).distinct() paginator = Paginator(projects, 10) page_number = request.GET.get('page', 1) paginateProjects = paginator.get_page(page_number) paginateProjects.searchTerm = querySearch elif queryOrderBy: projects = Project.objects.order_by(queryOrderBy) paginator = Paginator(projects, 10) page_number = request.GET.get('page', 1) paginateProjects = paginator.get_page(page_number) paginateProjects.orderby = queryOrderBy else: if user.is_admin: projects = Project.objects.order_by('-created') else: projects = Project.objects.filter(creator=user).order_by('-created') paginator = Paginator(projects, 10) page_number = request.GET.get('page', 1) paginateProjects = paginator.get_page(page_number) return paginateProjects Render.py paginateProjects = searchProjects(request,user) context = { 'projects': paginateProjects } return render(request, "main/globale/home.html", context) Home.html {% if projects.searchTerm %} {% if projects.has_previous %} <a href="?page=1&q={{ projects.searchTerm }}">&laquo; first</a> <a href="?page={{ projects.previous_page_number }}&q={{ projects.searchTerm }}">previous</a> {% endif %} <span class="current"> Page {{ projects.number }} of {{ projects.paginator.num_pages }}. </span> {% for i in projects.paginator.page_range %} {% if i == projects.number|add:'-1' … -
comparing form field value with a random object list value inside Django template
I'm trying to build a simple dictionary quiz app . Basically I write the new words and translations , then pick one randomly and ask for its translation.. They get rendered OK in the template but the "if" doesn't work Views.py def QuizRandom(request): choices = list(mydictionary.objects.all()) random_word = random.sample(choices, 1) form = QuizForm() q = '' if 'q' in request.GET: form = QuizForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] return render ( request, 'quiz.html', {'random_word':random_word, 'form':form, 'q':q,}) forms.py class QuizForm(forms.Form): q = forms.CharField() quizz.html {% for word in random_word %} <h4>guess the translation: {{word.german}}</h4> <h4>translation: {{word.english}}</h4> <h6>form value: {{q}}</h6> <form method='get' class="form-group" id='get-form' > {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-success btn-sm " >GO</button> </form> {% if q == word.english %} <h5>correct</h5> {% else %} <h6>wrong</h6> {% endif %} {% endfor %} -
Use Dictionary based values for Chained Dropdown box Django
How to create a dependent/chained dropdown list for rank dropdown box based on the value of type dropdown list by using values in TYPE ,CO_RANK and NOC_RANK dictionaries if type is OC , rank Field would view CO_RANK dictionary values or if type is NOC, rank Field would view NOC_RANK dictionary values class SysUsers(AbstractUser): """ model all SOILDERS """ # Declare Constants Values TYPE = ( ("CO", 'CO'), ('NOC', 'NOC') ) NOC_RANKS = ( ('AC', 'AC'), ('LAC', 'LAC'), ('CPL', 'CPL'), ('SGT', 'SGT'), ('F/SGT', 'F/SGT'), ('WO', 'WO'), ('MWO', 'MWO'), ) CO_RANK = ( ('PLT OFF', 'PLT OFF'), ('FG OFF', 'FG OFF'), ('FLT LT', 'FLT LT'), ('SQN LDR', 'SQN LDR'), ('WG CDR', 'WG CDR'), ('GP CAPT', 'GP CAPT'), ('ACDR', 'ACDR'), ('AVM', 'AVM'), ('AM', 'AM'), ('ACM', 'ACM'), ) STATUS = ( ('Active', 'Active'), ('Deactivated', 'Deactivated') ) service_no = models.CharField(max_length=100, default="None", null=False, unique=True, blank=False) type = models.CharField(max_length=50, null=False, choices=TYPE, blank=False) rank = models.CharField(max_length=50, null=False, choices=ENG_RANK, blank=False) -
Django: make all models user dependent?
I have many models for very different things. Now I have added user authentication with django-allauth. What I want to do is to make all models user dependent. I mean that only the user can see their own model data that they have stored. What is the best way to achieve this? Do I need to add a ForeignKey to each model I have? model.py: class images(models.Model): ... class things(models.Model): ... class devices(models.Model): ... class messages(models.Model): ... #and so on... -
Virtual Environment Django
Whenever I'm trying to run "./scripts/activate.bat" command in my virtual environment directory for a DJANGO Project, i'm getting the following error : '.' is not recognized as an internal or external command, operable program or batch file. HELP ME TO RESOLVE THIS ERROR... -
Dynamically Process Stored Procedure Results With Django
I am attempting to get the results of a stored procedure and populate a model dynamically, or at a minimum, generate a model based off of the result. My intent is to create a reusable function where it should be ambiguous to the data. I will not know the fields being returned, and wish to take what's returned from the stored procedure, get the field names and put to the data in a an object with said field names. How can I dynamically discover the columns in a result set returned from a stored procedure and then create an object to match? -
Websocket with Django channels doesn't work with heroku, drops connection
hello everyone, i made a blog with a chat room , with django channels and its workin locally perfectly, but when i deploy it to heroku using daphne no message(chat) is showing this is the result og heroku logs --tail this is redis configuration in settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [(os.environ.get('REDIS_HOST', 'localhost'),6379)], }, }, } Procfile web: daphne elearnow.asgi:application --port $PORT --bind 0.0.0.0 -v2 please let me know if i need to add anything else, as i mentioned its stopped showing messages only in production , but locally with the same code everythin is fine i made sure Redis is working, and add "s" for my jquery so its secure "wss://" Thank you very much -
passing the dates between two dates back into the formatday method
I'm learning Python and Django and building a job management app, i have the following which is all working ok and displays the jobs on a html calendar it displays the start and end dates no problem, however if the job is more than two days there is a gap in the calendar as there is no date related to the job to show. i can get the dates in between by doing the following; start = job.start_time end = job.end_time between = end - start for i in range(between.days + 1): datesbetween = [start + timedelta(days=i)] below is my views.py file class AdminCalendarView(LoginRequiredMixin,PermissionRequiredMixin, ListView): model = Job template_name = 'jobs/admin_diary.html' permission_required = 'jobs.add_job', 'raise_exception=True' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = AdminCalendar(d.year, d.month) jobs = Job.objects.filter(start_time__year=d.year, start_time__month=d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(jobs, withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context and the utils.py file from datetime import datetime, timedelta, date from calendar import HTMLCalendar from .models import Job from django.db.models import Q class … -
Django - Update an existing field when another object of same name is added to the table
I'm fairly new to Django, hence open for any kind of suggestions I have two models Order and Stock My code: models.py class Order(models.Model): idorder = models.AutoField(db_column='idorder', primary_key=True) date_ordered = models.DateField(db_column='Date_Ordered', blank=True, null=True) # Field name made lowercase. number_ordered = models.IntegerField(db_column='Number_Ordered', blank=True, null=True) # Field name made lowercase. idproduct = models.ForeignKey(Product, models.DO_NOTHING, blank=True, db_column='idProduct', verbose_name='Product Name') # Field name made lowercase. idsupplier = models.ForeignKey(Supplier, models.DO_NOTHING, blank=True, db_column='idSupplier', verbose_name='Supplier Name') # Field name made lowercase. class Meta: managed = False db_table = 'order' class Stock(models.Model): idstock = models.AutoField(primary_key=True) quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase. idproduct = models.ForeignKey(Product, models.DO_NOTHING, db_column='idProduct', verbose_name='Product Name', blank=True) # Field name made lowercase. idorder = models.ForeignKey(Order, models.DO_NOTHING, db_column='idOrder', verbose_name='Order Name', blank=True) class Meta: managed = False db_table = 'stock' def __str__(self): #to return supplier_name for foreign key references return self.idproduct.product_name I have implemented the addition of corresponding Order object into Stock table using signals #this signal is to add object to stock automatically when order object is created def create_stock_item(sender, instance, created, **kwargs): if created: s = Stock( idorder=instance, quantity=instance.number_ordered, idproduct=instance.idproduct ) s.save() post_save.connect(create_stock_item, sender=Order) When I add an Order, the corresponding Stock object is created What I want to achieve is that … -
Django Celery consuming from AWS SQS
I have a Django app running celery already connected to SQS, everything works if I send the tasks thought Django. But I want to try to send tasks from Cloudflare Workers which use JS. This is the code I'm running in Cloudflare: const client = new SQSClient({ region: "eu-west-3", credentialDefaultProvider: myCredentialProvider }); const send = new SendMessageCommand({ // use wrangler secrets to provide this global variable QueueUrl: URL_HERE, MessageBody: { 'lang': 'py', 'task': 'config.celery.debug_task', 'id': taskId, 'shadow': null, 'eta': null, 'expires': null, 'group': null, 'retries': 0, 'timelimit': [null, null], 'root_id': taskId, 'parent_id': null, 'argsrepr': "", 'kwargsrepr': '{}', 'origin': 'gen46150@Marcoss-MacBook-Pro.local', 'reply_to': uuidv4(), 'correlation_id': taskId, 'hostname': 'celery@Marcoss-MacBook-Pro.local', 'delivery_info': { 'exchange': '', 'routing_key': 'default', 'priority': 0, 'redelivered': null }, 'args': [{ 'hello': 'wolrd', 'success': true }], 'kwargs': {}, 'is_eager': false, 'callbacks': null, 'errbacks': null, 'chain': null, 'chord': null, 'called_directly': false, '_protected': 1 } }); The message gets to SQS correctly and my Django app tries to execute. But I get this error: File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char … -
Select dropdown from another model is not working in django-import-export
I am trying to implement django-import-export in an existing django app. When I'm trying to select an item from dropdown (ForeignKey), I can select the item but it does not save in the subject data. Please see the screenshot for more details: Import Screen: Confirm Screen: [subject is not selected] Here is my code: models.py file class Subject(models.Model): subject = models.CharField( max_length=250, blank=True, null=True) def __str__(self): return self.subject class Answer(models.Model): question = models.ForeignKey(MCQQuestion, verbose_name='Question', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that \ you want displayed", verbose_name="Content") correct = models.BooleanField(blank=False, default=False, help_text="Is this a correct answer?", verbose_name="Correct") def __str__(self): return self.content class Meta: verbose_name = "Answer" verbose_name_plural = "Answers" forms.py file from django import forms from import_export.forms import ImportForm from .models import Subject class CustomImportForm(ImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) admin.py file from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from import_export import fields, resources from .forms import CustomImportForm from .models import Answer, Subject class AnswerResource(resources.ModelResource): class Meta: model = Answer chunk_size = None fields = ['id', 'question', 'content', 'correct', 'subject'] class AnswerAdmin(ImportExportModelAdmin): resource_class = AnswerResource def get_import_form(self): return CustomImportForm def get_form_kwargs(self, form, *args, **kwargs): # pass on … -
How to serialize only certain elements of M2M set of the object being serialized?
So I have these models: class Group(models.Model): name = models.CharField(max_length=255, blank=True, null=True, default=None) class Member(models.Model): name = models.CharField(max_length=255, blank=True, null=True, default=None) group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE) is_deleted = models.BooleanField() And these serializers: class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True, read_only=True) class Meta: model = Group fields = '__all__' class MemberSerializer(serializers.ModelSerializer): # some field defintions here class Meta: model = Member fields = '__all__' And view: class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer Now what I want to do basically, is not return "members" of Group that has is_deleted set to True. So if I have a Group with 3 Member where 1 has is_deleted set to True, I want my serializer to return the Group with 2 Members. How do I go about achieving this? -
How do I convert 2021-01-05T23:19:30.685658Z to dd-mm-yyyy
In my django app I am getting the date returned in the following format 2021-01-05T23:19:30.685658Z How do I convert this to dd-mm-yyyy? -
getting NameError when tries to migrate mySQL database into django project
I have a django - mySQL migration problem. I can not figure out what is the problem, please if you have any idea let me know. I try to change the basic sqlite3 database to mySQL. I started a new django project. I work on mac, I use virtual env and my python version 3.9.0. I have installed pip and homebrew. I installed mysql with homebrew. I made a sample database in mysql, and also checked in the workbench. I started mysql. I installed mysqlclient (2.0.3) via pip. I opened my project and change the DATABASE = {...} in settings.py to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sample', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'thisisreallymypassword', } } My problem is when I run the python manage.py -migrate command I always get NameError: name '_mysql' is not defined. I went through all the topics, but can't figure out the problem. Any idea? (env) Csutkas-MacBookPro:greenium gezamacbookpro$ pip freeze asgiref==3.3.1 Django==3.1.4 django-filter==2.4.0 django-mysql==3.10.0 mysqlclient==2.0.3 Pillow==8.0.1 pytz==2020.4 sqlparse==0.4.1 (env) Csutkas-MacBookPro:greenium gezamacbookpro$ python manage.py migrate Traceback (most recent call last): File "/Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so Reason: image … -
Why i cannot give this values
I want to when i click on the user discharge button it will go to the page and the all user information take automatically. But i cannot get this value. Here is the image in the discharge button i click but its shows like this. Here is my code : views.py def discharge_view(request, pk): form = DischargForm() if request.method == 'POST': form = DischargForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Successfull') return redirect('discharge-patient') context = { 'form': form, } return render(request, 'hospital/discharge.html', context) forms.py : class DischargForm(forms.ModelForm): class Meta: model = PatientDischarge fields = ('assign_doctor', 'admitted', 'release_date', 'medicine_cost', 'other_charge') widgets = { 'assign_doctor': forms.Select(attrs={'class': 'form-control'}), 'admitted': forms.Select(attrs={'class': 'form-control'}), 'release_date': forms.TextInput(attrs={'class': 'form-control'}), 'medicine_cost': forms.TextInput(attrs={'class': 'form-control'}), 'other_charge': forms.TextInput(attrs={'class': 'form-control'}), } discharge.html {% extends 'base.html' %} {% block content %} Discharge patient {% csrf_token %} {% for fields in form %} {{ fields.label_tag }} {{ fields }} {% endfor %} {% endblock %} -
Django grouped queryset with subqueries
I'm trying to create a grouped queryset in Django to first group by occupation and then aggregate sum of occupation by date_rented where date_rented is grouped by month. I have been able to accomplish getting the desired results in python but it seems rather inefficient to me as it is necessary to do subqueries for each occupation to get the sum according to date_rented. Failing being able to use Django's built-in query API, I suppose I will have no choice but to use this solution, but if anyone can help me solve this using Django built in query API, I will be eternally grateful. Model class Tenant(models.Model): name = models.CharField(max_lenght=254) occupation = models.CharField(max_length=254) date_rented = models.DateField() Sample Data | id | name | occupation | date_rented | | -- | ----------------- | ------------------ | ------------- | | 1 | Orlando Barrero | Electrician | 2020-01-13 | | 2 | Miguel Espinosa | Mechanic | 2020-01-24 | | 3 | Renan Figueroa | Electrician | 2020-02-22 | | 4 | Marco Galvez | Mechanic | 2020-03-13 | | 5 | Eric Mendosa | Mechanic | 2020-03-22 | | 6 | Giovani Vela | Electrician | 2020-03-24 | Expected Result | occupation … -
how to get instance of a model form and assign it to its key in view?
During form processing, I'd like to be able to set a foreign key field on a model object from its base model when the user selects a value from the dropdown list. models.py class Question(models.Model): question = models.CharField(max_length=200) class Teacher(models.Model): name = models.CharField(max_length=200) l_name = models.CharField(max_length=200) class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES) For example, I have five records in model A, two records in model B and I have two model forms. forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer fields = ('answer',) widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),} class TeacherForm(ModelForm): name = ModelChoiceField(queryset=Teacher.objects.all()) class Meta: model = Teacher fields = ('name',) For the questions, I just assign them directly within the view and then giving the instances to the foreign key after validation. Now, if I do the same for Teacher I mean this teacher = Teacher.objects.get(id=2) and then choice.teacher = teacher it's going to work perfectly. But that is not the case which I want. The teacher will be selected by the user. I am looking for a way like the below view. views.py def index(request): question1 = Question.objects.get(id=6) question2 = Question.objects.get(id=7) if request.method == "POST": teacher_form = TeacherForm(request.POST) form = AnswerForm(request.POST, … -
DJANGO - Reduce amount of field in queryset
I have a model Product with a lot of fields (~50). I have a filter like : sale = Product.objects.filter(id=2) But this give me all 50 fields for id = 2, so I tried to add only to reduce the queryset size since I only need 2 fields: sale = Product.objects.filter(id=2).only("Origin","Price") Now I want to access to the price with sale.Price but I have the error 'QuerySet' object has no attribute 'Price' -
Convert a list of dictionary to a list of tuples
I have a requirement where I am getting data from DB in a certain format (List of dictionary), but the next set of methods require data in a certain format (List of tuples). How to convert it. The input format is [{'approximate_age_band': ['80-89', '70-79', '60-69'], 'state': ['WY', 'WV', 'WI', 'WA'], 'relationship': ['DEPENDENT', 'SELF', 'SPOUSE'], 'gender': ['Female', 'Male'], 'attribute1_name': ['Medical Plan Type', None], 'attribute1_value': ['POS', None], 'attribute2_name': ['Company Code'], 'attribute2_value': ['M110', None], 'attribute3_name': ['Business Unit', None], 'attribute3_value': ['00001009', '0000444', None], 'attribute4_name': ['Employee Type'], 'attribute4_value': ['Permanent'], 'attribute5_name': [None], 'attribute5_value': [None]}] The output format which I need from this data is [('approximate_age_band', '80-89'), ('approximate_age_band', '70-79'), ('approximate_age_band', '60-69'), ('state', 'WY'), ('state', 'WV'), ('state', 'WI'), ('state', 'WA'), ('relationship', 'SPOUSE'), ('relationship', 'SELF'), ('relationship', 'DEPENDENT'), ('gender', 'Male'), ('gender', 'Female'), ('attribute1_name', 'Medical Plan Type'), ('attribute1_value', 'POS'), ('attribute2_name', 'Company Code'), ('attribute2_value', 'M110'), ('attribute3_name', 'Business Unit'), ('attribute3_value', '00001009'), ('attribute3_value', '0000444'), ('attribute4_name', 'Employee Type'), ('attribute5_name', ''), ('attribute5_value', '')] Can someone please help me with finding the solution.