Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to 'remember' some SQL queries
There's this line in the Django documentation: "When running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you’re debugging, but it’ll rapidly consume memory on a production server." So if I want to remember some queries when DEBUG=False on my server, how do I do it? Use Redis/memcached I guess? But they are key-value stores, so I will need to go over several files and change the code, right? What if I just want to cache a SQL query that's repeated often. The documentation around caching is mostly about template caching or storing key-value pairs. I couldn't find anything about caching full, often used SQL query. -
How django REST Framework works regarding cache and SQL requests
Working currently with DRF for my project, I decided to use a cache system (REDIS in that case) in order to limit the number of SQL requests directly to the DB. So I saw/read many pages on that topic, but I didn't find out my answer. on the DRF web site, they talk about to use the cache_page with the help of the decorator @method_decorator. Ok it works correctly but in the HTTP header, an expiration_date field appears, indicating to the browser to put in its cache the whole page and do not request anything until the end of the expiration date. So if the expiration is around current time + 5 minutes, during 5 minutes we "live" with the web browser cache, and if something change during that 5 minutes, we could not know it. Are you agree with that behavior of that decorator? Since I would like to be informed about any changes during that time, I update my code to cache all needed SQL requests. Like this if something change, I flush the cache and the next time, I will get the up-to-date datas. Here is an light example of a ModelViewSet: queryset = MyModel.objects.all().select_related(...).prefeth_related(...) cache.set('MyKey', queryset) … -
An unexpected effect appears when using django's Q
In [25]: Project.objects.filter(Q(change__date__date__range=('2020-04-28','2020-04-28'))&~Q(change__se__isnull=True)).count() Out[25]: 8 In [26]: Project.objects.filter(Q(change__date__date__range=('2020-04-28','2020-04-28'))&Q(change__se__isnull=False)).count() Out[26]: 9 enter image description here I don't know what the difference is -
GET Response with several models
I have two ViewSets. They have unique serializer and model. For example, CitiesViewSet and TypesViewSet: CitiesViewSet - [{"name":"Moscow"},{"name": "Kazan"} etc...] TypesViewSet - [{"id": 1, "name": "sample"}, {"id": 2, "name": "sample"} etc... ] I want to combine this ViewSets to one GET Response. For example, I can do GET request and I will get looks like - { "cities": [ {"name": "Moscow"}, {"name": "Kazan"} etc... ], "types": [ {"id": 1, "name": "sample"}, {"id": 2, "name": "sample"} etc. ] } How to create it? -
Django Model Foreign Key to text
There is a problem, there is a Book model and in it title is the name of the book, and author is the ForeignKey of the Author model where there is a name field. I need to get a Python list and for this I do books = list(Book.objects.values('title', 'author'), but the result is a list [{'title': 'Harry Potter', 'author': 1}]. How do I make sure that the author is instead of the unit? -
Display a checkbox choice as "disabled" in django 3.0. ModelForm
I've been looking around for similar issues and I've yet to come across a solution to my specific problem. What I aim to do is display a checkbox like this. Where only the signed in (authenticated) user has the ability to select/deselect the checkbox corresponding to his profile. In this case, mindspace is authenticated I reached this point by trying this solution: But as one of the comments suggest the create_option method doesn't get called through the CheckboxSelectMultiple class. As a result I messed a bit with the SelectMultiple class, like-so. class CheckboxCustom(forms.SelectMultiple): def __init__(self, *args, **kwargs): self.input_type = 'checkbox' self.checked_attribute = {'checked': True} self.template_name = 'django/forms/widgets/checkbox_select.html' self.option_template_name = 'django/forms/widgets/checkbox_option.html' self.allow_multiple_selected = True self.request = kwargs.pop("request") self.option_inherits_attrs = False # print(options super(CheckboxCustom, self).__init__(*args, **kwargs) def create_option(self, *args, **kwargs): options_dict = super().create_option(*args, **kwargs) selected = options_dict['selected'] print(selected) option_attrs = self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} # if selected: # options_dict['attrs']['multiple'] = True if options_dict['label'] != str(self.request.user.profile): options_dict['attrs']['disabled'] = True # print(val) return options_dict And used this as a widget. However, no matter if I select or deselect one of the two checkboxes (from the corresponding profile), the other will get deselected both in the template and the database. Same thing happens … -
Django one to many get all underlying records
I'am creating a django application with a database including the following tables: I created the models as following: class Group(models.Model): id = models.AutoField(primary_key=True, editable=False) text = models.CharField(db_column='Text', max_length=4000) class Meta: db_table = 'Group' class Filters(models.Model): id = models.AutoField(primary_key=True, editable=False) text = models.CharField(db_column='Text', max_length=4000) group_id = models.ForeignKey(Group, on_delete=models.CASCADE, db_column='GroupId') class Meta: db_table = 'Filters' The goal is to call an endpoint and return a list with all Groups and underlying Filters. Is it possible to achieve this? If possible, I want it in a Serializer class. I know I can get the group of a filter record, but is this also possible the otherway around? -
FileField is valid even when empty
I have a parent and child model: class Parent(models.Model): name = models.SlugField(max_length=45, null=False) tags = TaggableManager() class Child(models.Model): version = models.CharField(null=False, max_length=10, default='1.0') upload = models.FileField( upload_to=hack_upload_path, blank=False, null=False ) parent = models.ForeignKey( Parent, on_delete=models.CASCADE, related_name='versions' ) class Meta: get_latest_by = "upload_date" verbose_name = "version" verbose_name_plural = "versions" def __str__(self): return f'v{self.version}' A parent basically has multiple children which are just file uploads with some more data. So I have a form where I want to create a Parent and one Child at the same time, so I made this form and view: class ParentForm(ModelForm): class Meta: model = Parent fields = [ 'name', 'tags' ] ChildFormset = inlineformset_factory( Parent, Child, fields=( 'version', 'upload' ), extra=1, max_num=1, can_delete=False, ) class ParentCreateView(LoginRequiredMixin, CreateView): form_class = ParentForm template_name = 'new.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['versions'] = ChildFormset( self.request.POST, self.request.FILES, instance=self.object ) else: data['versions'] = ChildFormset(instance=self.object) return data def form_valid(self, form): form.instance.seller = self.request.user context = self.get_context_data() versions = context['versions'] if versions.is_valid(): # It comes here even though the upload field is empty! self.object = form.save() versions.instance = self.object versions.save() return super().form_valid(form) else: return self.render_to_response( self.get_context_data( form=form, versions=versions ) ) And It passes the if versions.is_valid(): check even though … -
How to add for loop iteration django templates
I have a template page and I have used models required in views.py file. The template page consists of cricket statistics and it consists of tb, tr tags along with div tags. My question is where should I use the for loop template tags to replace the values as per the model data. {% extends 'base.html' %} <!DOCTYPE html> <html> {% block content %} <head> <meta charset="utf-8"> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/details.css' %}"> <style> td,tr { height: 10px; width: 10px; } th, td { padding: 10px; } </style> </head> <body> <div class="page"> <div id="page-wrapper" class="container" style="display:inline-block;"> <div id="shosh" class="ad-unit shosh-embed" style="height:0; width:980px; text-align:center;"></div> <div style="margin-top:20px;"></div> <div> <div class="cb-col cb-col-100 cb-bg-white"> <div class="cb-col cb-col-20 cb-col-rt"><img height="152" width="152" title="profile image" src="{{PlayerStructure_details.imageUri.url}}"></div> <div class="cb-col cb-col-80 cb-player-name-wrap"> <h1 itemprop="name" class="cb-font-40">{{PlayerStructure_details.firstname}} {{PlayerStructure_details.lastname}}</h1> <h3 class="cb-font-18 text-gray">{{PlayerStructure_details.country}}</h3></div> </div> <div class="cb-col cb-col-100 cb-bg-grey"> <div class="cb-col cb-col-33 text-black"> <div class="cb-hm-rght"> <div class="cb-font-16 text-bold"> Personal Information</div> <div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Born</div> <div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BirthDate}} </div> <div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Birth Place</div> <div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.BirthPlace}} </div> <div class="cb-col cb-col-40 text-bold">Jersey No</div> <div class="cb-col cb-col-60"> {{PlayerStructure_details.JerseyNumber}} </div> <div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Role</div> <div class="cb-col cb-col-60 cb-lst-itm-sm"> {{PlayerStructure_details.Role}} </div> <div class="cb-col cb-col-40 text-bold cb-lst-itm-sm">Batting Style</div> … -
Django - Retrieve unique rows by latest date/column
I have the following table: class AccountData(models.Model): id = models.BigIntegerField(primary_key=True) date = models.DateField() last_update = models.DateTimeField() account = models.ForeignKey('Account', models.DO_NOTHING, db_column='account', related_name="values") value = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) Given a queryset/list of ID's (unknown amount how many ID's, could be None/0) Is there a way to get the latest row for each account, then sum the value? The part I'm really struggling with is only retrieving the latest row per account. I know I can get the accounts that are in the given queryset by doing: accounts = [1, 4, 65] AccountData.objects.filter(account__in=accounts) Just need to figure out how I can only get the rows where "date" is as close to "now" as possible. Thus resulting in having unique rows (only 1 row per account) -
Must i install django every time am starting a project in pycharm
i am just starting a new project on my pycharm i start a new project and run my server but am getting this error message couldn't import django, Must i install django for every project am creating? -
Please help me how can i add some option like inserting images, bold italic inserting link in body
it is a screenshot I listen about markdown but I don't know how to use please suggest some good alternative or tell me about markdown Please check it and tell me a fix. -
Django set logged in user inlineformset_factory
hello Everyone I'm trying to build an application where I can add multiple forms but I am facing a problem when trying to add current logged in user Exception Value:'list' object is not callable @login_required(login_url='login') def addIncome(request, month_id): monthname = Month.objects.get(pk=month_id) monthnameid = Month.objects.get(id=month_id) monthes = Month.objects.all() newForm = inlineformset_factory(Month, IncomeAmount, fields=('income_Name','incomeAmount','incomeCurrency'),can_delete=False, extra=5) if request.method == 'POST': form = newForm(request.POST, instance=monthname) if form.is_valid(): newForm = form.save(commit=False) print(type(newForm)) newForm.user = request.user newForm.save() return redirect(home) else: monthes = Month.objects.all() monthname = Month.objects.get(id=month_id) month = newForm(instance=monthname) context = {'form': newForm, 'month': monthname, 'monthes':monthes} return render(request, 'add.html', context) -
How to count foreign keys in django
I have a project with courses where every Course has Sections, and every Section has Videos, I want to count number of sections in each course, and count number of videos in each Section. How to implement that? views def CourseView(request,slug): course = get_object_or_404(Course,slug=slug) sections = CourseSections.objects.filter(course__title=course.title) videos = SectionVideos.objects.filter(section__course__title=course.title) return render(request,'courses/course_detail.html',{'course':course,'sections':sections,'videos':videos}) models class Course(models.Model): title = models.CharField(max_length=255) class CourseSections(models.Model): title = models.CharField(max_length=50) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True) class SectionVideos(models.Model): title = models.CharField(max_length=50,null=True) video = models.FileField(upload_to='courses/course_videos',max_length=100) section = models.ForeignKey(CourseSections,on_delete=models.CASCADE,null=True) -
Redirecting To a New Angular Application After Login and Subscription Success
Good Day Everyone, Please I am working on a personal project on Angular, I have two angular applications, the main angular application and the second angular application to redirect to after login and subscription has been validated. The Only issue now is how to make use of the home.component.html of the second application which contains different menu or navbar items but each time i redirect to the second application, the items or menu showing on the navbar are the main or default application component.html but with the second angular application contents. I also discovered that second application was not generated with any index.html file. Please I need help on how to go about this. In summary two angular applications one acting as default (thriller page), the second to display the real contents for movies. How can i implement the default application having its own menu and the second application having its own menu as well. Thanks -
Repeated query in Django View
Good Morning, I have repeated Views in Django app, I am pretty sure there is a better solution to this situation. class BaseMixin: model = Post paginate_by = 9 class PostPostgresList(BaseMixin, ListView): template_name = "blog/postgres_field.html" def get_queryset(self): return Post.published.filter(field=Category.objects.get(name='PostgreSQL')) class PostDjangoList(BaseMixin, ListView): template_name = "blog/django_field.html" def get_queryset(self): return Post.published.filter(field=Category.objects.get(name='Django')) Field in model post is ForeignKey, so I need to put in query instance of the Category. Perhaps I should create some function where I could insert for instance name='Django' and put this function in utils? Thanks in advance for any advise. -
Django Password Validators: If any three of the validations pass user can go ahead
I am looking at how can we set the number of validations that must pass to allow the user to set the password. For example, we have these 5 validtors: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'registration.validators.CustomPasswordValidator',} ] We want if the user password passes any of the 3 requirements from them. Users can create an account. Any idea how can we do that in Django? -
how to migrate from postgres to phpmyadmin mysql django
our university has MySQL 5.6 server with phpMyAdmin, and my django project uses postgresql. and we cannot deploy project. any help? -
Django & React Deployment on VPS
I'm a newbie trying to deploy a Django backed react app. Please advise. What I've created: An app initiated with create-react-app, fully functional locally; A Django api serving the data They 'talk' perfectly to each other, but they are built separately Questions: I'm not sure how to incorporate them into one app for deployment. This post by VALENTINO GAGLIARDI is very helpful. But it seems like it's not suitable for an app initiated with create-react-app? Should I learn webpack for deployment? I have experience deploying a fully functional Django e-commerce website and it's up and running. Django handles both frontend and backend via many Django templates. I used Gunicorn and Nginx for serving the website on a VPS (Ubuntu 18). It's all quite confusing for me to deploy ONE website, and it seems to me, with having to serve TWO apps at the same time under one domain name? Any pointers for what knowledge should I acquire before completing this task? -
403 forbidden CSRF verification failed. Request aborted
for my pizza orders website, I am getting the above error on every time I try to make browser refresh cache by Ctrl^F5. the view for the login function goes as follows: @csrf_protect def login(request): username = request.POST.get("username") password = request.POST.get("password") myUser = authenticate(request, username=username, password=password) if myUser is not None: auth_login(request, myUser) context = { "toppings" : Topping.objects.all(), "subs" : Sub.objects.all(), "pastas": Pasta.objects.all(), "salads": Salad.objects.all(), "platters": DinnerPlatter.objects.all(), "username": username } return render(request, "orders/menu.html", context) else: return render(request,"orders/error_login.html") and the html code for the index.html and the menu.html both have {% csrf_token %} inside the forms as follows: index.html - <div class="login_box"> <form action="{% url 'register' %}" method="POST" class="p_signin_form"> {% csrf_token %} ... </form> <form action="{% url 'login' %}" method="POST" class="p_login_form"> {% csrf_token %} ... menu.html - <div class="make_an_order" id="order"> <h2>Pizza Order</h2> <form id="form_pizza_order" class="form_pizza_order" method="post"> {% csrf_token %} ... so what seems the problem? thanks. -
Django: Writing a custom UserManager for AbstractUser class, in order to handle foreign keys during superuser creation
I have an AbstractUser class as following in my models.py file: class UserModel(AbstractUser): some_field = models.ForeignKey(SomeOtherModel, on_delete = models.CASCADE) # other fields Since this is a user model, I am required to use the same to create a superuser but I am unable to handle the foreign key some_field while using the createsuperuser command. I have read at places that I need to add REQUIRED_FILEDS = ['some_field'] and also create a custom UserManager to handle it, but it is all very unclear to me: Can I create a custom UserManager for an AbstractUser class (and not an AbstractBaseUser class)? If yes then how to do it? Any code example or reference document will be helpful. Is there any other way to solve this problem? I just need to handle this one field during superuser creation. NOTE: I have initialized AUTH_USER_MODEL in settings.py I am a beginner at Django programming so any further reference, documentation or tutorials on handling user model will be very useful for me. Thanks in advance! -
How to integrate djangoCMS with existing django project
I am new to Django-CMS. I have a Django project with multiple apps to manage specific data. I want to add a CMS platform to my project to let some users contribute to publishing content. The content would be a simple contact page or a complicated page including text, images, as well as charts and report tables of data stored in DB via the existing Django project. I don't have any idea how to add djangoCMS to my existing project. How I can integrate djangoCMS as a new app in my project? Or is it a better idea to have a separate CMS and show data via REST API of the existing project? Can I use Django-CMS plugins to publish my reports via CMS? Is it needed to have a separate database for CMS? Many thanks in advance. -
Django URL gets called twice and crashes view
I am trying to implement a payment system now from the company documentation, I am expecting their api to call my project at http://127.0.0.1:5000/cart/payment/verify/?flwref=FLW-MOCK-5254aaf8272ae6c1ebbeaf754a75509b&txref=user-1-cart-40 and from the request tab the right url is returned. However there is no response to that url instead immediately see a get request with the url http://127.0.0.1:8000/cart/payment/verify/?resp={%22name%22%3A%22opop%22%2C%22data%22%3A{%22data%22%3A{%22id%22%3A1249370%2C%22txRef%22%3A%22user-1-cart-22%22%2C%22orderRef%22%3A%22URF_1588046289399_3226935%22%2C%22flwRef%22%3A%22FLW-MOCK-d92dbe44cad98158ebf026c29eaf91df%22%2C%22redirectUrl%22%3A%22http%3A%2F ...} I have no idea what is causing this and was hoping someone can help me track it down. Views @csrf_exempt def verifyPayment(request): # ref = json.loads(request.GET['resp']) # ref_code = ref['tx']['txRef'] ref_code = request.GET.get('txref') if ref_code != None: cart_id = ref_code.split('-')[3] cart = Cart(request, id=cart_id) data = { # this is the reference from the payment button response after customer paid. # "txref": "user-%s-cart-%s"%(request.user,cart.cart.id), "txref": ref_code, # this is the secret key of the pay button generated "SECKEY": "FLWSECK_TEST" } if cart.items_available(): r = requests.post( 'https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify', data=data) response = r.json() if response['status'] == 'success': # confirm that the amount for that transaction is the amount you wanted to charge if response['data']['chargecode'] == '00': # a = cart.summary_delivery() if response['data']['amount'] == float(cart.summary_delivery()): print("Payment successful then give value") payment = response cart.mark_items_paid() cart.complete(request, cart_id) cart.sendResturantOrder(cart.groupCartOrders(), response['data']['meta'][0]['metavalue']) payment = 'success' else: payment = "failure" return render(request, 'payment/payment.html', {'payment': payment}) def processPayment(request): … -
django fullcalender refetching events not workig
I am trying to implement a fullcalendar in django. All the functions are working fine, but the calendar doesn't get refreshed if I use refetchevents or rerender events calendar.fullCalendar('refetchEvents');. If i reload the page the events are showing up, but i want to see the changes without reloading the page. Any idea why is it not working? Models: from django.db import models class Events(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255,null=True,blank=True) start = models.DateTimeField(null=True,blank=True) end = models.DateTimeField(null=True,blank=True) def __str__(self): return self.name urls: from django.contrib import admin from django.urls import path from calend import models from calend.views import * from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('', calendar, name='calendar'), path('add_event/', add_event, name='add_event'), path('update/', update, name='update'), path('remove/', remove, name='remove'), ] views: from django.shortcuts import render from .models import Events from django.http import JsonResponse def calendar(request): all_events = Events.objects.all() context = { "events":all_events, } return render(request,'calendar.html',context) def add_event(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) event = Events(name=str(title), start=start, end=end) event.save() data = {} return JsonResponse(data) def update(request): start = request.GET.get("start", None) end = request.GET.get("end", None) title = request.GET.get("title", None) id = request.GET.get("id", None) event = Events.objects.get(id=id) event.start = start event.end = end event.name = title event.save() … -
Deployment error to AWS using psql and django
I am currently building a Django webapp as a front end to my Postgresql database. I am using elastic beanstalk to deploy to AWS (the database also lives on AWS). The website works locally (it's just a simple table at the moment) but whenever I run eb deploy I get the following error: >"2020-04-28 10:23:56 ERROR [Instance: i-0e140fa936b76bee1] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. 2020-04-28 10:23:56 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]." Sorry in advance if this may lack info, any feedback would be much appreciated :)