Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Previous Months in python-Django
I want to generate a code in python to get the previous 10 months from the month we are in and the next month (to get some stats for it and labels in Line chartJs) e.g(we are currently in December 2019 , I want it to show from Feb 2019 - Jan2020) I have tried the old way but it is fixed range: months =[] for j in range(12): curr_month = calendar.month_name[j] my = [curr_month,y] months.append(my) # print(months) lnqs_rfq =[] lnqs_local =[] allrq = [] for i in range(12): lnqs_rfq.append(Request.objects.filter(req_date__month=(i),req_type='stock').count()) lnqs_local.append(Request.objects.filter(req_date__month(i),req_type='Local').count()) allrq.append(Request.objects.filter(req_date__month=(i)).count()) I tried also panda but I don't get the previous months : td = datetime.today() mon = pd.date_range(start=td ,periods = 12, freq='MS').strftime("%b,%Y").tolist() print(mon) I hope you help me if there is a better way. Thanks -
uwsgi falied , vultr server, django+ngin+uwsgi
please help, i dont know the reason why uwsgi failed uwsgi.service - uWSGI Emperor service Loaded: loaded (/etc/systemd/system/uwsgi.service; disabled; vendor preset: disabled) Active: failed (Result: start-limit) since Wed 2019-11-20 09:41:15 EST; 2 weeks 2 days ago Process: 31588 ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites (code=exited, status=203/EXEC) Process: 31585 ExecStartPre=/usr/bin/bash -c mkdir -p /run/uwsgi; chown user025:nginx /run/uwsgi (code=exited, status=0/SUCCESS) Main PID: 31588 (code=exited, status=203/EXEC) Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable. uwsgi.service file content: [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/usr/bin/bash -c 'mkdir -p /run/uwsgi; chown user025:nginx /run/uwsgi' ExecStart=/usr/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target firstsite.ini content: [uwsgi] project = firstsite username = user025 base = /home/%(username)/myproject chdir = %(base)/%(project) home = %(base)/myprojectenv module = %(project).wsgi:application master = true processes = 5 uid = %(username) socket = /run/uwsgi/%(project).sock chown-socket = %(username):nginx chmod-socket = 660 vacuum = true -
loading admin page after upgrading to django 3.0 crashes dev. server
I upgraded Django from 2.2 to 3.0, Now I can't access admin page. Every time I access http://127.0.0.1:8000/admin the dev. server quits without any message or error. I wen to upgrade by following this link: https://docs.djangoproject.com/en/3.0/howto/upgrade-version/ Is this a common issue or do I have any error. -
Django/ReportLab: pdf print do not works on alwaysdata
I just have deployed an update of my project on alwaysdata.net All works except pdf print I do not have any error and looking browser debug network request status is 200 but I can not find my pdf anywhere in local, pdf is save in download folder -
Activated Virtualenv in commands but the bracket is not showing in the directory [Python]
I am trying to learn django. In VS code, I have installed pip and virtualenv. I created a env folder by using virtualenv command. $ virtualenv env To activate virtual environment, I ran the command below. $ source env/bin/activate The result I was expecting to see was I see the little brackets in front of directory address in bold below. However, I do not see any brackets to indicate that the virtual environment is being activated. dhkang@dhkang-Lenovo-IdeaPad-S145-15API ~/fastcampus/django % source env/bin/activate **dhkang@dhkang-Lenovo-IdeaPad-S145-15API ~/fastcampus/django % (env) ** However, I do not see (env) here. I don't know if the virtual environment is activated or not. Does anyone know how to resolve to show the brackets when virtual environment is activated? -
Django how to make a form
I try to make an user registration form, how do make a form to this code: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): STUDENT = 1 TEACHER = 2 SUPERVISOR = 3 ROLE_CHOICES = ( (STUDENT, 'Student'), (TEACHER, 'Teacher'), (SUPERVISOR, 'Supervisor'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() Create this form I don't know how to made this -
Problems understanding Django app dependencies
I'm relatively new to Django working on my first project. Im getting kinda confused when it comes to app dependencies in Django. Comming from Odoo (Python based ERP-System) Apps/Modules all have their own manifest.py which handles dependencies amongst other things. So you can say App1 depends on App2 and cannot be installed without its dependency being installed. How would I handle something like that in Django? Say I have an app called "account" for user accounts and I wanna make a new app "account_profile" where I put everything related to user profiles. Classes in "account_profile" may inherit from "account". What are best practises to achieve something similiar in Django? Or is it even needed here? -
How to get MIMEText to render HTML?
I'm not quite sure what I'm doing wrong with MIMEText. The emails are still sending as plain text. The email body that the user receives looks like this: Content-Type: text/html; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit <html>Thanks for signing up. Go to <a href=localhost:8000/confirm>confirm</a> to complete your registration.</html> (In this example it links to localhost, but in production it will be to my site) Here is the relevant code from my views.py file: from email.mime.text import MIMEText import mailer def signup(request): current_site = get_current_site(request) email_address = request.user.email mail_subject = 'Welcome!' msg = u'<html>Thanks for signing up. Go to <a href=localhost:8000/confirm>confirm</a> to complete your registration.</html>' print(msg) html_msg = MIMEText(msg, 'html') send('myemail@gmail.com', 'myemailpassword', email_address, mail_subject, html_msg) And here is the email sender module, mailer.py: import smtplib def send(user, pwd, recipient, subject, body): FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print('successfully sent the mail') except Exception as e: print("\n\nfailed to send mail, here's why:\n") print(e) Thank you for any help at all here. -
request.method and request.GET in Django
I am following a tutorial and I am unable to understand some lines in it from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from . models import Page from .forms import ContactForm def index(request, pagename): pagename = '/' + pagename pg = get_object_or_404(Page, permalink=pagename) context = { 'title': pg.title, 'content': pg.bodytext, 'last_updated': pg.update_date, 'page_list': Page.objects.all(), } # assert False return render(request, 'pages/page.htm', context) def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data #assert False return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request,'pages/contact.htm',{'form': form, 'page_list': Page.objects.all(), 'sbmitted': submitted}) The above is pages/view.py file {% extends "pages/page.htm" %} {% block title %} Contact us {% endblock title %} {% block content %} <h1>Contact us</h1> {% if submitted %} <p class="success"> Your message was submitted successfully. Thankm you. </p> {% else %} <form action="" method="post" novalidate> <table> {{ form.as_table }} <tr> <td>&NonBreakingSpace;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} The above is pages/contact.htm file so, what is meaning of "if request.method == 'POST':" and why is there "if submitted in request.GET: submitted=True"? I have googled a lot but … -
Django iis deployment postgres
I have deployed a django app on an iis server. I'm using postgres as the database. However while connecting with the application remotely, I'm getting they following error - Operational error.. An error has occurred: could not connect to server: No buffer space available (0x00002747/10055) is the server running on "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server : no buffer space avalaible (0x00002747/10055) is the server running on "localhost" (::1) and accepting TCP/IP connections on port 5432? What could be the possible scenario: 1. Should i ask the server team to unblock port 5432 for remote access? 2. Is any other configurations required at server end? -
i need to know how i user OPT pin instead of password [closed]
i would like know how can a user use OTP pin instead of a user inserting password. The code for generating OTP in using email address. -
NoReverseMatch at /tinku/update
Reverse for 'update_student' with no arguments not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/update$'] it is showing error above please tell if anyone know about this how to resolve this urls.py path('',views.index,name="home"), path('<slug:name>/update',views.student_update,name="update_student"), path('delete/<slug:name>',views.student_delete,name="delete_student") student_update.html <div class=" row d-flex justify-content-center"> <div class="col-md-6 box-shadow"> <form action="{% url 'update_student' %}" method="POST" class="form"> {% csrf_token %} {{updateform|crispy}} <button class="btn btn-primary form-control">update</button> </form> </div> views.py:- def student_update(request,name): instance=get_object_or_404(Student,name=name) print(instance) form=StudentForm(request.POST,instance=instance) print(form) if form.is_valid(): form.save() return redirect('home') return render(request,'webapp/student_update.html',{'updateform':form}) models.py from django.db import models from django.core.validators import MaxValueValidator,MinValueValidator from django.contrib.auth.models import User class Student(models.Model): gender=( ('M','male'), ('F','female') ) name=models.CharField(max_length=50) age=models.PositiveIntegerField(validators=[MinValueValidator(18),MaxValueValidator(50)]) sex=models.CharField(max_length=1,choices=gender) def __str__(self): return self.name forms.py from django import forms from django.core.validators import MaxValueValidator,MinValueValidator from webapp.models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields=['name','age','sex'] -
migration images to another table and save them
I was using images in one table of Product like that class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.DO_NOTHING, null=True, blank=True) name = models.CharField(max_length=200) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image1 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) But I am going to move this images to another table which includes only images class ProductImage(models.Model): image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image1 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) image4 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, null=True) one problem is that I added many images in Product table now If I do this without deleting products. Can I add those images to product? But how can I do? any help please -
ImproperlyConfigured Django error when runing an external script
hi all I've coded a script that generates some Django files with the following structure _Django-project | |_main-app | | | |_ urls.py | views.py | . | . | |_Django-project | | | |_settings.py | urls.py | . | . | |_manage.py myscript.py the problem is when I try to run myscript.py Django raises this error ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings myscript.py import ast from main-app.models import * with open('main-app/models.py', 'r') as myfile: source = myfile.read() p = ast.parse(source) classes = [node.name for node in ast.walk(p) if isinstance(node, ast.ClassDef) and node.name != "Meta"] #fields are Classname+fields returns a list for i in range(len(classes)): exec("a="+classes[i]+"()") exec(classes[i]+"fields = [key for key in a.__dict__ if key != '_state']") the code works well when I run it in the shell but when I try to run the file it fails! i think that the problem is because of from main-app.models import * -
Django - QuerySet is not iterable in permissions.py
New to Django and Django Rest here. I have the following structure : class MyUsers(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' class roles(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=80) class user_roles(models.Model): id_user = models.ForeignKey(MyUsers,on_delete=models.CASCADE) id_role = models.ForeignKey(roles,on_delete=models.CASCADE) I'm trying to create a custom permission, to allow users with a specific role to access some endpoints. class IsAuthenticatedAndLeader(BasePermission): def has_permission(self, request, view): id_role=models.roles_users.objects.filter(id_user=request.user.id).values_list('id_role',flat=True) if "Leader" in models.roles.objects.filter(id=id_role).values_list('label',flat=True): return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return True When I try to access to the endpoint, I have the following error: TypeError: argument of type 'QuerySet' is not iterable However if I try in views.py something simple like the following it works : if "Leader" in models.roles.objects.filter(id=3).values_list('label',flat=True): print("Yes") So I'm not sure why I'm getting this error when trying to apply it to permissions.py -
django-rest-auth unable to access user details page
I am using django-rest-auth to authenticate and register my user I can do everyhting. Login is working Registration is working but I am unable to access get User details: /rest-auth/user/ (GET, PUT, PATCH) I am trying to access this endpoint I am using JWT I am getting correct token. But when I am using this command in curl: curl -X GET http://localhost:8000/rest-auth/user/ -H 'Authorization: Bearer <jwt-toke>' I am getting this error: {"detail":"Authentication credentials were not provided."} What do I need to do to access details of user -
Django-Alwaysdata->TypeError: 'client_encoding' is an invalid keyword argument for this function
I try to deploy ma django project on Alwaysdata but get an error I am not very confortable with deployment I follow steps mentionned in alwaysdata doc what I have done via Shell in box on alwaysdata: - clone my project - setup settings.py (with parameters that use to works) - activate my env - install requirements.txt My database seems to be OK (with data inside) I contact alwaysdata supports that say me it is a python problem TypeError: 'client_encoding' is an invalid keyword argument for this function -
Getting weird error with django: ORA-01843: not a valid month
I am using django 2.0.13 and I am connecting to an Oracle database with cx_oracle. The only thing I am trying to achieve is to pull data from a view and display it with datatable. I use django-datatables-view. But for a reason that I am unable to figure out about I am stuck with this issue. Below is my sql request for creating the view. create view V_SOLDE_FFTO_FTTH as select distinct a.custid,client_name,code_cpt,c.categorie,round(b.solde) solde,suspendue,montant_gnf last_invoice from v_ftto_ftth a, v_solde_client_good b, v_facture_mois c where a.custid = b.custid and b.custid = c.custid order by 5 desc Here is the result of this request: And here is also the Django model I am using: class SoldeFttoFtth(models.Model): class Meta: db_table = 'V_SOLDE_FTTO_FTTH' managed = False CUSTID = models.IntegerField(db_column='CUSTID') CLIENT_NAME = models.CharField(max_length=200, db_column='CLIENT_NAME') CODE_CPT = models.CharField(max_length=200, db_column='CODE_CPT') CATEGORIE = models.CharField(max_length=100, db_column='CATEGORIE') SOLDE = models.IntegerField(db_column='SOLDE') SUSPENDUE = models.CharField(max_length=1, db_column='SUSPENDUE') LAST_INVOICE = models.IntegerField(db_column='LAST_INVOICE') But when I try to access the view data with Django's ORM it get the following error: django.db.utils.DatabaseError: ORA-01843: not a valid month ORA-06512: at "LOG.DATECONVERTER_PLSQL", line 8 I have used two ways but none is working: SoldeFttoFtth.objects.values('CUSTID', 'CLIENT_NAME', 'CODE_CPT', 'CATEGORIE', 'SOLDE', 'SUSPENDUE','LAST_INVOICE') and rows = [] with connection.cursor() as cursor: cursor.execute("select *from V_SOLDE_FTTO_FTTH") for … -
What is the different in Django 3 ASGI and Django 2 + Channels?
django-channels is on my 1st list of material I am going to learn during this new year. But Django 3 also has ASGI feature without any document on it. Then I doubt that what is the different between django-channels use cases VS Django 3 ASGI? -
Stopping users from submitting same form n times
I have a Django coded backend server, with Apache to serve When I submit a form (click on form submit in html) for n times, it submits the data n times into db and server i.e. When I gave "abc" as input in text field and click on submit buttom for 10 times, I could see that the db has 10 record with "abc" as data. I tried installing mod_evasive to prevent DDOS attack (thought this is a version of the attack), still I couldn't stop users from submitting only for one time. Please help me on how to achieve this Thanks in Advance -
Django - Is it possible to find the mobile device name of users?
As the title suggests, is there any way to obtain the mobile device name (like Samsung Galaxy S10) of the client user? The best I have across is - Django-user_agents but it doesn't fetch that information -
Problems to display django chart with chartit in right order
When I use Chartit PivotDataPool the month number is not in the right order. Chartit PivotDataPool graph is in this order 1, 10, 11, 2, 3, 4, 5, 7, 8, 9. I want to have right order like 1, 2, 3, 4 , 5, 6, 7, 8, 9, 10, 11. ![Graph image][1] ![1]:(https://imgur.com/UPBZY8G) ds = \ PivotDataPool( series= [{'options': { 'source': DerangementAdsl.objects.filter(annee=year), 'order_by': ['mois'], 'categories' : ['mois'], 'legend_by': ['sous_traitant'], }, 'terms': { 'total': Count('id') } } ]) pivcht = PivotChart( datasource=ds, series_options=[{ 'options': { 'type': 'column', 'stacking': True, 'order_by': 'mois', }, 'terms': ['total'] }], chart_options={ 'title': { 'text': 'Répartition dérangements relevés / structure' }, 'xAxis': { 'title': { 'text': 'Semaine' } } } ) -
How to add button on django model in django admin panel
I want to add two buttons in model objects in Django. I haven't tried anything. the buttons are "Approve" and "Deny". enter image description here -
How make a simple rest-framework example?
I'm trying to make a hello world in Django and rest-framework, but when acess the url: http://localhost:4444/products to get all products the terminal is giving me this error: Traceback (most recent call last): File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/mixins.py", line 45, in list serializer = self.get_serializer(queryset, many=True) File "/home/developer/.virtualenvs/store/lib/python3.5/site-packages/rest_framework/generics.py", line 110, in get_serializer return serializer_class(*args, **kwargs) TypeError: object() takes no parameters [06/Dec/2019 11:49:35] "GET /products HTTP/1.1" 500 17530 I use Django, but i dont know how start a project from 0. Here is my code: view.py: from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from rest_framework.response import Response from .models import Product from .serializers import ProductListSerializer class ProductViewSet(viewsets.ModelViewSet): lookup_field = 'pk' model = Product queryset = … -
Passing a value from html template to views.py in Django using AJAX
can someone please assist me with this issue? I am new to Django and I've been trying to create a web-based application which gets the user location and displays the shops around them from the tutorial I followed online. However, the initial values were hard-coded in the views.py in order to change the user's location. I've asked a question before in order to find the best solution to this, and the kind people advised to use AJAX. I've been trying to come up with a solution for few hours now and its driving me insane. I have never used AJAX before so I apologize for this. This is what I have so far, no issues or errors when running the application, however, the values are not changing for user's location Please see attached code views.py user_location = Point(0, 0, srid=4326) def process_loc(request): lat = float(request.GET.get('lat')) lon = float(request.GET.get('lon')) global user_location user_location = Point(lat, lon, srid=4326) return render(request, 'shops/index.html', {'lat': lat, 'lon': lon}) class Home(generic.ListView): model = Shop context_object_name = 'shops' queryset = Shop.objects.annotate(distance=Distance('location', user_location) ).order_by('distance')[0:15] template_name = 'shops/index.html' As it can be seen I'm declaring the user_location is located outside the function and then changing it inside the function, so …