Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
How to block user after 3 login attempts using Django rest-framework
I'm using djngo-rest-framework for my projects and django-oauth-toolkit to authentication users through the api I wanted to when a users intend to login and get access token if user enter wrong username or password for three time their accounts get deactivated. -
How do I include a Background picture in a css file for django usage?
I'm trying to include a background picture into one of my css files which is then loaded into a html file using djangos compressor module. The project looks as follows: djangoproject |-myproject (with setup.py etc) |-statics |-images |-css |-templates |-index.html In the index.html i used {% load static %} {% load compress %} {% compress css %} <link rel="stylesheet" href="/static/css/style.css"> {% endcompress %} and in this style.css, I would like to include a background picture from statics/images/bg.jpg. I tried to do this as follows: background: url('../images/bg.jpg') 50% 0 repeat-y fixed; but the picture wont appear. So does anyone know how to refere the url here? Because outside of django, this way works well. Thanks for any advie and sorry for my bad english skills (just ask if you are not able to understand something because of bad word choice etc.)! Thanks! -
Which one makes more sense, writing models in django or creating a table then auto-generating the models?
We have designed our ER diagram for our database design but I don't know if it makes more sense to write models in Django from scratch or create tables in Postgres then use inspectdb. What are the disadvantages of the latter and which one is most commonly used in projects? -
Store ALL Django errors in a Model?
I was wondering if there is a way to store every and all errors in a Django Model? Let's say I have a function that connects to an API and that API returns 404. Similarly, I have a model that people add their attendances to, if there's something wrong in a Model, it doesn't let the User proceed with what they're doing but I want it to log that error as well, not locally, but in a Model. Consider a model of a similar structure: class ErrorLog(models.Model): error = models.CharField(max_length=255) message = models.TextField() #Then date and time etc. I understand that for my function I'd need to use a try and except block but what would I do for the models to automatically log the error inside a model? -
consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused
This is my project structure myproj │ ├── app1 ├── __init__.py ├── tasks.py |---gettingstarted ├── __init__.py ├── urls.py ├── settings.py │ ├── manage.py |-- Procfile In gettingstarted/settings: BROKER_URL = 'redis://' In Procfile: web: gunicorn gettingstarted.wsgi --log-file - worker: celery worker --app=app1.tasks.app In app1/tasks.py from __future__ import absolute_import, unicode_literals import random import celery import os app = celery.Celery('hello') @app.task def add(x, y): return x + y When I run "celery worker" it gives me: consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. -
handle forms in python django
today i have a challenge for my customer's site ... in this site we have a form that contains some radio and checkbox to get information from clients i want when client complete the form and clicked on Submit button , information send to admin of the site and when admin confirmed the POST the form information send to the other page that designed by front-end developer as post ... like this ... client side : <form action="#"> <input type="text" placeholder="Enter Your Name :"><br><br> Genger :<br><br> <input type="radio" name="GDR">Male<br> <input type="radio" name="GDR">Female<br><br> Select Your Skils :<br><br> <input type="checkbox">HTML5<br> <input type="checkbox">CSS3<br> <input type="checkbox">JavaScript<br> <input type="checkbox">ES6<br> <input type="checkbox">Django<br> <input type="checkbox">NodeJS<br><br> <input type="submit"> </form> now is the time that admin confirm the post : for example completed form is : my name is : Hassan Raji I'm : Male And my skills are : HTML5 , CSS3 and JavaScript i want to show this information in other page as post like this : .STL{ background-image : linear-gradient(#000 , #555 , #000); padding:25px; border-radius:15px; border: 5px solid red; color:white; } h4{ color:red; } <div class="STL"> <p>Name : Hassan Raji</p> <h4>Gender</h4> <p>Male</p> <h4>Skills:</h4> <p>HTML5</p> <p>CSS3</p> <p>JavaScript</p> </div> the back end is by Django Please Help … -
django AdminDateWidget: Uncaught ReferenceError: quickElement is not defined
I am trying to use AdminDateWidget in my application, I get below javascript error, tried different options available on the internet still couldn't solve. FYI, my admin url is "/newadmin" I have properly include the form.media, where am I making mistakes? Console error; DateTimeShortcuts.js:259 Uncaught ReferenceError: quickElement is not defined at Object.addCalendar (DateTimeShortcuts.js:259) at init (DateTimeShortcuts.js:46) My template looks like; {% block style %} <script type="text/javascript" src="/newadmin/jsi18n/"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="/static/myn/starter.css" rel="stylesheet"> <script type="text/javascript" src="/static/myn/starter.js"></script> {{ form.media }} {% endblock %} Form; from django.contrib.admin.widgets import AdminDateWidget #class YourForm(forms.ModelForm): # from_date = forms.DateField(widget=AdminDateWidget()) class EventForm(ModelForm): class Meta: model = Event fields = ['title', 'ondate', 'photo', 'desc'] widgets = { 'title': TextInput(attrs={'size': 70}), 'ondate': AdminDateWidget(), } -
Stripe cancellation of subscription is not working with Django
I'm trying to create a cancellation page to remove a subscription of monthly payment. However, I still cannot retrieve the customer information with Stripe API. The customer and subscription is already succeeded to create when I saw the Dashboard of Stripe. Here is my views.py: def charge(request): if request.method == 'POST': form = CustomUserForm(request.POST) try: user = form.save() plan = 'plan_xxxxxx' customer = stripe.Customer.create( card=customer.stripe_id, email=user.email, plan=plan) charge = stripe.Subscription.create( customer=customer.id, plan=plan, ) user.stripe_id = customer.id user.save() return render(request, 'charge.html') Here is cancel the subscription in views.py: def cancel_subscription(request): try: customer = stripe.Customer.retrieve(request.user.stripe_id) customer.cancel_subscription(at_period_end=True) return redirect('home') except Exception as e: print(e) return render(request, 'accounts/cancel.html') Here is cancel the subscription in model.py: class CustomUser(models.Model): username = models.CharField(max_length=255) email = models.EmailField() stripe_id = models.CharField(max_length=255) plan = models.CharField(max_length=50, default='xxxxxxx') Here is cancel the subscription in form.py: class CustomUserForm(ModelForm): class Meta: model = CustomUser fields = ("username", "email", "stripe_id") def show_error(self, message): # pylint: disable=E1101 self._errors[NON_FIELD_ERRORS] = self.error_class([message]) This is the error that I get: 'User' object has no attribute 'stripe_id' I think that it could not save stripe_id to form and not retrieve from form. How should I edit it ? -
Render different date format depending on time that passed - either |timesince or |date
Good morning. What I would like to achive is that when user posted sooner than 24h from now, I would like to have for example: Posted: 4h ago, but when it's more than 24h, it would be nice to have: Posted: November 10. First approach is doable by using: {{ post.date_posted|date:"F d, Y" }}, second one: {{ post.date_posted|timesince }}, but is there a way to "mix" them? Is is possible in Django? -
django how to make custom url
hey guys i have been learning Django for about 3 week now and i am just curious is there anyway to set custom url for main page(the first page shown when starting the server) because i try to do it like the code below but still it give me error if anyone know please help if not hmm...maybe that how Django operate i think haha. Thanks // Django api from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('account/',include("useraccount.urls")), ] //useraccount from django.urls import path from . import views urlpatterns = [ path('login',views.login,name="login"), ]