Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to override river-admin template?
Firstly , i would like to say that this package is amazing in the sense where there can be so much flexibility. Im relatively new to this package and im just trying to figure a way to fiddle around with the provided front end in the river-admin package. Could someone point me in the correct direction in doing so? -
Django, environment variables. Error: SMTPRecipientsRefused at /password_reset/
it's my first post here. I'm learning Django, and i'm trying to send an email to reset my password. There is one problem.. When I send an email with my username and password assigned to these constants, everything works well: EMAIL_HOST_USER = 'abc.def@gmail.com' EMAIL_HOST_PASSWORD = 'Abc123' But when i try to use environment variables instead: EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') i got an error SMTPRecipientsRefused at /password_reset/ {'abc.def@gmail.com': (501, b': sender address must contain a domain')} Am I doing something wrong? Maybe I should use environment variables in different ways? In advance, thanks for your help, guys! -
can we work with Django authentication without builtin Django forms
I want to use input field for authentication but if I search for authentication tutorial they are using built-in Django forms which I can't design it using html -
how to implement a movie review system using sentimental analysis in python using django
Take a movie as a input from a user and pass it as a argument to our python file and our program will do a sentimental analysis on movie comments and give output wheather a movie is worth watching or not . framework used is django , backend language python and movie reviews collected from rottentomatoes. -
How to specify basehref in Django
Is it possible to launch Django app depending on .env configuration with BASEPATH=/api or just BASEPATH=/? -
404 error when deploying django project with apache2
I tried to create a new django project on apache2, but I got 404 error. Here are what I did. -In /home/ubuntu/django directory, type django-admin startproject proj -Edit proj/proj/wsgi.py as follows. import os import sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') sys.path.append('/home/ubuntu/django/proj'); sys.path.append('/home/ubuntu/django/proj/proj'); application = get_wsgi_application() -Edit ALLOWED_HOSTS in proj/proj/settings.py as follows. ALLOWED_HOSTS = ['example.com'] -Edit /etc/apache2/conf-available/wsgi.conf as follows. WSGIScriptAlias /proj /home/ubuntu/django/proj/proj/wsgi.py WSGIPythonPath /home/ubuntu/django/proj <Directory /home/ubuntu> Require all granted </Directory> <Directory /home/ubuntu/proj/proj> <Files wsgi.py> Require all granted </Files> </Directory> -Restart apache2 as /etc/init.d/apache2 restart -Access to http://example.com/proj, and then got 404 error as follows. Page not found (404) Request Method: GET Request URL: http://example.com/proj/ Using the URLconf defined in proj.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. My enviroment is as follows. Ubuntu 18.04 LTS (AWS) Apache/2.4.29 Python 3.6.9 Django 3.0.5 How can I solve this 404 error? -
Django graphql JWT authentication gives anonymous user although valid token is given
I'm following this tutorial on authentication with django-graphql-jwt. I'm failing at step Testing the Authentication. I get a valid token via ObtainJSONWebToken but when I insert this token into the HTTP header authorization and perform a query (me) that checks the user status it gives an anonymous user. When I am logged in via django admin page it works without any token. It seems like the middleware is not working properly but that is just a guess. Here my code and what I do: settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] GRAPHENE = { 'SCHEMA': 'schema.py', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware' ] } schema.py class Query(teamorgaisation_queries.Query, users_queries.Query, graphene.ObjectType): # this class inherits multiple Queries as we add more apps with their own schema pass class Mutation(teamorganisation_mutations.Mutation, users_mutations.Mutation, graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() me-query import graphene from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from voss_be_django.users.graphql.types import UserType class Query(graphene.ObjectType): me = graphene.Field(UserType) def resolve_me(self, info): user = info.context.user if user.is_anonymous: raise Exception('Not logged in!') return user Postman query without authorization header: mutation tokenAuth($username: String!, $password: String!){ tokenAuth(username: $username, password: $password){ token } } variables: { "username": "testUser", "password": "UserTest#1234" } response (inside … -
Django static url with digitalocean spaces
I have an droplet on digitalocean which for the most part is working great, however i have enabled the cdn option in digitalocean spaces (similar to aws s3 storage) and in trying to load static files using the cdn url, i cannot seem to get the url working correctly so suspect i am missing the obvious? For example when i change the STATIC_URL in settings to the cdn no change is seen in the web page source? If i change the AWS_S3_ENDPOINT_URL and MEDIA_ENDPOINT_URL then the source does change but the files are not found and as one can guess a collectstatic no longer works, So i assume that the AWS_S3_ENDPOINT_URL & MEDIA_ENDPOINT_URL need to remain as is and i merely need to ensure the static_url is used? I did read somewhere that it was not good practice to change the templates from {%static.... to {%static_url so have not done that, is this something i should update or not? Settings: AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' MEDIA_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com/media/' AWS_STORAGE_BUCKET_NAME = 'mysitestaging' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # if False it will create unique file names for every uploaded file AWS_S3_FILE_OVERWRITE = False STATICFILES_STORAGE = 'mysite.settings.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'mysite.settings.storage_backends.MediaStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } … -
How to limits some users to view Django admin content by default permission
Am new to Django I have developed app in Django, when I assign view permission allowed to view content Question is this how can I override default view permission to allow user to his own created content on admin site Any help appreciated -
how does django get_next_by_FOO() query work?
i want to know how get_next_by_FOO()/get_previous_by_FOO() fetch data from database. anyone know the SQL code for that?. can anyone tell me how it works behind the scene? -
Django Authentication - Page redirecting to home even it goes in to exception
I am doing Simple User Registration part of my project, using Django's User table. Which supposed to redirect to home page after successful user registration and its login only, but even though I am filling up duplicate (incorrect)entry for username, its going to home page instead of showing the error on Sign up page. P.S - Tried to keep the question short, not displayed unnecessary code Please do read comments in the code and logs, added extra explanation there def register(request): if request.method == 'POST': reqdict = to_reqdict(request) print("user.is_authenticated", reqdict) # This statement printed in the logs username = reqdict.get('email') first_name = reqdict.get('first_name') last_name = reqdict.get('last_name') raw_password = reqdict.get('password') try: clear_old_sessions(request) user = User.objects.create_user(username=username,first_name=first_name, last_name=last_name,email=username, password=raw_password) user.save() user = authenticate(username=username, password=raw_password) login(request, user) print("user.is_authenticated>>>>>", user.is_authenticated) # This does not get printed in the logs return redirect(reverse('home')) # Only this line redirects page to home page except IntegrityError as e: messages.error(request, "User already exists!") print("error", e) except Exception as e: print("Other error", e) messages.error(request, "User already exists!") return render(request, template_name="signup.html") else: return render(request, template_name="signup.html") See the logs for detail: System check identified no issues (0 silenced). April 13, 2020 - 15:51:54 Django version 3.0.5, using settings 'backend.settings' Starting development server at … -
Change function to class view django
I'm doing a django app and at first I've done methods to my view, but I'd like now to change to class. Here's an exemple of how I tried : def register(response): if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) And tried to change like this : class RegisterView(generic.View): def post(self, request): form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: form = RegisterForm() return render(response, "register/register.html", {"form":form}) But I keep getting a 405 Error Method not allowed, I guess it's because I'm not doing right the changing from method to class. Any idea ? -
How to calculate the value of two html tags and output it to other tag
Is there any way to calculate the subtotal using (price * quantity), quantity is the number tag which needs to be entered by the user. Then all the subtotals should be added to the total. Can this all be done without submitting any form?(Price * quantity = Subtotal) -
Where is Django's own database?
This question asks where the Django installation is. This question is about the table django_migrations. I've looked under the path from the command django in the interactive console, where I find a subdirectory db, along with middleware, etc. But I've no idea where this table django_migrations (i.e. the data in it) is in fact kept. I want to know firstly because I want to know what happens if this data is lost. I'm just learning Django and I don't quite understand how much of a problem this would be. The path to the Django location is under a directory in my home folder where I keep my Python virtual environments, the name of which begins with a ".". I tend to exclude such directories from my backup plans... Having just deleted db.sqlite in my project I see that it gets regenerated when you do migrate, together with a list of (in my present case) some 15 migration operations. I'm quite mystified by some of these: the first 10 or so seem to have occurred before I started doing anything to my models.py file. Are they documented or explained somewhere? -
Managing timer based threads
I'll give some back story for context before the question. I'm currently creating a small Django based web site with some code on the back. This is basically a security scan website, so a Recon module is part of it. A user fills up a form and recon begins. Because many users can access the website at the same time, I handeled the call to recon method with threads, this way more than one user can actually use the website. Something like the following def recon_view(request): if request.method == 'POST': form = ReconForm(request.POST) if form.is_valid(): recon_thread = threading.Thread(name='Recon Process', target=recon.run_recon, args=(form,)) recon_thread.start() The next step is to implement some sort of monitoring mode, from what I have searched, one can use threads this way. threading.Timer(1, foo).start() The recon will run once a week or few days so time is not an issue. Would this be the correct approach? Woulnd't this mean that everytime the user starts a recon, the Thread will continue running basically until the server stops (Meaning possibly hundreds of threads at the same time). The other option I can think of is using a separate script that makes an API call to the website, triggering the recon -
Fetch modal data with Ajax from Django Model
Sorry for repeating this question, and Ajax integration since its very broad subject, but I just can't figure it out. I have a html table with 4k+ rows of data, and each of rows has some basic information like name, address, last name, phone, and a button which triggers a bootstrap modal which contains additional data like phone2, address 2, etc. My problem is, since my modal is located inside a for loop like this - <tbody> {% for opp in optika %} <tr> <td>{{ opp.example }}</td> <td>{{ opp.some_field }}</td> <td> <button id="testbtn" type="button" class="btn btn-success btn-sm btn-detail" data-toggle="modal" data-target="#detalji_modal{{ opp.pk }}" Detalji </button> </td> ... </tr> {% include "opportunity/partials/_detalji_modal.html" %} {% endfor %} </tbody> And this is modal detail - <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" id="detalji_modal{{ opp.pk }}" aria-labelledby="detalji_modalLabel"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="detalji_modalLabel">Detalji</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id=""> <div class="container-fluid"> <h5>{{ opp.... }}</h5> <p>{{ opp.....title }}</p> ... </div> </div> <div class="modal-footer"> <p style="margin-right: auto">Zahtev uneo/la : {{ opp.... }}</p> ... ... <button type="button" class="btn btn-outline-primary" data-dismiss="modal"> Close </button> </div> </div> </div> </div> I'll pass the view also : @login_required(login_url='registration/login') def OptikaList(request): user_groups = request.user.groups.all() … -
Django runserver on BASEHREF
I have such bash script #!/bin/bash BASEHREF="0.0.0.0:8000/python-api" exec ./manage.py runserver "$BASEHREF" --settings api.settings.local But after launch I got such error CommandError: "0.0.0.0:8000/python-api/" is not a valid port number or address:port pair. How can I runserver with relative path? -
Django: How to iterate over form fields choices without knowing the fields name?
I have a form whose fields are created in its __init__method: class Form(forms.Form): def __init__(self, modelInstance, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) # create fields based of modelInstance data (because it might change) self.fields[modelInstance.name] = models.ChoiceField(choices=SomeChoices, widget=forms.RadioSelect()) Therefore i can not know in advance how the field may be named. Now how can I iterate over the field choices without knowing its name? What I'd like: {% for field in form %} <p>sometext</p> {% for value, text in field.NAME.choices %} <input type="radio" name="{{ field.name }}" value="{{value}}" id="id_{{ field.name }}_{{forloop.counter0}}"> <label>{{text}}</label> </div> {% endfor %} {% endfor %} I know field.NAME only returns the actual field name and does not give me access to its choices. But how else can I do this? Any help is greatly appreciated! -
After inherited from AbstractUser, Django admin can not change user's permissions any more
I change django user model by inherited from AbstractUser, codes like the following. But I can not modify user permissions and change the group which user belong to any more in Django admin site. When I logon to admin as super user, go to the user page. The user'permissions can not be changed. Can anyone help? from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib import admin class UserProfile(AbstractUser): mobile = models.CharField(max_length=20, null=True, blank=True) avatar = models.CharField(max_length=100, null=True, blank=True) admin.site.register(UserProfile) #settings.py add this AUTH_USER_MODEL = 'users.UserProfile' -
Django. Hash password in models.py
I have a trigger in my database to create a password from another column and update it in the current database. Then I insert this password to another table. The problem is my project doesn't need a registration form as a new page. So only admin can add new users. The question sounds like: is there an opportunity to create a hash password in models? Or from another hand how to create password fill in models.py? models.py class Student(models.Model): studentIndex = models.IntegerField() studentName = models.CharField(max_length=50) studentSurname = models.CharField(max_length=50, default='') studentPhoneNumber = models.CharField(max_length=12, default='+48') studentPesel = models.CharField(max_length=11, default='') studentStudyMode = models.CharField(max_length=12, default='') studentFaculty = models.CharField(max_length=30, default='') studentSemester = models.IntegerField(default='') studentAddress = models.CharField(max_length=255, default='') studentMotherName = models.CharField(max_length=100, default='') studentBirth = models.DateField(help_text='year-month-day') studentEmail = models.EmailField(max_length=255, default='') studentImage = models.ImageField(default='default.jpg', upload_to='profile_pics') studentPassword = models.CharField(max_length=100, default='12345678', help_text='Do not modify this field. Password will be generated automatically') studentDateJoined = models.DateTimeField(default=datetime.datetime.now()) def __str__(self): return f'{self.studentIndex} - {self.studentName} {self.studentSurname}' Trigger in user_student table CREATE TRIGGER add_new_student_with_correct_password after insert on users_student begin update users_student set studentPassword = strftime('%Y', studentBirth) || substr(strftime('%m', studentBirth), 2, 1) || strftime('%d', studentBirth) || substr(studentMotherName, 1, 1) || lower(substr(studentName, 1, 1)) where studentPassword = '12345678'; insert into auth_user(password, last_login, is_superuser, username, first_name, email, is_staff, is_active, … -
I'm trying to apply celery to Class based view(apis) in django. How can I do this?
Is it a correct way to apply celery to class based views? I think APIs are sync tasks... And, if it is, how can I apply celery to class based Views? I can’t apply just tagging @app.task above functions inside class. I failed to apply making tasks.py with functions and calling them inside functions in class.(it throws not JSON serializable error..) Please can someone give me the keryword to search with? -
Migrating error "OperationalError at /admin/accounts/userstripe/ no such table: accounts_userstripe"
Hi I'm trying to develop a website for an online store and in my accounts' models.py, I have two models. While table for one model was created successfully, table for my UserStripe model wasn't created and it says: OperationalError at /admin/accounts/userstripe/ no such table: accounts_userstripe What should I do ? Can anyone please help me out? My models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings import stripe from localflavor.us.us_states import US_STATES stripe.api_key = settings.STRIPE_SECRET_KEY class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) class UserAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) address = models.CharField(max_length=120) address2 = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=120, choices=US_STATES) country = models.CharField(max_length=120) zipcode = models.CharField(max_length=25) phone = models.CharField(max_length=120) shipping = models.BooleanField(default=True) billing = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return str(self.user.username) My signals.py: import stripe from django.conf import settings from django.contrib.auth.signals import user_logged_in from .models import UserStripe stripe.api_key = settings.STRIPE_SECRET_KEY def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email), ) new_user_stripe = UserStripe.objects.create( user = user, stripe_id = customer.id, ) except: pass user_logged_in.connect(get_or_create_stripe) My apps.py: from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def … -
django.contrib.gis.geos.error.GEOSException: Could not parse version info string "3.7.1-CAPI-1.11.1 27a5e771"
Background of the problem: I'm working on a legacy project built on python 2 and Django 1.9. So a few days back I have set up this project and then my debian 10 OS got some problem I had to reinstall the OS but my project was saved and I am using the same env which was created before. I had this error before but I had no idea how it got fixed on its own now it's coming up again. So the research and based on the recent workout the only lead I got buy some StackOverflow fellow have is According to old docs for 1.10 (1.9 docs aren't available). Django 1.9 only supported GEOS 3.4 and 3 docs.djangoproject.com/en/1.10/ref/contrib/gis/install/geolibs. You'll have to install the older version of GEOS or upgrade Django Now the link provided has few lib to be installed, I have done that but still getting this error when I run python manage.py migrate I'm still getting this error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/rehman/projects/comparedjs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/rehman/projects/comparedjs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/home/rehman/projects/comparedjs/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/rehman/projects/comparedjs/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in … -
How to get started with DJ-stripe?
For what I can see Dj-stripe seems to be a very active project. However, the documentation is lacking so many details, tutorials, etc., that for me it has been easier to re-create the wheel than using the library. How do I get started? How do I, for example, save credit card details to a customer? How to use Connect? I am sorry I am so not specific. Nevertheless, there are so many open questions is impossible to list them all. -
Putting break points or line breaks in the comment section (Python - Django)
Update This is now how my site is rending - It doesn't appear as if the br is doing anything. <article class="media content-section"> <!-- comments --> <h2>{{ comments.count }} Comments</h2> {% for comment in comments %} <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <h3 class="article-title">{{ post.title }}</h3> <p class="article-content">{{ comment.body }}</p> <br><br><br> <p>test2 test2</p> <br><br><br> <p>test2 test2</p> <br><br><br> {% endfor %} </article> Original Post This is how my site is rendering - I tried putting <br> and </br> in a few places and I have not seen any impact. Does anyone have any ideas? <article class="media content-section"> <!-- comments --> <h3>{{ comments.count }} Comments</h3> <br><br/> {% for comment in comments %} <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <br><br/> <h2 class="article-title">{{ post.title }}</h2> <p class="article-content">{{ comment.body }}</p> <br><br/> {% endfor %} </article>