Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python 3 on Django 2 throws a UnicodeEncodeError
On my Django 2 / Python 3 project I get a UnicodeDecodeError when uploading an image to the server. Interestingly I don't get this error on my development PC. I only get this on the staging server. views.py if request.method == "POST": image = request.FILES.get("avatar") user.avatar = image user.save() # <-- Error is thrown here my locale setup on the server LANG=en_GB.UTF-8 LANGUAGE= LC_CTYPE="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_COLLATE="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_PAPER="en_GB.UTF-8" LC_NAME="en_GB.UTF-8" LC_ADDRESS="en_GB.UTF-8" LC_TELEPHONE="en_GB.UTF-8" LC_MEASUREMENT="en_GB.UTF-8" LC_IDENTIFICATION="en_GB.UTF-8" LC_ALL= on manage.py shell I get this: Python 3.5.2 (default, Oct 8 2019, 13:06:37) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import sys >>> sys.stdout.encoding 'UTF-8' >>> And this is the error: UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 75: ordinal not in range(128) I also have included # coding=utf-8 on all my python files. My code seems to be OK, because the same image (filename is: Vs_Filemón.png) uploads fine on my development machine. So, I guess there must something broken on my staging machine which is this: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 16.04.6 LTS Release: 16.04 Codename: xenial -
How to associate foreign keys model in HTML
I am writing portal to manage tasks , i have created following models shown below and in addition following view shown below , in the HTML(shown below ) i have section i display recent tasks last 30 days, when i am looping on each main task that can have multiple sub tasks i would like for example to show sub task associated users and details , i know how to get data from main model class data, but i don't know how to retrieve data associated form foreign Key sub model to its main model. for example how do i display all users for sub task associated to main task task_assign = models.ForeignKey(User, on_delete=models.CASCADE, related_name="task_assign",default=1) or any other related like all sub tasks descriptions associated to main task for example task_description = models.CharField(max_length=200) Please advice Thanks view class class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) #filter active runing tasks context['active_tasks'] = MainTask.objects.filter(complete=False).count() #All oobjects main Task context['maintask'] = MainTask.objects.all() #All objects Subtask context['childtask'] = MainTask.item_main.all() #filter task due date #due_range = context['due_task'] = MainTask.objects.filter(due_date__day__lte=7, complete=False).count() #task paused context['task_paused'] = MainTask.objects.filter(task_status='PA', complete=False).count() #task paused context['task_completed'] = MainTask.objects.filter(task_status='CO', complete=True).count() #task paused context['task_started'] = MainTask.objects.filter(task_status='NS', complete=True).count() ###query for … -
Best Practises for Storing Email Templates in Django
I was wondering what's best practise for storing email templates in terms of project structure. I don't like the idea of having them in the same directory as your normal templates. I can imagine it can be quite hard to differentiate which is which with growing project size. Wouldn't it be better to have a separate folder "mail_templates" within your app? In case that was a good idea how do I change TEMPLATES in settings.py so that Django would be able to find "mail_templates"? -
Django UpdateView with multiple models and forms
Is it possible to have, for example, two forms with different models in one class (UpdateView)? Around stackoverflow and rest of the web, I couldn't find any information about that. Here is what I try to accomplish: class SettingsView(LoginRequiredMixin, UpdateView): # Here I'm trying to combine multiple models and display each form in settings.html model = (User, Currency) fields = [ # ... ] success_url = reverse('main:settings') template_name = 'settings.html' -
Basic Django, How do I configure this empty path
So, I was trying to run a Django website I found on github Link but the home page for the site isn't working. It gives the following error Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: blog/ admin/ login/ [name='login'] logout/ register/ [name='register'] login/ [name='login'] logout/ [name='logout'] password_change/ [name='password_change'] password_change/done/ [name='password_change_done'] password_reset/ [name='password_reset'] password_reset/done/ [name='password_reset_done'] reset/<uidb64>/<token>/ [name='password_reset_confirm'] reset/done/ [name='password_reset_complete'] The empty path didn't match any of these. Can anybody take a look at the repository and help me out with what's wrong. Thanks -
Synchronize authentications between two django projects
I have two separate Django projects with separate databases. I would like that when a user logs in site A, he is automatically logged into site B. I thought of doing the following: When user log into site A, server A requests server B to create a new session for the user, Server A then sends back session information to the user client, When the client logs into site B, the session data is sent so that server B considers the user as logged in. Would that work? How should I send the session data from the browser to server B (with a cookie?)? -
how to match a year range (string) argument eg. 2001-2002 in django urls by using regex
I am getting a string value from Django form which I want to map to a URL. I tried with regex but it gives an error. I tried below URL pattern to match: year/2006-2007 re_path(r'year/(?P<clg_year>.+?+)/', view.get_details, name="year") Please note that the value 2006-2007 is a string that I am getting in some of the forms. The error I am getting is: Reverse for 'year' with arguments '('2', '0', '0', '6', '-', '2', '0', '0', '7')' not found. 1 pattern(s) tried: ['year/(?P[\w-]+)/'] -
Using django project on a notebook pc
I developed a django project and selling it to my customers. Generally we install it on a server. But some customers tell us that they will use the project iternally, not on internet. So they want us to install it on their daily used pc. So they will use it like a desktop application with the web browser just on the local pc. So they wont make any investment on server. Everyday they will shutdown their pc while taking to home. So is it feasable, applicable and safe to use a django project on a laptop pc. -
Can't receive data value with a PUT Ajax request in a django view
I'm doing a PUT Ajax request sending a value in data parameter, but i don't receive any data in my django view. This is my code: function wordUpdate(){ $.ajax({ url:'/socialanalyzer/dictionary_update/', headers: { "X-CSRFToken": $.cookie("csrftoken") }, type: 'PUT', data: { word_id: temporalWordToEdit },success: function(data) { if (data.code==200) { alertify.success('Word modified successfully'); var delayInMilliseconds = 2000; setTimeout(function() { location.reload(true); }, delayInMilliseconds); }else{ console.log('Error, status:',data.code); alertify.error('Error updating the word'); } } }) } views.py def put(self, request, *args, **kwargs): try: if request.method == 'PUT' and request.is_ajax(): import pdb;pdb.set_trace() Am I passing this in properly? This should be works, but I receive empty data: (Pdb) request.GET <QueryDict: {}> I also tried sending data with JSON.stringify function, but i get the same result: var word_id = { 'word_id': temporalWordToEdit }; $.ajax({ url:'/socialanalyzer/dictionary_update/', headers: { "X-CSRFToken": $.cookie("csrftoken") }, type: 'PUT', data: JSON.stringify(word_id) I received the value, but instead of sending it as data, i sent it directly in the url like this: url:'/socialanalyzer/dictionary_update/?word_id='+temporalWordToEdit, (Pdb) request.GET <QueryDict: {'word_id': ['1']}> I don't know if this is the right way or I'm doing something wrong. I understand that in a PUT request, you try to update an instance, but it's correct to send the id instance in the url … -
How to return only the relevant related objects in Django REST Framework
I am trying to create an API such that when I give it a keyword it will return all the cinemas that have movies containing said keyword. Right now I am using: queryset = Cinema.objects.filter(movies__icontains = keyword) My serializer is: class CinemaSerializer(serializers.ModelSerializer): class Meta: model = Business fields = ('id', 'name', 'city', 'movies') depth = 1 If the keyword is "ghost" this returns the cinemas with all their movies. { "id": 1, "name": "My Cinema", "city": "London", "movies": [ { "id": 1, "title": Ghosts }, { "id": 2, "title": Ghostbusters }, { "id": 3, "title": Star Wars } ] Is there a way to return the cinemas and only the relevant movies (Ghosts and Ghostbusters)? -
Cannot run program "/../../python.exe" (in directory "/PythonSoftwareFoundation.Python.3.8_3.8.240.0_x64__qbz5n2kfra8p0"):Access is denied
I'm getting this error anytime when creating a new project in pycharm: Cannot run program "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.240.0_x64__qbz5n2kfra8p0\python.exe" (in directory "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.240.0_x64__qbz5n2kfra8p0"): CreateProcess error=5, Access is denied I have Python 3.8 installed from Windows Store but when I try to create the project it says "Choose another SDK" It seems like a fairly common issue but since I'm new to Python I'm not really sure what it involves. -
Django: When do I need Q lookups?
I have one question to that example in the official Django documentation. Is the Q lookup necessary here, and why? I tried it without and it works fine for me (at least from what I can see). >>> highly_rated = Count('book', filter=Q(book__rating__gte=7)) >>> Author.objects.annotate(num_books=Count('book'), highly_rated_books=highly_rated) -
How to display model data in Django template after reloading a page once?
Scenario: Currently, my Template has a text which says "Last seen" and a timer that mentions the time generated after clicking a button. If a new user visits the site, there will be no time displayed. If a user clicks on the button, the time will be generated and created in the model. And every time a user refreshes the page, the old/current time should be displayed near the text. Right now, every time I reload the page, there is no time displayed despite being saved in my model. How can I show the current time in my Template after reloading each time? This is what I have tried out so far: models.py: from django.contrib.auth.models import User class Path(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) current_time = models.DateTimeField(blank=True, null=True) #can be Null or blank if users enters the site for the first time. views.py: from django.utils import timezone import pytz from django.http import JsonResponse, HttpResponse def Func(): ''' If the current_time does not exist, then we create it in the Path model. #If time already exists, then we grab the id and replace current time with a new one using the update() method. ''' time = timezone.now() #Format: 2019-11-16 14:53:35.774824+00:00 … -
can not use fire-base_document_refference.get() function when run the django project with apache2 https and call the function using API
can not use firebase_document_refference.get() function when run the django project with apache https and call the function using API def get_test_api_https(request): subject_list_ref = db.collection(u'subject_list').document(u'301') doc = subject_list_ref.get() context = {'result': str(doc)} return_data = json.dumps(context) return HttpResponse(return_data, content_type='application/json') ` when i use django runserver the DocumentRefference.get() work fine and it return a doc from which i get the document field value when i call the function usinf API (http://my_ip/get_test_api_https/) But not return anything or time out when use (https://my_ip/get_test_api_https/). If i return the subject_list_ref it return successfully. i.e. the function successfully read the document refference from firebase. To access firebase data i am using service_account previlleage. The Sever configuration i am using OS:Ubuntu 18.04 apache: apache2 CA provider : certbot Python: 3.6 login as user configure the virtual environment and build the project under the environment -
Django: object has no attribute 'annotate'
My goal is to get two numbers "total" and "num_very_disappointed". Currently, I always get the following error message: AttributeError: 'Question' object has no attribute 'annotate' Do you have any idea what I'm doing wrong? very_disappointed = Count('answers', filter=Q(answers__choices__answer="Somewhat disappointed")) answers = Question.objects.get( focus=QuestionFocus.FEELING_ABOUT_ATTENDING_AGAIN, survey__event=12, survey__template=settings.SURVEY_POST_EVENT, ).annotate(total=Count('answers'), num_very_disappointed=very_disappointed) models.py class Response(TimeStampedModel): class Language(Choices): CHOICES = settings.LANGUAGES survey = models.ForeignKey( "surveys.Survey", on_delete=models.CASCADE, related_name="responses" ) order = models.ForeignKey( "orders.Order", on_delete=models.SET_NULL, null=True, blank=True, related_name="response", ) attendee = models.ForeignKey( "attendees.Attendee", on_delete=models.SET_NULL, null=True, blank=True, related_name="response", ) total_time = models.PositiveIntegerField( null=True, blank=True, verbose_name=_("Total time") ) ip_address = models.GenericIPAddressField(null=True, verbose_name=_("IP Address")) language = models.CharField( max_length=Language.get_max_length(), choices=Language.CHOICES, verbose_name=_("Language"), ) class Answer(TimeStampedModel): question = models.ForeignKey( "surveys.Question", on_delete=models.CASCADE, related_name="answers" ) response = models.ForeignKey( "Response", on_delete=models.CASCADE, related_name="answers" ) answer = models.TextField(verbose_name=_("Answer")) choices = models.ManyToManyField( "surveys.AnswerOption", related_name="answers", blank=True ) class Question(TimeStampedModel): survey = models.ForeignKey( "surveys.Survey", on_delete=models.CASCADE, related_name="questions" ) question_set = models.ForeignKey( "QuestionSet", on_delete=models.CASCADE, related_name="questions" ) title = models.CharField(max_length=100, verbose_name=_("Title")) help_text = models.TextField(null=True, blank=True, verbose_name=_("Help text")) type = models.CharField( max_length=QuestionType.get_max_length(), choices=QuestionType.CHOICES, verbose_name=_("Question type"), ) focus = models.CharField( max_length=QuestionFocus.get_max_length(), choices=QuestionFocus.CHOICES, verbose_name=_("Question focus"), ) required = models.BooleanField(default=False, verbose_name=_("Is required?")) position = models.PositiveSmallIntegerField( null=True, blank=True, verbose_name=_("Position") ) # Translatable fields i18n = TranslationField(fields=("title", "help_text")) class Meta: ordering = ("position", "pk") class AnswerOption(TimeStampedModel): question = models.ForeignKey( "Question", on_delete=models.CASCADE, … -
How to render the markdown content in the front-end using django-mdeditor?
I am using django-mdeditor (https://github.com/pylixm/django-mdeditor) in a project of mine. I have integrated the editor in the admin panel. How can I render the saved markdown content in the front-end? django-mdeditor must be using some function to generate the live-preview in its editor. The solution to me question would be finding that particular function. I can then use the same function to render the content in the front-end. Can someone help me with that? -
How can I get session data into django model?
I am trying to set default value to a column which is getting stored in django session. Below code gives an error get_state_id() missing 1 required positional argument: 'request' I know the reason for this error. But when I don't give request parameter in defined function get_id then I don't able to get the id value. please help me on this. def get_id(request): id = request.session.get('id') return id class Forms(models.Model): form_id = models.AutoField(primary_key=True) id= models.IntegerField(default=get_state_id) -
how to get a username to show on serializer django rest framework
how would i get the user name to show in the serializer along wit the data. I tried doing serializer char field but did not work. Model class Pet(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=50) serializer class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = '__all__' view set: class PetViewSet(viewsets.ModelViewSet): queryset = Pet.objects.all() permission_classes = [ permissions.AllowAny # permissions.IsAuthenticated, ] serializer_class = PetSerializer what i tried: class PetSerializer(serializers.ModelSerializer): username = serializers.CharField( source = "users.username", read_only = True ) class Meta: model = Pet fields = '__all__' expected result: { "id": 1, "title": "dog", "owner": 1, "username": "someusername" }, -
Cannot authenticate web application with Django
I am trying to access a Django API from within a web app hosted in another domain, but I have to do it in the context of a logged in user. I don't have access to the API server but it is suposably correctly configured for this scenario. In order to set the csrftoken cookie I execute a GET on the API login page -- this seems to be working, I can see the cookie in Chrome DevTools. Now, when I'm fetching for a /uid=123, the preflight request returns 200, but on the actual request I keep getting the 403 Forbidden: Authentication credentials were not provided. A short investigation with Fiddler pointed out that on fetching data the csrftoken cookie isn't included in the request even with credentials="include", although other cookies on the same domain do get included. I was able to manually add the X-CSRFToken header, as suggested by the Django documentation, but that didn't solve my problem. // axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; // axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true; axios.defaults.auth = { username: 'my-username', password: 'my-password', }; axios .post('https://login.url/', { username: 'my-username', password: 'my-password', }) .then(response => { const html = document.createElement('html'); html.innerHTML = response.data; const token = html.querySelectorAll('input[name="csrfmiddlewaretoken"]')[0].value; … -
react + django project runs OK on localhost but have issue on remote server
I have a project by react + django-rest-framework, on local host everything is OK but when I run project on remote server sometimes page stuck on loading function and component didn't mount and in the console i don't see any error log, I am using nginx and uwsgi for run project. this is a sample code that include loading function import React, {Component} from 'react'; import {Button, Card, CardBody, CardHeader, Col, Collapse, Modal, ModalBody, ModalHeader, Row} from 'reactstrap'; import axios from 'axios' import Moment from "react-moment"; import {Link} from 'react-router-dom'; import {toast} from "react-toastify"; import Loading from "../../../Component/Loading"; class Success extends Component { constructor(props) { super(props); this.toggleView = this.toggleView.bind(this); this.toggleCollapse = this.toggleCollapse.bind(this); this.fetchCampaignDetails = this.fetchCampaignDetails.bind(this); this.saveAndContinue = this.saveAndContinue.bind(this); this.send = this.send.bind(this); this.state = { isLoading: true, campaign: { received_list: [], html_content: '<h1>hi</h1>' }, received_list: [], error: null, showViewModal: false, showCollapse: false }; } notifyAlert = (e) => toast.error(e, { position: "top-right", autoClose: 5000, hideProgressBar: true, closeOnClick: true, pauseOnHover: true, draggable: true, }); saveAndContinue(mode) { this.setState({isLoading:true}) const config = { headers: {'Authorization': `Token ${localStorage.getItem('token')}`} }; const body = {step: 4}; axios.patch(`api/campaigns/${this.props.match.params.id}/`, body, config) .then((response) => { if (mode === 'next') this.props.history.push(`/campaigns/`); else if (mode === 'back') this.props.history.push(`/campaign/wizard/confirmation/${this.props.match.params.id}`); this.setState({isLoading:false}) }).catch(error => { … -
Results not being displayed when using 'lte' in IntegerField in Django
I have created a model named Product containing these fields ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type') I want to display those products in the webpage that have less than 2 units remaining this is what I have tried: Here is my views.py file: from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import * from .forms import * def get_stock(request): items=Product.objects.filter(units__lte=2) context={ 'items':items } return render(request, 'UpdateStock.html', context) here is my urls file: from django.conf.urls import url from django.urls import path from .views import * urlpatterns=[ url(r'^get_stock$', get_stock, name='get_stock'), ] here is my HTML file for the same {% extends 'base.html' %} {% block body %} <br> <h3>Update Stocks</h3> <br> <table class="table table-hover"> <thead> <tr> <th>Sr. No.</th> <th>Product Name</th> <th>Company</th> <th>Quantity</th> <th>Price</th> <th>Units</th> <th>Product Type</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td>{{item.pk}}</td> <td>{{item.prod_name}}</td> <td>{{item.company}}</td> <td>{{item.quantity}}</td> <td>{{item.price}}</td> <td>{{item.units}}</td> <td>{{item.prod_type}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} But the results are not getting displayed -
sum values of many (upto n or unknown) dictionary
I have a dictionary like following : dict_items([(True, 1), (None, 16)]) dict_items([(True, 3), (None, 15)]) and there number increases as number of user increases i.e it might go upto n. So I wanted to find the total number of true and none in total. For the above data I want to find total_true = 4, total_none = 31 counts = dict(Counter(care_needs_name.values()).items()) print(counts.items()) total_review_completed = 0 total_review_to_add = 0 for k, v in counts.items(): if k == True: total_review_completed = total_review_completed + v else: total_review_to_add = total_review_to_add + v print(total_review_completed) But for this I am getting : dict_items([(True, 1), (None, 16)]) 1 dict_items([(True, 3), (None, 15)]) 3 -
Django CustomUser Function
I created a CustomUser as follows, however, I am not able to use the CustomUser functions in Views as I get the error message "get_first_name() missing 1 required positional argument: 'self'" when I call CustomUser.get_first_name(). I checked my settings.py and do import CustomUser, models as well as settings in the view file. If you could help me here that would be awesome. models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email', unique=True) first_name = models.CharField(verbose_name='first_name', max_length = 15) last_name = models.CharField(verbose_name='last_name', max_length = 15) organization = models.CharField(verbose_name="organization", max_length = 15, choices=ORGANIZATIONS) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # check this for login email purposes date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'organization'] objects = CustomUserManager() def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def __str__(self): return self.email def get_organization(self): return self.organization def get_first_name(self): return self.first_name def get_email(self): return self.email -
I get django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username for no apparent reason
I have a very weird situation when I create the superuser at first I get no problem, then when I run python manage.py shell and type >>> from django.contrib.auth.models import User >>> User.objects.all() I get the following <QuerySet [<User: >]> a superuser with no username , and when I try to create a second superuser(even with a different username) because this one obviously can't be used , I get the error in the title what happened to my app ? or what was new ? .. I deleted my database file and migration files and made a makemigrations and migrate commands to know more about why I did that check this problem so how can I fix this ? -
How to Create Friends Object having 2 foreign keys?
I want a friends database which will have following fields: class Friends: status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="friend_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs, ): friend = self.create(from_user=request.user.id, status="Pending") return friend class Meta: unique_together = (('from_user', 'to_user'),) def __str__(self): return self.to_user I am unable to create object of the same in the view as given below: def add_friend(request, pk): """Sending friend request to email""" name = request.user.first_name from_user = request.user.email current_site = get_current_site(request) to_user = get_object_or_404(User, pk=pk) email_subject = 'Friend Request from ' + name to_email = to_user.email email = EmailMessage(email_subject, message, from_user, to=[to_email]) email.send() context = {'name':name,'first_name':to_user.first_name,'last_name':to_user.last_name } f = Friend(from_user=request.user.id,to_user=to_user.id,status= "Pending") f.save() return render(request, 'users/sent_friend_request_success.html', context)