Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do you know why pip list shows one installed version but then python shell shows another?
I have created a virtual environment. I activate it with conda activate my_venv. I do pip list and check statsmodels version. result -->0.12.1 I do pip freeze. The same result. I get inside of the python shell and execute the next code: import sys import statsmodels print(sys.prefix) print(statsmodels.__version__) the output: '/home/skootik/anaconda3/envs/prodenv' '0.10.2' Does anybody know why? Thank you in advance -
aggrigate on many to many fields
i want to create a report for sum of duration that a adviser advise on this month. my model : class Adviser(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='adviser') patients = models.ManyToManyField('patient.Patient', through='adviser.AdviserPatient', related_name='advisers') class AdviserPatient(models.AbstractBaseModel): adviser = models.ForeignKey('adviser.Adviser', on_delete=models.PROTECT, related_name='adviser_patient') patient = models.ForeignKey('patient.Patient', on_delete=models.PROTECT, related_name='adviser_patient') duration = models.SmallIntegerField() assign_date = models.DateField(auto_now_add=True) release_date = models.DateField(null=True, blank=True) class Patient(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='patient') my query : ended_advise_this_mouth = Adviser.objects.annotate( total=Case(When( adviser_patient__release_date__gte=start_of_month(), adviser_patient__release_date__lte=end_of_month(), then=Sum('adviser_patient__duration')), default=Value(0), output_field=IntegerField())) but with this query i get response like that : <QuerySet [<Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [2 vahid imanian]>]> as you see adviser 1 repeat 6 time with separate total . when i use method values('id') or use distinct() not effected in result . my db is mysql and cant use distinct('id'). please help me . is there any way to use django-rest-framework serializers for this queryset? -
Deleting newline by python (Django) by taking string by textarea in html but the answer is wrong. WHY?
print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" print(djtext) for char in djtext: if char !="\n": analyzed=analyzed + char print(analyzed) suppose newlineremove is on and the input in textarea(html) is: dam dam djtext=request.GET.get('text','default') OUTPUT: on dam dam dam dam dam but it should have been: on dam dam dam dam damdam -
Use condition in update_or_create of django (DRF)
Here is my Serializer for API: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'name', ] def create(self, validated_data): from django.db.models import F, Case, When instance, created = self.Meta.model.objects.update_or_create( merchant=validated_data.pop('merchant'), client_id=validated_data.pop('client_id'), defaults={ 'name': Case( When(is_synchronizable=True, then='test'), default=F('name') ) } ) return instance I want to update the name just when is_synchronizable is True. But I get this error: django.core.exceptions.FieldError: Cannot resolve keyword 'test' into field. -
Django REST api Parent and child componet to use react js form submit as it is DRA?
guys i am beginner React js. i want get as it is rest API drop-down list box have to create in react. so how to do it ? could you guy please give way method -
How to create slug of many to many fields in django?
I want to make slugs on post save for my model using three fields one charfield and two ManytoMany Fields but getting error during saving. Here is my code: Heading ##class product(models.Model): id = models.AutoField(primary_key=True) image = models.ForeignKey(all_images, verbose_name='Product Images', on_delete=models.CASCADE, related_name='proimages') ProductName = models.CharField(max_length=200, null=False,default="None", blank=False,verbose_name="Product Name") CategoryName = models.ManyToManyField(category,related_name='procat', blank=False,verbose_name="Category Name") SubcatName = models.ManyToManyField(subcategory,related_name='prosubcat', blank=False,verbose_name="Sub-category Name") description = RichTextUploadingField(blank= False,verbose_name="Description") price = models.IntegerField(default=100, null=True, blank=True, verbose_name='Price') slug = models.SlugField(max_length=55, blank=True, null=True) def get_slug(self): slug = self.ProductName try: for items in self.SubcatName.all(): slug +=items.name try: for items in self.CategoryName.all(): slug +=items.CategoryName except: pass except: pass return slugify(slug) def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_slug() super(product, self).save(*args, **kwargs) -
How can I see all possible attributes of an context variables in django templates
I am trying to use double model form at once in one single view, I am using django-betterforms to merge those, It merged all fields from two model in one single form. I know I can use different class and id to separate them, But I can't extract them in template form, like {{ form }} it will place full form in template, I can render all field like this {% for field in form %} {{ field }} or anything {% endfor %} My question is how can I know all the possible attributes of this field like {{ field.* }} *=anything kind of dir(field). This is a problem I have facing but what will be solution to find all attributes or separate two forms in two side. Basically I need to separate two model, those will save in same time with same view but in front-end those will be different. Thanks in advance!!! -
Post gis raw query returns empty set on st_asmvt
I am trying to generate dynamic mvt tiles using django. I used the sql query given in the documentation to generate the tiles. I changed the z,x,y as per my requirements. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon WHERE ST_Intersects(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; This gives empty result. But if i only run the following query it returns the results: SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon And if i try to run the following query it again returns the empty set. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; -
How to upload gist(CSV) file to Django app database?
Good day! I need to upload info from gist file(Myfile.CSV) to my Django app database? Can anybody give me suggestion how to do it more correctly? I have gist file which is located on github. It's a csv file wich containes 3 columns(number, name, colour) and several rows. So I need to upload(save) to existing Django project info from this file and after it change names of columns to different one. -
AttributeError: 'WindowsPath' object has no attribute 'endswith'
When I run my project this error comes. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\checks.py", line 9, in check_finders finder_errors = finder.check() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 81, in check if prefix.endswith('/'): AttributeError: 'WindowsPath' object has no attribute 'endswith' -
How to pass a variable value in Django template URL name?
I need to pass the variable value in the Django template URL name. At first, I want to query the URL name from the database then the query URL name-value use in the Django template like as view.py: def user_home(request): user = request.user role = user.employinfo.designation element = role.sbtitleelement_set.all() context = { 'sb_title_element':element, } return render(request, 'home/index.html', context) Template: {% for element in sb_title_element %} <li class="nav-item"><a href="{% url 'element.url' %}" class="nav-link">{{element}}</a></li> {% endfor %} Here "{% url 'url-name' %}" i want to use URL name form {% url 'element.url' %}. How is it possible? Please help me to solve the problem.... -
How to write search query that gets input from separate fields in Django?
I need to create a search query that takes input from these fields. I would appreciate actual code example. I can query using one search field. But my project requires separated fields. Thank you. enter image description here -
Multiple Django services + centralised user authentication, management and provisioning
I have multiple running Django services, each with their own databases, and I'm trying to implement an authentication solution to achieve the following: Single Sign On. e.g. user can login to an authentication service at accounts.example.com, and when they browse to service-a.example.com or service-b.example.com, they will automatically be authenticated without any further login action. Centralised User Management. e.g. creating, updating an deleting accounts will all be done at accounts.example.com by an admin account Ability to provision service resources to new users even before the user's first login to the service. e.g. With an admin account, I created UserA at accounts.example.com, and then in service-a.example.com I would want to be able to assign tasks to UserA even if UserA has not first logged in to service-a.example.com yet. I have looked through and experimented with a number of SSO solutions such as OpenID, SAML, CAS, but it seems that with any of them I can't seem to achieve Point #3. This is because even if the new user account is created in the Identity Provider, the user object will not exist in the Django service until the user first login to the Django service (which only then the user object will be … -
What is the maximum length of TextField in django while using PostgreSQL
i wanna known what is the maximum length of TextField in django models while using PostgreSQL.. I just know Mysql uses the longtext data type to store the content, which can hold up to 4 Gigabytes but i wanna know what is the maximum length of TextField in django models while using PostgreSQL and if can increase it ? -
crispy form field type attribute ignored
I am trying to use crispy forms in my django app and I can not seem to get the type attribute to set on a field. #forms.py class ReminderForm(ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.helper=FormHelper() self.helper.layout = Layout( Fieldset('Reminder', Row( Div(Field('message'),css_class="col"), ), Row( Div(Field('messagetype'),css_class="col-md-6"), Div(Field('account'),css_class="col-md-6"), ), Row( Div(Field('reminddate',type="date"),css_class="col-md-6"), Div(Field('duedate', type="date"),css_class="col-md-6"), ), ) ) class Meta: model=Reminder exclude=['sentdate','confirmdate','completedate'] my modal form {% load cms_tags crispy_forms_tags %} <div class="modal fade" id="{{formid}}" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{title}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form > {% crispy form %} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> rendered html for the inputs below show reminddate and duedate style with type="text" <div class="modal-body"> <form> <fieldset> <legend>Reminder</legend> <div class="form-row "> <div class="col"> <div id="div_id_message" class="form-group"> <label for="id_message" class=""> Message </label> <div class=""> <textarea name="message" cols="40" rows="10" class="textarea form-control" id="id_message"></textarea> </div> </div> </div> </div> <div class="form-row "> <div class="col-md-6"> <div id="div_id_messagetype" class="form-group"> <label for="id_messagetype" class=""> Messagetype </label> <div class=""> <select name="messagetype" class="select form-control" id="id_messagetype"> <option value="">---------</option> <option value="email">Email</option> <option value="sms">Text Message</option> <option value="internal">Internal Website</option> </select> </div> </div> </div> <div class="col-md-6"> <div id="div_id_account" class="form-group"> <label for="id_account" class=""> Account </label> … -
How to filter date According to Today Current Date in Django?
I am trying to filter date in Django according to current date, But it's displaying mr 0 results, Please let me know Where I am mistaking. Hers is my models.py file... class Customer(models.Model): name = models.CharField(null=True, blannk=True) customer_date = models.DateTimeField(null=True, blannk=True) here is my views.py file, where i am trying to get date according to today date... from datetime import datetime, timedelta, time, date def getdate(request): today=datetime.today() customer_data = Customer.objects.filter(customer_date=today).count() print(customer_data, "Count Values") -
How to send email in django with attaching dynamic context passed invite.ics file?
My is a simple celery asyncronus task which sends email attaching invite.ics file, but i dont know how to pass dynamic context in invite.ics file? my task file for sending email -> import os from django.conf import settings from celery import shared_task from time import sleep from django.core.mail import send_mail from django.core.mail import EmailMessage @shared_task def send_email_with_celery(company, date, sender, receiver): email = EmailMessage(f'Interview with {company}', f'You have been selected for the interview at time {date}', f"{sender} from {company}", [f'{receiver}']) email.attach_file('invite.ics', 'text/calendar') email.send() return None my invite.ics file--> BEGIN:VCALENDAR VERSION:2.0 PRODID:-//hacksw/handcal//NONSGML v1.0//EN BEGIN:VEVENT UID:{{ sender }} <-- dynamic sender context DTSTAMP:19970714T170000Z ORGANIZER;CN=Sonu Sud:MAILTO:{{ receiver }} <-- dynamic reciever context DTSTART:20201005T110000Z <-- should be dynamic time value in this format DTEND:20201005T114500Z <-- should be dynamic time value in this format SUMMARY:Interview with {{ company }} <-- should be dynamic Company name GEO:48.85299;2.36885 END:VEVENT END:VCALENDAR i want to pass the context like this -> context = { "sender":, "receiver":, "start":, "end":, "company": } how to pass the context in invite.ics file...? -
Django Class-based view pass custom request
I am using unittest in my project, and the following is my test code. import unittest from unittest.mock import patch, Mock from lists.views import NewListView @patch('lists.views.NewListForm') class NewListViewUnitTest(unittest.TestCase): def setUp(self): self.request = HttpRequest() self.request.POST['text'] = 'new list item' self.request.user = Mock() def test_passes_POST_data_to_NewListForm(self, mockNewListForm): NewListView(self.request) # The important bit mockNewListForm.assert_called_once_with(data=self.request.POST) I want to pass a custom request, which as you see has some POST data. I had originally had a view, so I could pass a custom request. Now, with a class based view, how can I do that? I am currently getting an error which says: TypeError: __init__() takes 1 positional argument but 2 were given I did try NewListView.as_view(self.request), but that says TypeError: as_view() takes 1 positional argument but 2 were given I know you should use the Django test client and make POST requests using the URL, not calling the actual view, but this is how they did it in the book I am currently studying (Test-Driven Development with Python by Harry Percival. Unfortunately, he doesn't seem to have updated his appendices, where he teaches the class based view stuff, so I am doing it my self. Or trying to.) Thanks. -
How to create one migration file for one model file in django
In a django app i created models folder, in which folder contains multiple model files, When i run command python manange.py makemigrations <app_name>, it generates one migration file for all the *.py models. So, is this possible to generate multiple migration files for multiple *.py models. -
How to send from JS to Python Django Server Backend
I have started learning about Javascript and I am trying to include it to my Django Project to calculate the time users are on the page so I found the answer to this question HERE but I am unable to implement it as it is the first time for me to link between JS and Django Python backend. Here is what I understand: Step 1 Add the following script for all HTML templates: <script src="timeme.js"></script> <script type="text/javascript"> TimeMe.setIdleDurationInSeconds(15); TimeMe.setCurrentPageName("my-home-page"); TimeMe.initialize(); window.onload = function(){ setInterval(function(){ var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2); }, 25); } </script> Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","ENTER_URL_HERE",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); xmlhttp.send(timeSpentOnPage); My questions are: Where should I place the 2nd Code? Should I start a new app in my django project to read the file sent from the JS? What is the TimeMe.setCurrentPageName("my-home-page"); what variable should I add? is it the HTML name of the name in the URL? -
Superuser dumpdata/loaddata in Django
I'm having a trouble on how can I dump a encrypted password data into authuser table in django, Currently I'm using python manage.py loaddata fixtures.json to dumpdata into database it works fine but the password is not encrypted, how can I encrypt it when using loaddata?. Is there any expert can share solutions or ideas with this problem, Much appreciate! [{"model":"auth.user", "pk" : 2, "fields" : {"password" : "superadmin", "is_superuser" : "1", "username" : "superadmin", "first_name" : "name" , "last_name" : "lname" , "email" : "a@gmail.com" , "is_staff" : "1", "is_active" : "1" }] -
Weird Concatenated Strings in browser URL
I am learning Django with materials in which the tutor used an old version of Django. I have been able to transform some of the codes into the currently supported version with the aid of some other recent material and by browsing through related questions here. The problem I have now is though everything works but the browser URL will display some weird strings concatenated together with the slug. Kindly help me point out what modifications I need to make on the following codes. Thanks in advance. This is the corresponding error part of the browser URL: (%3FP2020%5Cd%7B4%7D)/(%3FP11%5Cd%7B2%7D)/(%3FP03%5Cd%7B2%7D)/(%3FPsecond-post%5B-%5Cw%5D+) This is the method in the models.py: def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) These are the codes in the urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/', views.post_detail, name='post_detail'), ] These are the codes in views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request, category=None): posts = Post.published.all() return render(request, 'list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'detail.html', {'post': post}) -
Guys I can't use my heroku domain name to generate a new Facebook access_token using postman like I used to do with my localhost
I did all steps mentioned here https://github.com/RealmTeam/django-rest-framework-social-oauth2 using POSTMAN to generate an access_token to login to Facebook using localhost:8000 and it generated perfectly and I got the the access_token and I can login perfectly but when I test the same way with a different url of my new domain name I can't get an access_token and I got an error said no module named 'social' so what should I do to do login with Facebook and generate access_token after pushed my project to heroku !!? There are all the steps I did after pushed my project to heroku : I Changed My Site Url Of My App On Facebook from localhost:8000 to https://whispering-hamlet-67095.herokuapp.com/ changed my ALLOWED_HOSTS In Settings.py To ALLOWED_HOSTS = ["localhost","whispering-hamlet- 67095.herokuapp.com"] This Step=> ### Testing On PostMan To Get facebook access_token As Usual Like I Used To Do When My Project is Only Running Locally But I Got This error When I Changed The Url From localhost:8000/ to https://whispering-hamlet-67095.herokuapp.com/ and my code of urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from egystoreapp import views, apis urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', … -
Need currency format from a number in template
I am not a Django programmer but trying to look at how I can change the output of number which is supposed to printed to the page as USD. For example: It prints "Price: 3295000" when I would like it to say "Price: $3,295,000". This is the template part: <h5 class="card-title h5-size">Price: {{property.price}}</h5> What code can I put in the template to output this in the way that I'm looking for? -
How to check the file type of python InMemoryUploadedFile file?
I am creating an app using python Django to merge documents and I would want to check the file type of the uploaded files because the code can only merge pdf file. I have tried to use endswith and split function to check the file type but there was error saying InMemoryUploadedFile has no such attributes. Hence, are there any other methods to check for file type of InMemoryUploadedFile file ? My code is shown below: I want to make sure that check that if the uploaded files are not pdf files, the code will ignore it (adding if statement & continue) def mergedocument(request): doc = request.FILES.getlist("file[]") mergedoc =[] for docu in doc: fs = FileSystemStorage() file_path = fs.save(docu.name, docu) pdoc = documentsfile(docs=file_path) pdoc.save() mergedoc.append(docu) merger = PdfFileMerger() for pdf in mergedoc: merger.append(pdf) merger.write("C:\\Users\\Downloads\\Merged.pdf") merger.close() messages.info(request,a) messages.info(request,'Files merged and stored in your Downloads folder') return redirect('home')