Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Oscar automatically empties the basket on redeeming an expired voucher
When a customer applies a voucher to an item in the cart and the voucher expires during the checkout process or inside the cart itself. During the checkout process, when clicked on place order, the cart automatically empties and the customer is sent this error, You need to add some items to your basket to checkout, this happens during the check_basket_is_not_empty method. Can someone help me understand which part of Django-Oscar could be modifying the cart in such drastic way. My initial thought was, that the cart was getting emptied because some oscar component was trying to remove the voucher and was removing the cart item as well. But during some more checks I find out that the voucher is successfully removed but the cart item only gets removed inside the PaymentDetailsView, probably. I don't have the code to PaymentDetailsView. I started the job as a Django developer a couple of days ago and I was thrown into this huge django-oscar code base, which I am completely unfamiliar with. I am not allowed to post any code online. I don't know what to do, and don't want to get fired. Any help would be highly appreciated. -
Save Datetime model field type as varchar in yyyymmddhhiiss
I'm using legacy db schema in Django admin. My datetime fields are varchar(14) saving this format: YYYYmmddHHiiss. I want that these type of "datetime" fields have similar behaviour to common datetime fields in django templates. (I mean, date/time widgets can understand the data). I have created this custom DateTime class: class TheappDatetime(models.DateTimeField): def from_db_value(self, value, expression, connection, context): return self.to_python(value) def to_python(self, value): if value is None: elif isinstance(value,str): value = u.get_objdatetime(value) else: value = u.get_strdatetime(value) return value # métodos al guardar def get_prep_value(self, value): if value is not None: value = u.get_strdatetime(value) #<-- bug here return value def value_to_string(self, obj): value = self.value_from_object(obj) return value def get_db_prep_value_(self, value, connection, prepared=False): if value==None: return None return u.get_objdatetime(value) def get_db_prep_save(self, value, connection, prepared=False): if value is not None: value = u.get_objdatetime(value) return self.get_db_prep_value(value, connection, prepared) widgets It is not working good. Because even though it looks good, when I recover the data the widgets understand it while trying to save it I got this error: return value.utcoffset() is not None AttributeError: 'str' object has no attribute 'utcoffset' This error is raised by this line: value = u.get_strdatetime(value) #<-- bug here Because I'm trying to store a string value in a "datetime" … -
How to get unique children in a many to many relation?
I need to make a list of the genres which have books. class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') class Book(models.Model): genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') -
Django : How to send notification to admin on a specific user activity?
I'm building a website that needs sending a notification to the admin when a request for help happens, It doesn't need to be literally a notification, it may b email in the admin panel or so, Thanks ^^ -
how can possible replacing variable value in triple quotation in python/ django with {value}?
i'm noob in django/python ,I saw a code in github about "exporting Vcard" files , my question is about a part that programmer replace variable value in string variable : admin.py: output = "" for person in queryset.all(): person_output = """BEGIN:VCARD VERSION:3.0 N:{last_name};{first_name} FN:{first_name} {last_name} TEL;TYPE=HOME,VOICE:{phone} TEL;TYPE=WORK,VOICE:{secondary_phone} EMAIL:{email} REV:{rev} END:VCARD""" # how can replace value when the source is string?! person_output = person_output.format( first_name = person.first_name, last_name = person.last_name, phone = person.phone, secondary_phone = person.secondary_phone, email = person.email, rev = d.strftime('%Y%M%d%H%f'), ) can anyone plz explain how it possible and let me know any python/django documentation about it?thank you. -
Why am I not seeing any increased performance when making async calls to database from django?
Django itself is synchronous, but I recently started a new Django project and decided to set it up from the ground up being asynchronous, that meant that I followed most of the django-channels design, with channels own async http-consumers and protocol router, and instead of using daphne I ran gunicorn with uvloop workers. One thing that became apparent was that using the ORM for queries to my database was not async. There was no information online about how to solve this, so I thought why not use a external async postgres client package (aiopg), and pass the ORM generated SQL query to aiopg, and then just convert the results back into the django model instances. It worked, but using apache bench before and after using async aiopg, I saw absolutly no increase in requests per second. The following code shows how I did it. import aiopg dsn = 'dbname=db user=root password=password123 host=postgres-container port=5432' pool = aiopg.create_pool(dsn) async def async_query(q): async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute(q) ret = [] async for row in cur: ret.append(row) return ret async def list(self, body): query = Model.objects.all().order_by("title") ares = await async_query(str(query.query)) results = [Model(**{ "id": i[0], "title": i[1], … -
Gitlab CI/DI - automatically deploy on VPS
I'm trying to configure GitLab CI/DI, stages: - test - deploy test: stage: test script: # this configures Django application to use attached postgres database that is run on `postgres` host - export DATABASE_URL=postgres://postgres:@postgres:5432/python-test-app - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test staging: stage: deploy script: - # Here I need to deploy the latest version on my VPS (run these three commands below) only: - develop stage test is working fine but how to run: git pull origin master python manage.py migrate sudo systemctl restart gunicorn on my DigitalOcean VPS automatically? -
Filtering the View Based on User Custom Permission
I have 2 Models, one for a list of Courses and the other with the list of Enrollments for each User. The Enrollment Table is currently structured to have only 1 record per student. There is a ManytoManyField in the Enrollment Table that allows me to add multiple courses for each Student. I want to ensure that when the Student Logs in they only see Courses they have enrolled for. I can't figure out as to what query in the view is most appropriate to achieve this. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Course(models.Model): title = models.CharField(max_length=255) description = models.TextField() created_dt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Enrollment(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) course = models.ManyToManyField(Course) def __str__(self): return f"{self.student}'s Enrollments" views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from .models import Course,Step,Enrollment from django.http import Http404 from django.contrib.auth.decorators import login_required @login_required def course_list(request): #courses = Course.objects.all() courses = Course.objects.filter(id in Enrollment.objects.filter(student=request.user)) return render(request,"courses/course_list.html",{'courses':courses}) -
How to access django python returned JSON data in the javascript part of an htmlpage
I want to know how to access the a django python returned JSON data in the javascript part of an html page. This is JSON data that I'm getting from the server end which I've logged in the browser console {"movieName": "Avengers", "releaseYear": "2019", "boxOffice": "2.3B"} 68 Here is my sample code Javascript part var dataFromDjango = "{{ myData | escapejs | safe }}"; console.log(dataFromDjango); var t = Object.keys(dataFromDjango).length; console.log(t); Python code context = {} context['movieName'] = 'Avengers' context['releaseYear'] = str(2019) context['boxOffice'] = '2.3B' jsonData = json.dumps(context) return render(request, "InterfacePage.html", {"myData" : jsonData}) I was expecting the length of keys to be 3. -
Django Race Condition when increment use table inside form_valid
I am using class based views. I am trying to increment a value everytime user create a new record. #models.py class User(models.Model) transaction_counter = models.PositiveIntegerField( default=1, # +1 when new transaction created ) class Transaction(models.Model) number = models.PositiveIntegerField() # base on the user.transaction_counter #views.py class TransactionCreate(CreateView): model = Transaction @transaction.atomic def form_valid(self, form): form.instance.number = self.request.user.transaction_counter # just assign the number self.request.user.transaction_counter= F('transaction_counter') + 1 self.request.user.save() # now we +1 for the next transaction return super().form_valid(form) Question Since I already use F() to increment the user.transaction_counter, does this solve the race condition issue? If no, please guide me on this. If yes Thank you & Love you. -
Event listener for 'devicemotion' not running function
I'm trying to assign motion to 3 variables outside the event listener, but the function inside my event listener doesn't even seem to be running. I've tried checking it like this too: if (window.DeviceMotionEvent) { console.log("devicemotion was defined"); }; The console logged the text, but not this text: var x, y, z; var interval; var arr = {'data':[]}; var ON = false; window.addEventListener("devicemotion", function(event){ x = event.accelerationIncludingGravity.x; y = event.accelerationIncludingGravity.y; z = event.accelerationIncludingGravity.z; console.log(x,y,z) } ,true); Edit: This script code is in the bottom of a html file located in a templates directory. The html is running on Django. -
Restricting a django page to unverified accounts [duplicate]
This question already has an answer here: Making a Django page visible only to confirmed emails 2 answers I am creating a Django site, and i would like to have some parts of this site restricted to users who did not confirm their email address. Basically, if you try to open X page and your email is not confirmed, you'll get an error. I found a solution, but it's not working. Here is what i did: I have been suggested to add a separate model for this: class account_emailconfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def has_verified_email(self): return self.user.emailaddress_set.filter(verified=True,primary=True).exists() And this is what the template looks like: {% extends "main/header.html" %} {% if user.account_emailconfirmation.has_verified_email %} {% block content %} <style> </style> <body> <div> <p>Here goes a bunch of features</p> </div> </body> {% else %} <p> Your email is ot confirmed </p> {% endif %} {% endblock %} The current solution has a problem: for some reason, even if the email is confirmed, i'll still get 'Not confirmed', while it should allow me to see the page if my email is confirmed. Here is what my db looks like: There is a table called account_emailconfirmation, then there is an index, verified, that … -
Could not open requirements file jenkins
failed to build what is the problem here. He wont find the requirement.txt but it is in the same directory of the manage.py No credentials specified pip3 install --user -U -r requirements.txt Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' You are using pip version 19.0.3, however version 19.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. + pip3 install --user -U -r requirements.txt Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' You are using pip version 19.0.3, however version 19.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. -
How to rename django core migration tables?
The Django core migrations create the following tables auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_permissions django_admin_log django_content_type django_migrations django_session But I would like to add acps before each of the table names like the following. acps_auth_group acps_auth_group_permissions acps_auth_permission acps_auth_user acps_auth_user_groups acps_auth_user_permissions acps_admin_log acps_content_type acps_migrations acps_session That is because I would like to run multiple instances of Django in the same database. I am using SQL Server and Django 2.1.8 Is there any way I can accomplish this? -
Why is my filter/search javascript script not working?
I'm trying to add a simple search/filter function to the backend of my website, but it doesn't work as i've adapted it from some other code that works on lists and i'm using divs. My html is also apart of a django backend, but hopefully that shouldn't effect the outcome of the javascript code This is the javascript / var userInput, filter, adContainer, daContainer, daRow, rowCont, val, i, j; input = document.getElementById('modal-search'); filter = input.value.toUpperCase(); adContainer = document.getElementById('adminContainer'); daContainer = adContainer.getElementByClassName('dataContainer'); for (i = 0; i < daContainer.length; i++){ rowCont = daContainer[i].getElementsByClassName('rowContainer') daRow = rowCont[0].getElementsByClassName('rowContainer'); val = daRow.innerHTML; if (val.toUpperCase().indexOf(filter) > -1){ daContainer[i].style.display = ""; } else{ daContainer[i].style.display = "none"; } } } This is my html below / <div id="adminContainer"> {% for info in data %} <div class="dataContainer"> {% for key, value in info.items %} {% if not forloop.last %} <div class="rowContainer"> <div class="rowHeading"> {{ key }} <!-- --> </div> <div class="rowData"> {{ value }}<!-- --> </div> </div> {% else %} <div class="rowContainer"> <div class="rowHeading" style="border: none;"> Actions </div> <div class="rowActions"> <a class="modal-btn" data-modal="modal-window-edit-{{ value }}"><img src="{% static 'Cobras/imgs/view-icon.png' %}"></a> <a class="modal-btn" data-modal="modal-window-delete-{{ value }}"><img src="{% static 'Cobras/imgs/delete-icon.png' %}"></a> </div> </div>``` -
Django - Delete File After FileField Delete
I have a Django project which in i use file field to upload files. What i want to do is to delete the file field's file every time a model with a file field gets deleted I used This document as an example: https://djangosnippets.org/snippets/10638/ when i use these functions i get the dollowing error on the server: "Error 32 - The process cannot access the file because it is being used by another process" I think that the process which uses it is the django server because i tried to delete it with a regular python script (same functions) and with batch and it worked just fine. Anyone knows a way around this? -
django-allauth) How to get access token from access code in url?
I'm trying to add social login to my django-rest-framework app, but I'm stuck on this problem and need some help. I used django-allauth to get code, which is used to get access token. Login Flow: Request code(GET) -> Response -> Request token(POST) -> Response API reference here So, after I log in to social account,(e.g. Facebook)click authorize my app button, I get access code like this : "GET /accounts/kakao/login/callback/?code=1cH2huI2SuGuZxY4wYHU8hieeIXAhhL_XTpTqdR0g5DV1Zn8smcGzheW4IqakEEzNshfMAo9dVoAAAFqzwxacQ&state=uqTv1puHiHuy HTTP/1.1" 200 487 But I just don't know how to get access token from this url! Should I make new view class inside of my view.py file? should I make a new url for getting access token?? -
How to configure django server and react server to AWS elastic beanstalk service at the same time
I am wondering how to setup and connect python server and react.js server to aws beanstalk at the same time. Ask someone who has some experience. -
Django Model-Register
My users upload sensor measurements to a django-backend. Before the upload, they post some foreignkey meta data via rest-calls, like Sensorposition and Sensorname from the models class Sensorname(models.Model): name = models.CharField(max_length=255) class Sensorposition(models.Model): name = models.CharField(max_length=255) Sometimes they want to upload a compressed file that contains measurements from multiple different sensors and they would like to post a Sensor-Registry for them that contains the name, positions and a description.pdf for each of the measured sensors: Sensor-Registry-Name Sensor1name Sensor1positions Sensor1description.pdf Sensor2name Sensor2positions Sensor2description.pdf ... I came up with the solution to have a Sensor class class Sensor(models.Model): sensorname= models.ForeignKey(Sensorname) sensorpositions = models.ManyToManyField('Sensorposition') description_pdf = models.FileField(...) which then can be added to a SensorRegistry that looks like this class SensorRegistry(models.Model): registryname=models.CharField(max_length=255) sensors = models.ManyToManyField('Sensor') This solution works okayish, however, if the same sensor is used at a different position, e.g. ["front"] instead of ["middle", "left"], the users first have to create a new Sensor with the same Sensorname and Sensordescription but with a different position. How can this be improved? Is there a solution where they first enter a registryname and then post as many instances of the set [Sensorname, Sensorposition, description_pdf] as they want? -
how to use context_processor properly in django
here i am trying to redirect to another page if the form is submitted successfully but this code is not woking properly .the code saves the form data sends the email , everything is fine but the problem is while redirecting to another page if the form succeed.the error i get is: Django Version: 2.0.6 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 0; 2 is required context_processor.py def volunteer_page2(request): volunteer = Volunteer.objects.all().order_by('date') if request.method == 'POST': form = VForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = "{0} with email address {1} has sent you new message \n\n{2}".format(name, email, form.cleaned_data['message']) form.save(commit = False) try: send_mail(name, message, 'appname <settings.EMAIL_HOST_USER>', ['myemail']) except: return HttpResponse('Invalid header found') form.save() messages.success(request, 'Success') return redirect('volunteer_page') else: messages.error(request, "Sorry try again") else: form = VForm() return {'volunteer': volunteer, 'form':form} views.py def about_page(request): about = About.objects.all().order_by('date') banner = Banner.objects.all() testimonial = Testimonial.objects.order_by('-pk')[0:2] nav = Nav.objects.all() footer = Footer.objects.all() latest_event2 = Events.objects.order_by('-pk')[0:2] context = { 'about': about, 'testimonial': testimonial, 'footer':footer, 'banner': banner, 'nav': nav, 'latest_event2': latest_event2, } return render(request, 'myapp/about.html', context) settings.py 'myapp.context_processor.volunteer_page2' -
Celery task not working in Django framework
I tried code to send_email 5 times to user as Asynchronous task using Celery and Redis Broker in Django Framework. My Celery server is working and it is responding to the celery cli interface also but when I am going to call using task it is giving me some bad syntax error I installed redis server on windows and It is working on 6379 port. I am able to get msg from server when I ping it using redis-cli. but When I tried to run on Django server showing as client connected but getting bad syntax error task.py - from celery import task from django.core.mail import EmailMessage import time @task(name="Sending_Emails") def send_email(to_email,message): time1 = 1 while(time1 != 5): print("Sending Email") email = EmailMessage('Checking Asynchronous Task', message+str(time1), to=[to_email]) email.send() time.sleep(1) time1 += 1 views.py - print("sending for Queue") send_email.delay(request.user.email,"Email sent : ") print("sent for Queue") settings.py - # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/India' celery.py - from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ECartApplication.settings') app = Celery('ECartApplication') # … -
Django CustomMiddleware causing csrf_token issues during log in
I have been trying to implement this logic: Whenever a user signs up, confirms his email, his account is active. However, in order to let the user gain full access to the website, he must enter some data first about his own self. I call it complete-profile. I figured making a middleware is a good way to implement the logic. So I wrote the following: class CompleteProfileMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) if request.path == "/account/" + request.user.username + '/complete-registration/': pass elif request.user.is_anonymous: pass elif request.user.is_superuser: pass elif request.user.student.complete_profile: pass elif not request.user.student.complete_profile: return redirect('/account/' + request.user.username + '/complete-registration/') # Code to be executed for each request/response after # the view is called. return response However, now, for accessing the complete profile page, people need to log in first. And during the log in process, it gives issues with the csrf token as: Forbidden. CSRF verification failed. Request aborted. If I remove the middleware everything starts working again, so the issue has to be here. -
Django Postgres View issue - Cannot delete User - Views containing GROUP BY are not automatically updatable
I am using Django (1.11.7) and Postgres (9.4) for my webapp. upon doing this: employee_var = Employee.objects.get(id = employee_id) employee_var.user.delete() <--- this where the error occurs employee_var.delete() the delete() for user will throw this following error cannot delete from view "view_attandance_reports" DETAIL: Views containing GROUP BY are not automatically updatable. HINT: To enable deleting from the view, provide an INSTEAD OF DELETE trigger or an unconditional ON DELETE DO INSTEAD rule. I'ved included my code for my model, view https://gist.github.com/axilaris/2f0164a7188ada5d86975c7e401ab454 after having this view, im not able to delete a record for Employee&User model ? How can perform a proper delete for these model ? -
GitLab CI/CD without Docker - automatically pull code on VPS
Can I use GitLab CI/CD without Docker? I'm thinking about something like this: run pytest if all goes fine run git pull origin master on my VPS run manage.py migrate run manage.py collectstatic run gunicorn and nginx reload How can I automatically pull code on my VPS and run these commands? -
How to import function as list
I have a class which expects a list as an argument. The issue is when I import this function and use it as an argument I get a TypeError or ValueError. I have tried searching for this issue but cannot seem to find matching issues. Code which is having issues: from payroll.payroll import get_employee_names class ManagerForm(forms.Form): names = forms.ChoiceField(choices=[get_employee_names()]) Function which is imported: def get_employee_names(): # place uploaded files into variables tips_file = 'media/reports/Tips_By_Employee_Report.xls' # get managers name df_employee_names = pd.read_excel( tips_file, sheet_name=0, header=None, skiprows=7) df_employee_names.rename( columns={0: 'Employee'}, inplace=True) df_employee_names['Employee'] = \ df_employee_names['Employee'].str.lower() # data-frame to list employee_names = df_employee_names.loc[:, 'Employee'].tolist() return employee_names I expect it to use the list which is returned at the end of the function to create a dropdown menu. The main Error I am currently getting is: ValueError at /select-manager-run-payroll/ too many values to unpack (expected 2)