Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - constructing multi column indexes
Say we have a model that looks thus: class Entry(models.Model): """Users will query for entries with various combinations of filters""" date_created = models.DateTimeField(auto_now_add=True) important = models.BooleanField(default=False, null=False) urgent = models.BooleanField(default=False, null=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) What is the correct way to create indexes that will cater for any combination of the above fields in filters? E.g. .filter(date_created__year='2021', important=False, user=1) My first thought was the below but I have a suspicion I'm doing something wrong here... class Meta: indexes = [models.Index(fields=['-date_created']), models.Index(fields=['-date_created', 'important']), models.Index(fields=['-date_created', 'important', 'urgent']), models.Index(fields=['-date_created', 'important', 'urgent', 'user']), models.Index(fields=['-date_created', 'user']), models.Index(fields=['....etc...'])] I read through the Django documentation and noted their use of the include argument that was introduced in Django 3.2, but was unable to find useful examples of it's use. Would it work in my situation? class Meta: indexes = [models.Index(fields=['-date_created'], include=['important', 'urgent', 'user'])] Thank you -
get list of items, which were passed from python file (Django) to html, from html to Javascript, which is on the same page
my python code: def index(request): body=list(Body.objects.all()) loads=list(Load.objects.all().order_by('length')) badLoads=[] goodLoads=[] for load in loads: if load.length>body[0].length or load.width>body[0].width or load.mass>body[0].mass: badLoads.append(load) else: goodLoads.append(load) goodLoadsLength=len(goodLoads) context={ 'body':body[0], 'loads':loads, 'badLoads':badLoads, 'goodLoads':goodLoads, 'goodLoadsLength':goodLoadsLength, } return render(request,'index.html',context) html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Positioning of objects</title> </head> <body> <div> {% if body %} <p>body length: {{ body.length }}, body width: {{ body.width }}, body height: {{ body.height }}, body max mass, which can be taken: {{ body.mass }}</p> {% else %} <p>No parameters found</p> {% endif %} </div> <div> {% if loads %} <ul> {% for load in loads %} <li>load id: {{ load.id }}, load length:{{ load.length }}, load width: {{load.width}}, load height: {{load.height}}, load mass: {{load.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if goodLoads %} <ul> {% for goodLoad in goodLoads %} <li>load id: {{ goodLoad.id }}, load length:{{ goodLoad.length }}, load width: {{goodLoad.width}}, load height: {{goodLoad.height}}, load mass: {{goodLoad.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if loads %} <ul> {% for badLoad in badLoads %} <li>load id: {{ badLoad.id }}, … -
(Django) include does not import other apps' urls
In my Django project I have 2 apps: core and books. In my core/urls.py, I use python include('books.url') to import the urls from books/urls.py, but I keep getting this error I have been having this issue now that's bugging me. I had a workaround for it, though I really want to fix this. core/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include # local urlpatterns = [ path('/', include('books.urls')), path('admin/', admin.site.urls), ] books/urls.py from django.contrib import admin from django.urls import path # local from graphene_django.views import GraphQLView from books.schema import schema urlpatterns = [ path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), ] As suggested by SO, I have: put books.urls inside the single quotes ' ' placed the path('/', include('books.urls')) on top switch from from django.urls import include to from django.conf.urls import include The only workaround I have is place all urls into the core/urls.py, but that seems too chunky in the long run. I don't get why include works for everyone but not me! Could you help me with this issue? Thank you! -
Django POST data to via form and redirect to page with POST data
I have a Django form, that once the data has been submitted I'd like to redirect to another page where the data will be displayed. I'm having trouble as I don't know how to retrieve the Foreign Key until the form has been submitted Form class addEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(addEventForm, self).__init__(*args, **kwargs) class Meta: model = Event fields = '__all__' View class addEventView(LoginRequiredMixin,View): template_name = 'pages/add_event.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): form = addEventForm(request.POST) if form.is_valid(): form.save() data = {"success": "successfully added"} else: data = {"error": form.errors} return JsonResponse(data, safe=False) How do I redirect but pull in the data from the POST? Thanks -
Multiple forms with bootstrap modal in one single create view in Django
I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm. 1st is Main form and others (EducationForm, ExperienceForm,RecommendationForm,OtherDocumentsForm) should be in bootstrap modal. During filling the main form(MyForm), I also have to fill other forms with bootstrap modal and Finally all of them should be attached to Main form. I connected them other forms with Foreign key to MyForm. I stucked in this situation. Could anyone knows how to get data from bootstrap and connect them in one view? MyForms class MyForm(forms.ModelForm): class Meta: model = UserForm_uz fields = 'all' class EducationForm(forms.ModelForm): class Meta: model = Education_uz fields = 'all' class ExperienceForm(forms.ModelForm): class Meta: model = Experience_uz fields = 'all' class RecommendationForm(forms.ModelForm): class Meta: model = Recommendation_uz fields = 'all' class OtherDocumentsForm(forms.ModelForm): class Meta: model = OtherDocuments fields = 'all' My models: # Create your models here. language_choices = [('1', 'Билмайман'), ('2', 'Ёмон'), ('3', 'Лугат ёрдамида'), ('4', 'Ўртача'), ('5', 'Яхши'), ('6', 'Жуда яхши'), ] approve_choices = [('Yes', 'Ха'), ('No', 'Йўк')] agreement_choices = [('Yes', 'Ха'), ('No', 'Йўк')] class UserForm_uz(models.Model): rasm = models.ImageField(upload_to='rasmlar',null=True,blank=True) lastName = models.CharField(max_length=200) firstName = models.CharField(max_length=200) middleName = models.CharField(max_length=200) birthData = models.DateField() nation = models.CharField(max_length=50) birthPlace = models.CharField(max_length=250) marriage_status = models.CharField(max_length=20) children = models.CharField(max_length=20) militaryResp = models.CharField(max_length=150) language_uzbek = models.CharField(choices=language_choices,max_length=150) … -
How to get data from User related model to template
I have Profile model in addition to native User model. Since user is logged in, I need to load avatar image to all pages in frontend. I need something like this: {% if request.user.is_authenticated %}<img src={{ profile.avatar }}>{% endif %} How I can do that? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='media/avatar/', verbose_name='Аватар', default='media/avatar/default_avatar.jpg') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Setting a lazy reference to a django serializer class
I have two models which has a field reference to each other. Both were in seperate files, but i decided to put them in a single file to avoid circular import bugs. However, unlike making a lazy reference to a django model class, i can't seem to make it work here class QuestionAnsweringModelResultsSerializer(ModelSerializer): answers = AnswerAnsweringModelResultsSerializer(many=True) images = QuestionAnsweringModelImagesResultsSerializer(many=True) written_answer_marking_settings = QuestionMarkingSettingsSerializer() parent_question = QuestionResultsSerializer() procedural_answers = ProceduralAnswerAnsweringSerializer(many=True) # the field below makes reference to the class below fill_in_the_blanks_answers = FillInTheBlanksAnsweringModelResultsSerializer(many=True) class Meta: model = QuestionAnsweringModel fields = '__all__' class FillInTheBlanksAnsweringModelResultsSerializer(ModelSerializer): # the field below makes reference to the class above question = QuestionAnsweringModelResultsSerializer() class Meta: model = FillInTheBlanksAnsweringModel fields = '__all__' I get the error a class is not defined error where class is the name of the Serializer Class -
Django importing a custom user model
I have a Django app with a custom user model. I am attempting to import this model into another app. So far I can't figure out how to do this. The customer user model at accounts/models.py is from django.db import models from machina.core.db.models import get_model from django.db.models import Q from django.contrib.auth.models import Group # signals imports from django.dispatch import receiver from django.db.models.signals import ( post_save ) Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): first_name = models.CharField(max_length=250, null=True) last_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) business_name = models.CharField(max_length=250, null=True) business_location_state = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft": 1}) business_location_county = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, related_name='county') business_location_city = models.CharField(max_length=1024, null=True) business_zipcode = models.CharField(max_length=12, null=True) The code I most recently tried to import this model is: from django.db import models from django.contrib.auth.models import User from django_tenants.models import DomainMixin, TenantMixin from django.utils.translation import ugettext as _ from localflavor.us.models import USStateField from accounts.models import CustomUser class Tenant(TenantMixin): user = models.ForeignKey('CustomUser', on_delete=models.SET_NULL, null=True) company_name = models.CharField(max_length=100) address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64) state = USStateField(_("state")) zip_code = models.CharField(_("zip code"), max_length=5) created_on = models.DateField(auto_now_add=True) When I attempt to start the server I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified … -
AWS EB CLI deployment Dango - Static files showing for web app but not showing for Admin panel
I have recently managed to setup and deploy my Django web app to AWS via EB CLI, everything looks fine on the web app however when I visit the admin panel I noticed the static files are not loading at all (but load fine on local server). I see on the S3 bucket admin static files were uploaded in the following structure (my app is called wfi_workflow): .elasticbeanstalk admin/ css/ fonts/ img/ js/ resources/ wfi_workflow/ Please see following relevant code in my project for static files: Settings BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') .ebextensions/django.config container_commands: 01_sh_executable: command: find .platform/hooks/ -type f -iname "*.sh" -exec chmod +x {} \; option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: wfi_workflow.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static /static_files: static_files aws:elasticbeanstalk:container:python: WSGIPath: wfi_workflow.wsgi:application .ebextensions/packages.config packages: yum: python3-devel: [] mariadb-devel: [] .platform/hooks/predeploy/01_migrations.ssh #!/bin/bash source /var/app/venv/*/bin/activate cd /var/app/staging python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py collectstatic --noinput Help is much appreciated on this, Thanks. -
Field 'maca2' expected a number but got 'Select'
class Maca(models.Model): class Maca2(models.IntegerChoices): Personal = 1, Work = 2, Transport = 3, __empty__ = _('Select') When I submit as empty value I got the following error Field 'maca2' expected a number but got 'Select'. -
@login_required decorator is not working (Django)
I am trying to build a social media like thing and have created the login and signup feature. For home page I have added login_required decorator and even added LOGIN_URL in settings.py but still I am able to access the home page without login i.e login_required decorator is not doing its job. Here is my view function code @login_required def home(request): return render(request, 'home/home.html') Here is my code in settings.py LOGIN_URL = '/login' Can anyone find out what might be the problem? -
Create and Retrive django session objects
I have customised the django default user table and used it for user signup and login. Now I need to create django session object to create a shopping cart (like that of an ecommerce website) which is user specific.How to create and retrive session objects in django?? -
related_name in many to many field
Below is my code. class Thing(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fav_thing_owner') favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_things') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return self.title class Fav(models.Model) : thing = models.ForeignKey(Thing, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='favs_users') # https://docs.djangoproject.com/en/3.0/ref/models/options/#unique-together class Meta: unique_together = ('thing', 'user') def __str__(self) : return '%s likes %s'%(self.user.username, self.thing.title[:10]) But I got confused related_name in ManytoMayFied. for example, in my code I can get user's Thing(my model name) using user.fav_thing_owner. But in ManyToManyField, I have two related_name(favorite_things, favs_users). user.favorite_things and user.favs_users get same object..? -
python single and multiple button operation
I have a concern on how to stimulate single or multiple button click operations. --code sample : .js file jQuery.ajax({ url : "/", type :"POST", data : { selected_obj : clicked_btn }) .py file object_selected = request.forms.get('selected_obj') # This (object_selected) return data like # data_returned = (0.48, 0.65, 2.32) -what i need is when the button clicked for the first time data_returned gets multiplied which it is no big deal. But when clicked for the second time either same or another button that has same output i need to (multiply the returned data) for the same or another button and sum it with the previous data(button clicked for the first time), and so on .. -
Django ORM DB Query Optimization
I have a Query that consists of two DB hits. which the first contains 'aggregate' - so it perform immediately. I want to know if I can reduce it to only one DB hit. The query is: "Find customers that their id's numbers are bigger than all of texas's customers id's." The two querysets are: highest_tx_id = Customer.objects.filter(state='TX').aggregate(Max('id')) res = Customer.objects.filter(id__gt=highest_tx_id['id_max']) Adding an example: >>> reset_queries() >>> highest_tx_id = Customer.objects.filter(state='TX').aggregate(Max('id')) >>> res = Customer.objects.filter(id__gt=highest_tx_id['id__max']) >>> connection.queries [{'sql': 'SELECT MAX("customer"."id") AS "id__max" FROM "customer" WHERE "customer"."state" = \'TX\'', 'time': '0.001'}] >>> res <QuerySet [<Customer: Customer object (550)>, <Customer: Customer object (551)>, <Customer: Customer object (552)>, <Customer: Customer object (553)>, <Customer: Customer object (555)>, <Customer: Customer object (661)>, <Customer: Customer object (665)>]> >>> connection.queries [{'sql': 'SELECT MAX("customer"."id") AS "id__max" FROM "customer" WHERE "customer"."state" = \'TX\'', 'time': '0.001'}, {'sql': 'SELECT "customer"."id", "customer"."fname", "customer"."lname", "customer"."address", "customer"."city", "customer"."state", "customer"."zip_code", "customer"."phone", "customer"."company_name" FROM "customer" WHERE "customer"."id" > 444 LIMIT 21', 'time': '0.001'}] >>> Any way to do these type of queries using 1 DB hit ? -
Don't render abel for id in django form
Is it possible not to render the for attribute of a label? I want <label>Text</label> instead of <label for="id_i">Text</label> ? -
why celery doesn't get the task in django?
i'm new in celery there is a simple task that I want to use celery in Django but in celery log there isn't any message to get task. these are my codes: celery.py: from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('kia', broker='redis://localhost:6379/0') app.conf.update( result_serializer='json', accept_content = ['application/json'], task_serializer = 'json' ) app.autodiscover_tasks() tasks.py: import section . . . logger = get_task_logger('__name__') @task(name="send_sms_task") def send_sms_task(text, phone_number): logger.info("sms sented") return sms(text, phone_number) views.py: import section . . . @api_view(['GET',]) @permission_classes((AllowAny,)) def TestSMS(request): if request.method == 'GET': x = send_sms_task.apply_async(["something", "somethingelse"]) data= {"OK"} return Response(data) sms.py: def send_sms(text,phone_number): print("an api service that work correctly") finally this is my tree project: ├── account │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── permisions.py │ ├── serializers.py │ ├── sms.py │ ├── tasks.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── db.sqlite3 ├── project │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py function in sms.py work without celery but when I try to use celery nothing happens in celery log in addition in 2 case(with celery and without it) I get 200 … -
Django repeated forms
I have a form with a dropdown select option with possible options of 1,2,3,4 or 5. Based on the user select option 'x', I render same form repeated 'x' many times. Upon submit, I try to fetch the data using following in my view userprofileForm(request.POST) but this fetches just the last entry or most recent entry and not all the 'x' entries. Here is the rough HTML for my rendered form. In this instance the user selects option 2 so the form has a div repeated 2 times. <form ... > <div> <label...> <input...> </div> <div> <label...> <input...> </div> </form> Upon hitting submit button, the view for registeration is triggered and like I explained above in the beggining doing userprofileForm(request.POST) does not fetch both the 2 entries but just the last one. How can this be fixed so I have all form data of both the divs and how do I access it? -
How to pass search input value in output
I have search bar that renders the list of elements that user whats to find. I'd like to pass the input value to output html so if user is searching for article 1 then I want to display above the list the query name. I tried to put query, lookup but it doesn't work. views.py def search_qa_results(request): query = request.GET.get('q') qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) qa_list = QA.objects.filter(lookups) context = { 'qa_list': qa_list } return render(request, 'search/search_qa.html', context) index.html <form action="{% url 'search_qa_results' %}" method="get" id="search"> {% csrf_token %} <div class="searchbar" id="autocomplete"> <input name="q" type="text" placeholder="Type your question" class="search_input"> <a href="{% url 'search_qa_results' %}" class="search_icon"><i class="fas fa-search"></i></a> <ul class="autocomplete-result-list"></ul> </div> </form> search_results.html {% extends 'base.html' %} <title>{% block title %}Q&A results{% endblock %}</title> {% block content %} <link rel="stylesheet" type="text/css" href="/static/search_qa.css"> <div class="d-flex justify-content-start"> Search results for my question: {{WHAT TO PUT HERE?}}</div> <div class="container h-100 pb-4"> <div class="d-flex justify-content-end h-100 pb-4"> {% for qa in qa_list %} <div class="card text-dark bg-light mb-3 text-left"> <a href="{{ qa.get_absolute_url }}"> <h5 class="card-header">Q: {{qa.title}}</h5> <div class="card-body"> <div class="card-title text-justify">A: {{ qa.answer }}</div> </div> <div class="card-footer"> <small class="text-muted">Published: {{qa.publish}}</small> </div> </a> </div> {% empty %} <p>No results</p> {% … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work
I would like to log out user if browser is closed. I added SESSION_EXPIRE_AT_BROWSER_CLOSE = True to my settings.py and the following function to my base.html file but it doesn't work. $(document).ready(function(){ $(window).on("beforeunload", function(e) { $.ajax({ url: logout_view, method: 'GET', }) }); }); What am I missing and how to solve it? I am using Django 3.2. -
Input Tag and spaces in Strings
model.py class Cartrecord(models.Model): cartid=models.AutoField(primary_key=True) cart_user=models.ForeignKey(User,on_delete=models.CASCADE) json_data=models.CharField(max_length=500,default="0") def __str__(self): return self.cart_user.username views.py param_cart=Cartrecord.objects.get(cart_user=request.user) params['cart']=param_cart params['cart_length']=len(param_cart.json_data) return params html <input id="cart_data" type="text" value={{cart.json_data}}> <input id="cart_length" type="hidden" value={{cart_length}}> enter code here cart.json_data is supposed to be printed as {"product7":{"0":1,"1":"USB cable","2":"250"},"product9":{"0":1,"1":"Sony Tv","2":"40000"},"product10":{"0":1,"1":"LG Refrigerator","2":"30000"},"product4":{"0":1,"1":"mobie","2":"10000"},"product6":{"0":1,"1":"bag","2":"1000"}} Instead im getting this {"product7":{"0":1,"1":"USB I have tried it with different sets of json data, but each time the string got sliced when it meets the space But later i have tried the same thing using textarea by replacing input tag, <textarea id="cart_data" type="text">{{cart.json_data}}</textarea> And i got my json string properly Can someone explain this behavior? -
How to Preview and Edit, Login the django model form after finishing the user signup in django?
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobile_number = models.IntegerField(blank=False, null=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] customer = models.BooleanField(default=False) vendor = models.BooleanField(default=False) id = models.AutoField(primary_key=True, editable=True) userid= models.CharField(max_length=100, unique=True, null=True) objects = UserManager() def __str__(self): return self.email forms.py class VendorCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['email','first_name','last_name','mobile_number'] def save(self, commit=True): user = super().save(commit=False) user.vendor = True if commit: user.save() return user views.py def VendorSignup(request): vendorform = VendorCreationForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendorform.is_valid(): new_user = vendorform.save() new_user.is_active = False new_user.save() return redirect('vendor_preview') else: vendorform = VendorCreationForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform}) def VendorPreview(request): details = CustomUser.objects.filter(id=request.user.id) return render(request,'vendor/preview.html', {'details':details}) My template: signup.html <div class="container"> <h1>VENDOR SIGNUP</h1><br> <form method="POST" action="{% url 'vendor_signup' %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Submit</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form> </div> preview.html <caption>Please, Check your details.</caption> <table class="table table-hover table-bordered mt-3"> <thead> <tr> <th scope="col">Email Address</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Mobile Number</th> </tr> </thead> <tbody> {% if details %} {% for data in details %} <tr> <td>{{data.email}}</td> … -
how export filtered data in django
I am using class based view to such for data and I want to export the output from search. The output is from two dates search. I use below code: class expenses_list(ListView): model = EXPENSES template_name = 'cashes/expenses_list.html' paginate_by=10 def get_queryset(self): filter_val1=self.request.GET.get("filter1","") filter_val2=self.request.GET.get("filter2","") order_by=self.request.GET.get("orderby","-date_of_operation") if filter_val1!="" and filter_val2!="": reqo=EXPENSES.objects.filter(Q(created_at__range= [filter_val2,filter_val1])).order_by(order_by) else: reqo=EXPENSES.objects.filter().order_by(order_by) return reqo def get_context_data(self,**kwargs): context=super(expenses_list,self).get_context_data(**kwargs) context["filter1"]=self.request.GET.get("filter1","") context["filter2"]=self.request.GET.get("filter2","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=EXPENSES._meta.get_fields() return context and I have this as interface enter image description here the following export code is not working as the value of date fields are empty value def exporexpensescsv(request,**kwargs): filter_val1=request.GET.get("filter1") filter_val2=request.GET.get("filter2") print(filter_val1) print(filter_val2) response=HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=expenses' + str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['Categoty','Beneficiary','Description','Operation Date','Amount','Account Number','Paymrnt Date','Status']) expes = EXPENSES.objects.filter(Q(created_at__range=[filter_val1,filter_val2])) # expes = EXPENSES.objects.all() for exp in expes: writer.writerow([exp.category,exp.beneficiary,exp.description, exp.date_of_operation,exp.amount,exp.account_number,exp.payment_date, exp.status]) return response but when I want to export with expes = EXPENSES.objects.all() it works well. Assist to be able to export the filtered data. -
Django - Вывод формы вопрос|вырианты ответов [closed]
помогите пожалуйста, нужно сделать вопросник(вопрос и варианты ответы) Сделал простую связанную модель: class Questions_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') def __str__(self): return self.title class Meta: verbose_name = 'Вопросы' verbose_name_plural = 'Вопрос' class Answers_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') correct = models.BooleanField(verbose_name='Правильный ответ') key_questions_set = models.ForeignKey(Questions_set, on_delete=models.CASCADE, related_name='question') Заполнил таблицы.Как вывести в шаблон вопрос и варианты ответов к нему в форме или это не через форму решается?Спасибо -
how to successfully upload BLOB images to django ImageField
I am using django rest framework(version 3.12.2) for my backend, and React/Next js in my front end. my goal is pretty straightforward, I want to upload BLOB images via POST request to django. but unfortunately I receive this error message {"photo_main":["The submitted data was not a file. Check the encoding type on the form."]} has anyone ever encountered this problem and was able to solve it? the model class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author') photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) description = models.TextField(blank=True) the view class RecipeCreate(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) queryset = Recipe.objects.all() serializer_class = RecipeCreateSerializer def perform_create(self, serializer): '''save the the current logged in user as the author of the recipe''' serializer.save(author=self.request.user) I'll appreciate every help that I can get, thanks in advance