Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to combine Q condition in Django
Say there're some query condition as below: from django.db.models import Q or_conditions = [ {"a": 1}, {"b": 2}, {"c": 3}, ] single_or_condition = {"d": 4} and_condition = {"e": 5} # I want get condition like (a or b or c) and (e) or (d) # And I've tried with below, but failed group_Q = Q() for condition_model in or_conditions: group_Q.add(Q(**(condition_model)), conn_type=Q.OR) final_Q = group_Q.add(Q(**single_or_condition), conn_type=Q.OR).\ add(Q(**and_condition), conn_type=Q.AND) I want to get something like (a or b or c) and (e) or (d) And tried with codes above, but unexpected result returned. It seemd that my Q query condition didn't work. How can I make it right? Thanks -
How to redirect django search from main page to another local page?
Ok I spent over two weeks trying to resolve this but I can't find a clear answer. I am new to django so I am trying to figure my way out. So here is my problem: I have a website with several products on it and I recently created search.html file that works when I go to "http://127.0.0.1:8000/search/" but I want to make it when the user types something in the search bar on the main page "http://127.0.0.1:8000" and clicks search Django will redirect the user with the input value to "http://127.0.0.1:8000/search/". ####-------------------------------------------------------### In my view.py def searchproduct(request, *args, **kwargs): if request.method == 'GET': query=request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups = Q(name__icontains=query)| Q(description__icontains=query) | Q(detailed_description__icontains=query) | Q(PN__icontains=query) | Q(image__icontains=query) results= Product.objects.filter(lookups).distinct() context={'results':results,'submitbutton': submitbutton} return render(request, 'search.html', context) else: return render(request, 'search.html') else: return render(request, 'search.html') ####-------------------------------------------------------### In my base.html <div id="search_head"> <br/> <form action="" method="GET" value="{{request.GET.q}}" > Search <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search products"/> <input type="submit" name="submit" value="Search" /> </form> </div> ####-------------------------------------------------------### in my url.py: urlpatterns = [ path('', home_view, name='Home'), path('search/', searchproduct, name='Search'),] -
How to configure Lambda function (django) outside VPC to access Amazon ElastiCache inside a VPC?
How to configure Lambda function (django) outside VPC to access Amazon ElastiCache inside a VPC?? The suggestions from everywhere is its possible only if its in same VPC, but my lambda function is outside VPC and Amazon ElastiCache inside a VPC. How do I configure? Thanks in advance -
Changing SQLite to PostgreSQL in Django cause Error 'cannot cast type bytea to boolean'
I had a project in Django that use SQLite as database and it works well. Now i want change my database from SQLite to PostgreSQL. i changed settings.py file and installed psycopg2. the problem is that when i want run python manage.py migrate i had error in CMD that says: ... django.db.utils.ProgrammingError: cannot cast type bytea to boolean LINE 1: ...ansactionType" TYPE boolean USING "TransactionType"::boolean and at django debug mode in browser shows this error: ProgrammingError at /home operator does not exist: bytea = boolean LINE 1: ...ction" WHERE ("web_transaction"."TransactionType" = true AND... this is my model in django class Transaction(models.Model): Amount = models.BigIntegerField() TransactionType = models.BooleanField() in my home view i use this query that error django debug mode indicates: def homePage(request): this_user=request.user income = Transaction.objects.filter(user=this_user, TransactionType=True).aggregate(Sum('amount')) i can't find out why this happen when use PostgreSQL but works well in SQLite. -
Django: save an instance and use it later in another form (two forms processed in one views.py function)
I have two forms in one html page. The first form has a button generate and the second form has the button save. For context, I have to save the object that is displayed when I click the generate button. In the views.py, these forms are contained in one function as shown below: def index(request): q = Quote.objects.all() if request.method == 'POST' and 'generate' in request.POST: form = EmotionForm(request.POST) if form.is_valid(): emotion = form.cleaned_data['emotion'] quote = choice(q.filter(tag__name=emotion)) # <–- use this instance... context = { 'emotion': emotion, 'quote':quote, } return render(request, 'main/index.html', context) if request.method == 'POST' and 'save' in request.POST: quote = SavedQuote(user=request.user, quote=quote) # <–- ...here quote.save() return redirect('account') else: form = EmotionForm() context = { 'form': form, } return render(request, 'main/index.html', context) My problem is that I want to use the instance quote = choice(q.filter(tag__name=emotion)) in the line quote = SavedQuote(user=request.user, quote=quote). I've already tested my code if everything works fine by hard coding the instance, e.g., quote = SavedQuote(user=request.user, quote=choice(q.filter(tag__name=happiness))) and it does work. Even if I try to assign a variable outside the if statements, it won’t work as the page reloads and runs the function again. What are good ways to save the instance … -
module 'django.db.models' has no attribute 'FieldDoesNotExist'
I am having issues with my django admin area while adding data and selecting theenter image description here author which comes from relation from another class it gives the error written in title the relation is enter image description here anyone with the answer will be helpfull thanks -
How to show validation error in my form instead of getting IntegrityError?
I am creating a portfolio app, in which there are two models: class Portfoller(AbstractUser): career_options = [('Developer','Developer'), ('Artist', 'Artist'), ('Writer','Writer')] gender_options = [('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other')] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=6, choices=gender_options, default='Male') birthdate = models.DateField('birthdate') country_of_birth = CountryField() career = models.CharField(max_length=20, choices=career_options) email = models.EmailField(max_length=254, unique=True) profile_picture = models.ImageField(upload_to=profile_picture_path, default='generic_user.png') biography = models.TextField(max_length=1000, null=True, blank=True) def get_age(self): now = timezone.now() return now.year - self.birthdate.year - ((now.month, now.day) < (self.birthdate.month, self.birthdate.day)) class Project(models.Model): user = models.ForeignKey(Portfoller, on_delete=models.CASCADE) project_name = models.CharField(max_length=50) project_description = models.TextField(max_length=1024) class Meta: unique_together = ('project_name', 'user') And now I am making a view to add a Project to a Portfoller: class AddProject(View): def get(self, request, username): form = AddProjectForm() form.instance.user = get_object_or_404(Portfoller, username=username) return render(request, 'portfolio/add_project.html', {'form': form}) def post(self, request, username): form = AddProjectForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('portfolio:profile', kwargs={'username': username})) The problem is that when I get a project_name equals to an existent project project_name I want to get a form error in the form page, but instead, I'm getting a: IntegrityError at /users/admin/add-project/ null value in column "user_id" violates not-null constraint How to solve it? urls.py: from django.urls import path, include from . import views app_name = 'portfolio' … -
How can I locking list when async task running for another task?
I have a task that needs to run every 1 minute. I want the orders in the order list I sent to this task not to be in the next task even if it is not completed. How should I make a development? async_row_process = kwargs.get("async_row_process", True) #when next task is running task must leave previous 'previous order list' for order in orders: if async_row_process: row_method.delay(row=order, lock_name=lock_name, now='%s' % now, *args, **kwargs) Am I should develop a decorator ? Or can I use order queue for all tasks can see ? -
Unable to pass a view function with two arguments in Django resulting in No Reverse Match Error
I am unable to understand why am I getting this error. If someone can please explain me why and how I can fix it, I am hoping that it will correct the underlying misconceptions that I probably have about Django views and urls. django.urls.exceptions.NoReverseMatch: Reverse for 'download' with keyword arguments '{'name': 'Dr. XYZ', 'date': '14 July 2020'}' not found. 1 pattern(s) tried: ['download/$'] I have a function called download in my views.py which takes two arguments: name and date Views.py def download (request, name, date): x = date.split(" ") date = f"29 {x[3]} {x[4]}" image = Image.open("certificates\static\certificates\Certificate_0001.jpg") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(810, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) image.save(f"certificates\static\certificates\{name}.pdf", "PDF", resolution=100.0) return HttpResponse ("works") I am calling this function upon a link click in my html file. <a class="nav-link active" href="{% url 'certificates:download' name=name date=program %}" download>Download Certificate</a> The url configuration is: urls.py from django.urls import path from . import views app_name = "certificates" urlpatterns = [ path("", views.index, name="index"), path("download", views.download, name="download") ] It is confirmed that there is no syntax or other logical error in my function. If I remove the two arguments in my html file … -
Django ModuleNotFoundError: No module named 'sql_server' With Docker
I am getting an error in console while trying to install lib django-pyodbc , django-pyodbc-azure and pyodbc With docker. How to fix this. PS C:\Users\TestPIXS\Desktop\Test\Testadmin\master> docker-compose build Building web Step 1/7 : FROM python:3 ---> 28a4c88cdbbf Step 2/7 : ENV PYTHONUNBUFFERED l ---> Using cache ---> aa30b1083d6a Step 3/7 : RUN mkdir /app ---> Using cache ---> 1a205fb68d9f Step 4/7 : WORKDIR /app ---> Using cache ---> 6f532c2f7d6b Step 5/7 : COPY requirements.txt /app/ ---> 1e900bfa67a1 Step 6/7 : RUN pip install -r requirements.txt ---> Running in 08071da8e89b Collecting Django==3.1.1 Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) Collecting django-pyodbc==1.1.3 Downloading django_pyodbc-1.1.3-py2.py3-none-any.whl (51 kB) Collecting django-pyodbc-azure==2.1.0.0 Downloading django_pyodbc_azure-2.1.0.0-py3-none-any.whl (39 kB) Collecting pyodbc Downloading pyodbc-4.0.30.tar.gz (266 kB) Collecting pytz Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting asgiref~=3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Building wheels for collected packages: pyodbc Building wheel for pyodbc (setup.py): started Building wheel for pyodbc (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-kfqrr62v/pyodbc/setup.py'"'"'; __file__='"'"'/tmp/pip-install-kfqrr62v/pyodbc/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-tiofv2rv cwd: /tmp/pip-install-kfqrr62v/pyodbc/ Complete output (14 lines): running bdist_wheel running build running build_ext building 'pyodbc' extension creating build creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/src … -
Django: Dynamically generate ChoiceField values from another model object
I want to implement a Django form with dynamically generated ChoiceField options. In my forms.py I have extended the Django forms as follows: class OptionForm(forms.Form): choicefield= forms.ChoiceField(choices= []) def __init__(self, *args, **kwargs): super(OptionForm, self).__init__(*args, **kwargs) self.fields['choicefield'].choices = forms.ChoiceField(choices= get_choice()) In my views.py I have defined the following (relevant) methods: from .forms import OptionForm def get_choice(): return # like this [(q.optionA, q.optionA), (q.optionB, q.optionB), (q.optionC, q.optionC), (q.optionD, q.optionD)] # how can I pass q to this __init__ method class OptionForm(forms.Form): options= forms.ChoiceField(choices= []) def __init__(self, *args, **kwargs): super(OptionForm, self).__init__(*args, **kwargs) self.fields['options'].choices = get_choice() def viewtest(request, test_pk): # get the test object containing all the questions # each question contains four options using which I want to generate ChoiceField options corresponding to each question # each option is available as q.optionA, q.optionB q.optionC & q.optionD test= get_object_or_404(Test, pk= test_pk) options= [] for q in test.questions.all(): opform= OptionForm() # how do I pass q.optionA, q.optionB q.optionC & q.optionD here to dynamically provide ChoiceField options? options.append(opform) return render(request, 'tests/test.html', {'test': test, 'options': options}) -
match everyhting after domain name in url django
I want to write a pattern matching for URL in django to match everything after the domain name. I've been on it for hours now but couldn't find the solution. For eg: https://example.com/dsfdsfsdf , output : dsfdsfsdf https://example.com/b?node=162250&pf_rd_r=SYPPX3PERB7N , output : b?node=162250&pf_rd_r=SYPPX3PERB7N Domain Name can also be localhost:8000(for testing on local system) https://localhost:8000/dsfdsfsdf , output : dsfdsfsdf https://localhost:8000/b?node=162250&pf_rd_r=SYPPX3PERB7N , output : b?node=162250&pf_rd_r=SYPPX3PERB7N It doesnt matter what is given after the domain name. I want to match everything that comes after domain in urls.py and execute my view function. I am able to solve this using findall, but unable to do the same in Django urls.py file. -
Passing django variable into php and JavaScript files [closed]
I know that I can type: <h1> result is: {{res}}</h1> But how to use {{res}} in php?? Can I type: echo {{res}} ? How can i use {{res}} in JavaScript function alert () as well? Is there any modification required in view and url pages??? Thank you very much in advance. -
How to display relation data in Django view page?
I have relation between TestForm and Customer and there are ForeignKey of customer in TestForm, but i want to display data from Customer, please let me know how i can display. I want to display name from Customer model... Here is my models.py file... class TestForm(models.Model): name=models.CharField(max_length=225) brand=models.ForeignKey(Customer, related_name='customer_data', on_delete=models.CASCADE, verbose_name='Customer') class Customer(models.Model): name=models.CharField(max_length=225) here is my view.py file... def myview(request, id): datas=TestForm.objects.select_related('customer').get(pk=id) template_name='test.html' context={'datas':datas} return render(request, template_name, context) here is my test.html file.. <p> {% for a in datas.customer_data.all %} {{a.name}} {% endfor %} </p> -
django ordering results are changed when i update one record
I used postgresql and rest_framework.filters.OrderingFilter library in my viewset: ... querset = myModel.objects.all().order_by('-id') filter_backends = (OrderingFilter,) ordering_fields = ('fields1', 'fields2') for example: i have five record ordering by fields2 desc: record3 record2 record1 record4 record5 when I update record2 fields3 and still ordering by fields desc, the ordering results got changed: record2 record1 record3 record4 record5 Why is this happening? -
Query problem how can i add or operator? with query dict
Hope You Are Good My Problem is i want to find properties by cities and if we get none we want to find properties with location but how can i achive this i want to add or operator something to get that result but the problem is how can i do that? here is my following code (That doesn't work): query = {} if city: newCity = City.objects.filter(name=city.lower()).first() if newCity: query["city"] = newCity query["location__icontains"] = city.lower() # if not query: queryset = Property.objects.filter(**query).order_by('-id') I want if properites with city doesn't found try with location! Thanks -
NameError at /admin/notebook/series_num/add/ [closed]
Would you guys please help me here. Why i get error ? NameError at /admin/notebook/series_num/add/ name 'model_num' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/notebook/series_num/add/ Django Version: 3.1.1 Exception Type: NameError Exception Value: name 'model_num' is not defined Exception Location: D:\PythonDjango\django_doc_mysite\notebook\models.py, line 16, in __str__ Python Executable: D:\PythonDjango\VENV\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\PythonDjango\\django_doc_mysite', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'D:\\PythonDjango\\VENV', 'D:\\PythonDjango\\VENV\\lib\\site-packages'] Server time: Wed, 16 Sep 2020 13:42:23 +0800 I created 2 database in the models.py and registered 2 databases in the admin.py I added data to Brand successfully but i got error when I add data to the database of series_num -
Django - Last Updated By and Update Date not working
Hi I need someone's advice. I created a form add organizations and a form to edit organizations. These are working fine. However, I have Last Updated By and Update Date fields on the model - These are not picking up the datetime and user information when editing the organization. views.py @login_required() def organization_edit(request, pk): org = Organization.objects.get(org_id=pk) form = OrganizationEditForm(instance=org) # Update Org if request.method == 'POST': form = OrganizationEditForm(request.POST, instance=org) if form.is_valid(): form.organization_code = form.cleaned_data['organization_code'] form.company_name = form.cleaned_data['company_name'] form.legal_name = form.cleaned_data['legal_name'] form.business_registration_no = form.cleaned_data['business_registration_no'] form.vat_registration_no = form.cleaned_data['vat_registration_no'] form.industry_distribution = form.cleaned_data['industry_distribution'] form.industry_education = form.cleaned_data['industry_education'] form.industry_healthcare = form.cleaned_data['industry_healthcare'] form.industry_manufacturing = form.cleaned_data['industry_manufacturing'] form.industry_retail = form.cleaned_data['industry_retail'] form.industry_services = form.cleaned_data['industry_services'] form.effective_start_date = form.cleaned_data['effective_start_date'] form.effective_end_date = form.cleaned_data['effective_end_date'] org = form.save(commit=False) org.last_updated_by = request.user org.save() return redirect('organizations_settings') context = { 'form':form, 'org':org, } return render(request, 'settings/edit_organization.html', context) models.py class Organization(models.Model): org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False) organization_code = models.CharField(max_length=20) company_name = models.CharField(verbose_name="Company Name", max_length=60) legal_name = models.CharField(verbose_name="Legal Name", max_length=100) industry_distribution = models.BooleanField(verbose_name="Distribution", default=False) industry_education = models.BooleanField(verbose_name="Education", default=False) industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False) industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False) industry_retail = models.BooleanField(verbose_name="Retail", default=False) industry_services = models.BooleanField(verbose_name="Services", default=False) business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True) vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True) created_date = models.DateTimeField(default=datetime.now) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created … -
Django/Templates/CSS: Fit a Plotly graph inside a responsive grid
I am using Django and trying to embed Plotly plots into my HTML templates. For testing I copied the simple examples into my views.py. This is the 2nd plot: # Plot 2 animals = ['giraffes', 'orangutans', 'monkeys'] fig2 = go.Figure([go.Bar(x=animals, y=[20, 14, 23])]) plot_div2 = plot(fig2, output_type='div', include_plotlyjs=False) All plots are included by the context dict. context = { 'plots': { 'test1': plot_div1, 'test2': plot_div2, }, } In my template home.html there is a responsive Grid (12 cols). The graphs are plotted side by side (each graph is inside a 6-col element). So one plot looks like this: <div class="p-relative col-6 pd-5 border-box elevation-1 primary"> <div class="p-relative border-box w-full"> {{plots.test1|safe}} </div> </div> Parent element CSS: position: relative; grid-column-end: span 6; padding: 1.25rem; box-sizing: border-box; box-shadow: ... ; background: ...; Child element CSS: position: relative; box-sizing: border-box; width: 100%; The Problem: The plot's height looks okay, but the plot's width is bigger than the container width. Because the plots should be displayed inside a responsive grid it would make no sense to resize the plots using pixels. The attached pictures shows the problem. Plot overflow (Picture) -
Get multiple objects of reverse foreign_key relation inside values()
I have two django models as below: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Entry(models.Model): entry_id = models.Autofield(primary_key=True) blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='blog') headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() I'm trying to get the backward relation using related_name. I want to get the entire data of the 'Entry' by using related_name 'blog'. There are multiple entry's for each blog. How can I achieve the following output: {'name': '', 'tagline': '', 'all_blogs':[{'blog': '','headline': '','body_text': '','pub_date': '', 'mod_date': ''},]} I tried this: response = Blog.objects.filter( name=name, blog__pub_date=date ).values( 'name', 'tagline', all_blogs=Entry.objects.filter(entry_id=F(blog__entry_id)).values() ) return response But it is throwing field error saying I cannot use "blog" field inside F() expression. Thanks for the response. -
how to calculate data fields that are filled in a certain id, implementing the count formula in excel in django?
ini adalah contoh kasus dalam pengisian baris data excel yang nantinya akan saya coba adaptasikan ke dalam penyimpanan data di django. Models.py class Quality_Model(models.Model): name = models.ForeignKey(Members, blank=True, null=True, on_delete=models.CASCADE) year = models.IntegerField(default=0,blank=True) jan = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) feb = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) mar = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) apr = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) mei = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) june = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) july = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) ags = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) sept = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) oct = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) nov = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) des = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal(0), blank = True, null=True) avg = models.DecimalField(max_digits = 5,decimal_places = 2,default=Decimal(0),blank=True,null=True) Views.py @login_required(login_url = settings.LOGIN_URL) … -
Django CreateView - How to leave some blank fields in the form
I have a CreateView class where I am passing a ModelForm. In this form, I made a checkbox. In the template, I am hiding some fields. If the user tick the checkbox, I remove the hidden attribute from those fields and make them Required. Otherwise, If the user doesnt tick the checkbox, I remove their attribute required and hide them. When I try to submit it with the checkbox unticked, it keeps redirecting me on the form (form invalid). If I tick the box and all the elements are fulfilled, it works well and redirect me on the main page of course. In the model, all the fields that could be hidden are having a default value... Could someone explain how I could leave these fields blank please? I will attach below all the code which could be useful if you wanna check it.. View.py: class QualityCreateView(LoginRequiredMixin, CreateView): model = Quality form_class = QualityForm def form_valid(self, form): if form.is_valid(): print('Valid!') else: print('not valid!') return super().form_valid(form) def get_success_url(self): return reverse('teamleaderworkspace:quality') #Checking if kwargs['instance'] is None means that the code works with both CreateView and UpdateView. def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) if kwargs['instance'] is None: kwargs['instance'] = Quality() kwargs['instance'].team_leader … -
TypeError: Object of type Asia/Kolkata is not JSON serializable
I am trying to use timezone_field, but it shows it is not serializable and shows error. Please need your help. I have provided code in below.. Thanks in advance. Models.py from django.db import models from timezone_field import TimeZoneField # Create your models here. class Member(models.Model): tz = TimeZoneField(default='Asia/Kolkata') def __str__(self): return self.tz serializers.py from . models import Member from rest_framework.serializers import ModelSerializer class Member_Serializer(ModelSerializer): class Meta: model = Member fields = '__all__' views.py from . models import Member from . serializers import Member_Serializer from rest_framework.generics import ListCreateAPIView # Create your views here. class MemberListView(ListCreateAPIView): queryset = Member.objects.all() serializer_class = Member_Serializer error: Object of type Asia/Kolkata is not JSON serializable Request Method: POST Request URL: http://localhost:8000/a/ Django Version: 3.1.1 Exception Type: TypeError Exception Value: Object of type Asia/Kolkata is not JSON serializable -
Form onSubmit is not updating the page
**first time asking qn on stack overflow so i apologize if i didn't do it right hah...and I am a beginner in React so this question might sound silly haha! So guys, my problem is that whenever I click on submit, it doesn't show any change and also the text on the form where you type title and content is still there. I tried using 'onSubmit' but it doesn't make any changes in my database and doesn't refresh the page either. So I used 'onSubmitCapture' and when I do so, doesn't show the change, doesn't empty the 'title' and 'content' that I typed in but in my Django Admin I can see that it added a new article or updated an existing one if I edited it. So, if i refresh it manually, i can see that it updated it, both while creating and updating an article. I couldn't find a solution for this because most problems are with the React app being refreshed every time the form is submitted. I was wondering if there us a way that I can empty the input fields and update the page too. This is the code...I was watching a tutorial on a … -
Django annotation on (model → FK → model) relation
Galaxies across the universe host millions/billions of stars, each belonging to a specific type, depending on its physical properties (Red stars, Blue Supergiant, White Dwarf, etc). For each Star in my database, I'm trying to find the number of distinct galaxies that are also home for some star of that same type. class Galaxy(Model): ... class Star(Model): galaxy = ForeignKey(Galaxy, related_name='stars') type = CharField(...) Performing this query individually for each Star might be comfortably done by: star = <some_Star> desired_galaxies = Galaxy.objects.filter(stars__type=star.type).distinct() desired_count = desired_galaxies.count() Or even, albeit more redundant: desired_count = Star.objects.filter(group__stars__type=star.type).values('galaxy').distinct() This get a little fuzzier when I try to get the count result for all the stars in a "single" query: all_stars = Star.objects.annotate(desired_count=...) The main reason I want to do that is to be capable of sorting Star.objects.order_by('desired_count') in a clean way. What I tried so far: Star.annotate(desired_count=Count('galaxy', filter=Q(galaxy__stars__type=F('type')), distinct=True)) But this annotates 1 for every star. I guess I'll have to go for OutRef, Subquery here, but not sure on how. ps: This is just an analogy for the unattractive models and fields within my code. I'd be inclined to think that all the galaxies host every type of star as we classify them, or …