Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django password reset confirm
I'm new in Django and really confused. I'm developing a authentication API by using built in rest auth. I want to reset password by API view but the mail link I send redirect me to "password reset confirm" HTML template but I need to redirect this link to API view. I expect to redirect to this page: but my email link redirect to this HTML template page: enter image description here this email is send by password_reset_email.html someone asked for password reset for email {{ email }}. Follow the link below: {{protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} this is the url for redirecting this email link: path('password/reset/confirm/(?P[0-9A-Za-z]+)/(?P.+)/$', auth_views.PasswordResetConfirmView, name='password_reset_confirm'), -
Custom command on elastic beanstalk prompts invalid syntax in manage.py file
I've been trying to figure out how to best call a script with cronjobs and am unable to figure it out. Either I go with a custom command where I use the following in .ebextension/"some config file": container_commands: 01_some_cron_job: command: "cat .ebextensions/some_cron_job.txt > /etc/cron.d/mycron && chmod 644 /etc/cron.d/mycron" leader_only: true some_cron_job.txt: * * * * * root source /opt/python/run/venv/bin/activate && source /opt/python/current/env && /usr/bin/python /opt/python/current/app/manage.py cron_command >> /var/log/myjob.log 2>&1 This works when i run the command locally but after having uploaded it to eb I get the following error: File "/opt/python/current/app/manage.py", line 18 ) from exc ^ SyntaxError: invalid syntax Or I could call the script directly: * * * * * root source /opt/python/run/venv/bin/activate && source /opt/python/current/env && /usr/bin/python /opt/python/current/app/api/cron.py >> /var/log/myjob.log 2>&1 But am then getting import errors when trying to import a function from a another file in the same directory: ImportError: attempted relative import with no known parent package I'm quite lost and would appreciate any help. -
Render a form function in multiple django templates
I have written a function where the function captures the details from a form and sends an email after form submission. How can I have this functionality rendered to multiple django templates where i can call the form and do so. Below is the related function.. def emailView(request): if request.method == 'GET': form = myform() else: form = myform(request.POST) if form.is_valid(): subject='form Details' mobile = form.cleaned_data['mobile'] email = form.cleaned_data['email'] dummy = '\nMobile: '+mobile+'\nEmail: '+email' try: send_mail(subject, dummy, 'dummy@gmail.com', ['dummy1@gmail.com', 'dummy2@gmail.com']) messages.success( request, " Thank you !! For contacting.') except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('email') return render(request, "my_app/email.html", {'form': form}) -
Particular models databases entries count in Django
How to count the total(all entries )number of row in a databases table in Django -
Django ORM query optimization
I am trying to optimize a database query for the following models: Conversation model: class Conversation(_BaseModel): is_test = models.BooleanField(default=False) meta = JSONField(default=dict) timestamp = models.DateTimeField() bot_version = models.CharField(max_length=128, blank=True) listen_mode = models.BooleanField(default=False) Message model: class Message(_BaseModel): conversation = models.ForeignKey( 'Conversation', on_delete=models.CASCADE, related_name='messages' ) timestamp = models.DateTimeField() message = models.TextField(null=True, blank=True, db_index=True) response = models.TextField(null=True, blank=True) data = JSONField(blank=True, null=True) meta = JSONField(default=dict, blank=True) The query is: conversations = Conversation.objects.filter( ~Q(messages__message='[{"text": "", "type": "text"}]') | ~Q(messages__message='[{"type": "text", "text": ""}]') ) But I am getting a lag as its so slow since the Message table in the DB has over 5 million rows. So I read up and tried to use DB indexes where I added an index to the message field in the Message table. message = models.TextField(null=True, blank=True, db_index=True) and I was hit with an error django.db.utils.OperationalError: index row size 3096 exceeds maximum 2712 for index "bot_api_message_message_00003" HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing This is when I stumbled upon a solution that needed me to create a migration file and manually do sql commands to create an index … -
Battling bugs stemmed from changed model objects as a result of db queries
This is the countless time in my exprience when I spent several hours trying to debug an abnormal behavour of my code which stemmed from the following situation: x = MyModel.objects.get(...) # Here I expect that x.name = 'a' #... MyModel.objects.update(...) # This results in x.name being changed to 'b' # Some long code..... # and the...oh my Gode... # Do something expecting that x.name equals to 'a', but the fact is that it's already b Is there any way to make Python warn me about such cases? For example, it could be some sort of decorator that would print to console that I am trying to access a changed model value within one view...Or maybe a PEP8 tool...I would like to emphasize that I am not interested in RESOLVING this issue. I am looking for a tool to WARN me about this. Decorator does not seem a good choice, because I would have not to forget to include it in each and every function. Maybe I could do that in a middleware ? That is, I am looking for a code that after each initialization of a new variable, would check whether its value is a model field value. … -
Can someone explain a part a small piece of Django code?
I was following this tutorial and trying to implement a profile updating tool. One piece of code they provided was as follows: @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, _('Your profile was successfully updated!')) return redirect('settings:profile') else: messages.error(request, _('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'profiles/profile.html', { 'user_form': user_form, 'profile_form': profile_form }) I managed to work out what all of meant apart from the line return redirect('settings:profile') After changing the variables, I get the error : NoReverseMatch at /profile/ 'settings' is not a registered namespace Do I need to create something else? Any help would be appreciated. -
unresolved attribute reference 'objects' for class
I am pretty new to coding and trying to make a website in django. I have broken something while trying to filter the class UserBets by the currently logged in user. Can anyone see what i have done wrong? #From Views class UserBetListView(ListView): model = UserBets template_name = 'betassistant/userbets.html' context_object_name = 'my_bets' paginate_by = 8 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return UserBets.objects.filter(User=user) #from Urls path('userbets/<str:username>', UserBetListView.as_view(), name='bet-userbet'), #from Models sport = models.CharField(max_length=50, choices=sport_choices, default='NRL') bet_type = models.CharField(max_length=50, choices=bet_choices, default='H2H') Tipper_Choices = models.CharField(max_length=50, choices=tipper_choices, default='Trypod') bet_ammount = models.FloatField(max_length=10, default=2) bet_odds = models.FloatField(max_length=10, default=2) result = models.CharField(max_length=50, choices=result_choices, default='Winner') User = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.sport def get_absolute_url(self): return reverse('bet-detail', kwargs={'pk': self.pk}) -
The current path, Envs/python-projects/learnpy/static/styles/bootstrap4/bootstrap.min.css, didn't match any of these
Using the URLconf defined in learnpy.urls, Django tried these URL patterns, in this order: [name='index'] admin/ The current path, Envs/python-projects/learnpy/static/styles/bootstrap4/bootstrap.min.css, didn't match any of these. Above error occuring in create django static page Please help me See belowe image: enter image description here Myapp url: travello/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name='index')] Main app urls: learnpy/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('travello.urls')), path('admin/', admin.site.urls), ] Myapp view file: travello/views.py from django.shortcuts import render def index(request): return render(request, 'index.html') In index.html {% load static %} set above code in my index.html file -
SQLDecodeError at /admin/auth/user/ while filter as group in django admin
Environment: Request Method: GET Request URL: http://localhost:8000/admin/auth/user/?groups__id__exact=1 Django Version: 2.2.5 Python Version: 3.7.5 Installed Applications: ['cisco_stc_portal', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'performance.apps.PerformanceConfig', 'lacp.apps.LacpConfig', 'syslogs.apps.SyslogsConfig', 'login_required'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'login_required.middleware.LoginRequiredMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] -
Django The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example
When I try To log in with my user ID on the server this message will raise. But The same database in my local PC is ok its login successfully. SuspiciousOperation at /loginCheck The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. also here is that error page pic I do a few google searches but not working out. I'm using Django 2.1 and my database is MySQL -
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
Here I am trying to add relation with User model but I am getting error.I am not being able to make migrations. ImportError: cannot import name 'User' from 'user_registration.models' When I use get_user_model() instead of User it throws below error "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user_registration.User' that has not been installed models from user_registration.models import User class SomeModel(models.Model): field = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) class User(AbstractBaseUser): username = None first_name = None last_name = None email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() -
How display the name of the student with their specific ID using Django
I had create table inside my views.py students = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('id','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial', 'Grading_Categories', 'Average','Grading_Categories__PercentageWeight') Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values('CategoryName','PercentageWeight'))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student[ 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] id = student['id'] student_name = student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + \ student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name print(table_row[0]) table_row[Categories.index(student['Grading_Categories']) + 1] = student['Average'] * student['Grading_Categories__PercentageWeight'] / 100 table.append(table_row) this is the result How to display the ID of specific student? this is my html {% for row in table|slice:"1:" %} <tr class="tr2update"> <td><input type="text" value="{{ id }}" name="studentname">{{ row.0 }}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for c in row|slice:"1:" %} <td><input type="text" id="oldgrade" class="oldgrade" name="gradeupdate" value="{{c|floatformat:'2'}}" readonly></td> {% endfor %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" readonly/></td> </tr> {% endfor %} ive already tried in my html this <td><input type="text" value="{{ id }}" name="studentname">{{ row.0 }}</td> but it doesn't work, please help me guys, this problem is almost a week now , till now i didnt solve it. -
ModuleNotFoundError: No module named 'dota' - importing from settings.py files that are exported via .env
Traceback (most recent call last): File "send_email.py", line 5, in from dota.settings import SECRET_KEY, DOMAIN, SENDGRID_API_KEY ModuleNotFoundError: No module named 'dota' Ok i created .env file in the root of my folder. I exported everthing and made a setup in settings.py file in dota directory that is main directory where settings.py file is. settings.py SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = os.getenv('EMAIL_PORT') EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS') DOMAIN = os.getenv("DOMAIN") After that I tried to import this including secret key that i stored in as env variable. Here is the code. send_mail.py import jwt from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Email from django.template.loader import render_to_string from dota.settings import SECRET_KEY, DOMAIN, SENDGRID_API_KEY def send_confirmation_email(email, username): token = jwt.encode({'user': username}, SECRET_KEY, algorithm='HS256').decode('utf-8') context = { 'small_text_detail': 'Thank you for ' 'creating an account. ' 'Please verify your email ' 'address to set up your account.', 'email': email, 'domain': DOMAIN, 'token': token, } # locates our email.html in the templates folder msg_html = render_to_string('email.html', context) message = Mail( # the email that sends the confirmation email from_email=Email('example@gmail.com'), to_email=Email('veljko33614@its.edu.rs'), # list of email receivers subject='Account activation', # subject of your email content=msg_html ) try: sg = SendGridAPIClient(apikey=SENDGRID_API_KEY) … -
unable to save data using django formsets
The data entered in the form is not saving in the database and it is not showing any errors. Iam trying to create an exam with atleast one question, using ExamModelForm and QuestionFormset. After entering exam details and questions in create_exam_with_questions.html, the create button is not saving the data into the database views.py from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponseRedirect, HttpResponse from .forms import ExamModelForm, ExamFormset, QuestionFormset from .models import Question def create_exam_with_questions(request): template_name = 'school/create_exam_with_questions.html' if request.method == 'GET': examform = ExamModelForm(request.GET or None) formset = QuestionFormset(queryset=Question.objects.none()) elif request.method == 'POST': examform = ExamModelForm(request.POST) formset = QuestionFormset(request.POST) if examform.is_valid() and formset.is_valid(): # first save this exam, as its reference will be used in `Question` exam = examform.save() for form in formset: # so that `question` instance can be attached. question = form.save(commit=False) question.exam = exam question.save() return redirect("map:map-home") return render(request, template_name, { 'examform': examform, 'formset': formset, }) forms.py from django import forms from django.forms import (formset_factory, modelformset_factory) from .models import Exam, Question class ExamModelForm(forms.ModelForm): class Meta: model = Exam fields = ['name', 'section', 'duration', 'subject', 'start', 'teacher'] QuestionFormset = modelformset_factory( Question, fields=('question', 'ans', 'op2', 'op3', 'op4', ), extra=1, widgets={'question': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter … -
Django unittest WSGI.py
I am creating unittests for Django and using coverage and the wsgi.py file sticks out like a sore thumb with 0% coverage. When creating unittests, should I create one for the wsgi.py file ? What would be the best way to do this using the standard Django test facility ? wsgi.py code: import os from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ebdjango.settings") application = StaticFilesHandler(get_wsgi_application()) Thanks Mark -
nginx server_name while setting up Django project
server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I've entered my IP address in server_name and it's perfectly working. And I forwarded my domain to the respected IP address but when I open my domain address it's showing 'Welcome to Nginx', not my web application. Do I've to provide domain in nginx sites available?? -
'utf-8' codec can't decode byte 0xe6 in position 3: invalid continuation byte
I'm writing the Django React application and I have a huge existing database. I created models using 'inspectdb' command... My database is a bit old and it is full of Croatian characters because of it models couldn't be created. Is there any line of code that could solve a complete issue with this chararacter set on Django side? -
Passing array from Django view to HTML/JS
I'm sending an array from a django view to an html (in which there is a JS script) but the array seems to be a string. In fact if I try to console.log(array[0]) or console.log(array[1]) it returns in the first case [ and in the second case ' The code is: Django view def results(request): h = request.POST['h'] name = request.POST['name'] array = [h, name] return render(request, 'app/index.html', {'h':h, 'array':array}) index.html <script> var h = "{{ h }}" //this is 3 var array = "{{ array|safe }}" //this is ['3', 'John'] console.log(h) console.log(array[0]) console.log(array[1]) The console is: 3 [ ' I wish it was: 3 3 John Do you have any idea how can I access the n value of the array? Thanks -
Django: Check if value exists in object.filter list
In my Django project I need to check whether a user submitted value exists in a list of values that is returned from the database via objects.filter(). User submitted data: value = request.data['value_id'] Get valid status as ids: allowed_values = Values.objects.filter(Q(code='Active') | Q(code='Inactive')).values('id') This returns a queryset as follows. <QuerySet [{'id': 1}, {'id': 2}]> Checking if user submitted value exists in the allowed_values: if value in allowed_values: return True But this does not work and I need allowed_values to return as a list of 'id's. How can I do this without iterating through allowed_values and creating a new list? -
Use range filter for django rest framework
I want to filter the objects with id. like this below. fetch more than 12 , between 6 and 12, something like this.. I set RangeFilter() like this but it shows only equal. not more than, less than class MyTextFilter(filters.FilterSet): my_text = filters.CharFilter(lookup_expr='contains') id = filters.RangeFilter() class Meta: model = MyText fields = ('id','myText') -
Unable to run Django with docker-compose up command
I am not able to run my Django and MySql application with docker-compose up command. I don't know how exactly to configure the host parameter of database from Django project settings. Earlier while configuring the same for other application it worked well. I don't understand what exactly went wrong this time. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eitan_database', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'mysql_db', 'PORT': 3306, } } docker-compose.yaml version: "3" services: eitan-application: restart: always build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py migrate && python manage.py makemigrations && python manage.py runserver 0.0.0.0:8000" depends_on: - mysql_db mysql_db: image: mysql:5.7 volumes: - "./mysql:/var/lib/mysql" ports: - "8080:3306" restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=eitan_database - MYSQL_USER=root - MYSQL_PASSWORD=root Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev gcc -y COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app Stack Trace Traceback (most recent call last): eitan-application_1 | File "manage.py", line 21, in <module> eitan-application_1 | main() eitan-application_1 | File "manage.py", line 17, in main eitan-application_1 | execute_from_command_line(sys.argv) eitan-application_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line eitan-application_1 | utility.execute() eitan-application_1 | … -
django api not working from <form> but working in postman
I am trying to download the returned json from the django api. I tested on postman the django api is correctly showing the json, but when i try in my html it's showing Error code 501. Message: Can only POST to myapp Error code explanation: 501 = Server does not support this operation. views.py @csrf_exempt def export_json(request): projectname = "resume" folderpath = "/home/user/mywebapp/data" if request.method == "POST": fullpath=os.path.join(folderpath,projectname) json_result=ann_json(fullpath) with open("json_file.json","w",encoding="utf-8") as jsonfile: json.dump(json_result,jsonfile) file1 = open("../json_file.json", "r",encoding="utf-8") response = HttpResponse(file1.read(),content_type="application/force-download") response['Content-Disposition'] = 'attachement; filename=%s' % smart_str("json_file.json") response['X-Sendfile'] = smart_str("myapp/project/json_file.json") return response index.html <form action="http://127.0.0.1:8000/export_json" method="POST"> <label class="optinLabel">Project Name</label> <input type="text" placeholder="confirm your project name"/> <label class="optionLabel">Downlaod</label> <input type="submit" value="Json" style="color:red" /> </form> <script> fetch('http://127.0.0.1:8000/export_json') .then((response) => return response.json()) .then((data) => { localStorage.setItem("jsonfile",data) }); </script> -
post files to django server from flask server via requests library, containing image files
i am using my flask server to post on django server , all i can see is empty inmemoryuploadedfile in django. i dont want to save file on flask server all i want is to directly read the file and send to django via requests library. flask code:---- def upload(): if request.method == 'POST': data = {} count = 1 for i in request.files.getlist('files'): data[count] = (i.stream.read()) count += 1 r = requests.post("http://127.0.0.1:9000/upload/files/",files=data) #it will post to upload_json function in djnago my django code:-- @csrf_exempt def upload_json(request): if request.method == 'POST': print(request.FILES) print(request.headers) print(request.POST) my django console prints : ----- [[03/Mar/2020 14:53:03] "POST /upload/files/ HTTP/1.1" 500 58063 <MultiValueDict: {'1': [<InMemoryUploadedFile: 1 ()>], '2': [<InMemoryUploadedFile: 2 ()>]}> {'Content-Length': '367434', 'Content-Type': 'multipart/form-data; boundary=9c79604fbd576719cfa0fd53ef6b5ad6', 'Host': '127.0.0.1:9000', 'User-Agen t': 'python-requests/2.23.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} <QueryDict: {}> -
Pandas regex to return any string that contains U or UN with a digit
I'm trying to create a new column with values from another columns string What I want is to create a new column with unit values. The position of the units can vary. The examples of my strings are this is a string and we have 4U to use this is another string 5UN only 6U to use today I need to extract the numbers that are joined to both U and UN since the positions vary. df['test_units'] = df['ITEM_DESC'].str.get(r'\(*U.*?\)',) df['test_units'] This is my regex but I return only nan values. How do I just return the number that's joined to a U Or UN?