Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Group by timestamp column serving as PK by day/month/year, and select that timestamp column at the same time in Django
I have a table with a 'timestamp' field as its PK. In Django View, I want to select all from the table and group by month('timestamp) and year('timestamp). In terms of MySQL script, I am looking for this: SELECT timestamp, sum(col1) col1, sum(col2) col2 FROM my_table GROUP BY MONTH(timestamp), YEAR(timestamp) ORDER BY timestamp One approach I have followed is from here. You can find more elaboration on that answer here. So to GROUP BY the rows, I work with annotate and values as discussed in this answer. The code in my Django View is the following: from django.db.models.functions import TruncMonth, TruncYear from django.db.models import Sum queryset = MyModel.objects .annotate(month=TruncMonth('timestamp'), year=TruncYear('timestamp')) .values('month', 'year') #Group by Month and Year .annotate(col1 = sum('col1'), col2 = sum('col2')) #Sum data of two columns .order_by('month', 'year') #Also tried 'timestamp' here. queryset_serialized = MySerializer(queryset, many=True) The code above does produce the query as expected. Here is the query generated from the code above: SELECT CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME) AS `month`, CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) AS `year`, SUM(`col1`) AS `col1`, SUM(`col2`) AS `col2` FROM `my_table` GROUP BY CAST(DATE_FORMAT(`timestamp`, '%Y-%m-01 00:00:00') AS DATETIME), CAST(DATE_FORMAT(`timestamp`, '%Y-01-01 00:00:00') AS DATETIME) ORDER BY `month` ASC However, while serializing the data … -
How to catch / get json from webhook in Django?
I am working with Pipedrive and Django. So far I have the following: I have configured a webhook in pipedrive that fires every time a new Deal is created, I am receiving the correct http status in the Django console, however, I cannot capture the data from the json that the webhook sends . The idea is to capture that data and then enter it into Django's model. -
Call function after update/bulk_update in Django
I am calling a function after an object is created in the model like this: class MyModel(models.Model): name = models.CharField() image = models.OneToOneField(Image, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.image.my_function() Now I want to call the same function after updating/bulk_updating the instances. I know I can create a post_save listener which can handle the case after update(), but how to call the function after bulk_update()? -
Odoo developer as a Full stack developer
Is odoo developer will work as a full stack developer later in career. He can work on core python and framework like Django??? -
Setting time zone according to user's Country
I am building a BlogApp AND i am stuck on a Problem. What i am trying to do :- I am trying to store timezone in every field ( post date, comment date ) according to User's Country. Suppose, A user is registered account on webapp from Brazil then i am trying to automatically set time zone of Brazil for the User. But i have tried many answers LIKE THIS and LIKE THIS but nothing worked for me. Some told that it should be done through JavaScript BUT i have no idea idea how can i do it. When i try to register then it automatically sets the timezone which i have settled in settings.py. TIME_ZONE = 'UTC' Any help would be appreciated. Thankyou in advance. -
user register form in the django not getting register
I am trying to register the user of the django website but it was not getting register I am posting the code please help me this is the code of the views.py where I get the input from django.shortcuts import render , redirect # Create your views here. from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm from .models import User_Main def become_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request , user) user_main = User_Main.objects.create(name = user.username, created_by=user) return redirect('home') else: form = UserCreationForm() return render(request, 'user_of_ecommerce/become_user.html' ,{'form':form}) code of urls.py from django.urls import path from . import views urlpatterns = [ path('become-user/' , views.become_user , name="become_user") ] and here is the code of the form {% extends "core_of_ecommerce/base.html" %} {% block content %} <form action="." method="post" > {% csrf_token %} {{form.as_p}} <div> <button>sbmot</button> </div> </form> {% endblock content %} another URLs.py from django.urls import path from . import views urlpatterns = [ path('' ,views.home, name='home') ] -
One transaction for mongoDB and MySQL with one to many relationship
My Django application uses both MySQL and MongoDB to store its data. I need to create one transaction to delete an instance with its relations from both MySQL and MongoDB. If the execution of one of the queries fails (SQL or Mongo) I must rollback all the executed queries. Is that possible? Example: from django.db import models class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Motorcycle(models.Model): manufacturer = models.ForeignKey('Manufacturer',on_delete=models.CASCADE) # ... def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document tr return super(Instance, self).delete(*args, **kwargs) class Manufacturer(models.Model): # ... pass def delete(self, *args, **kwargs): ... # delete from mongoDB (must use a session to support multi document transaction) return super(Instance, self).delete(*args, **kwargs) When I delete a manufacturer, I need to delete the related cars and motorcycles from both MySQL and MongoDB. If one transaction fails (let's say delete one of the motorcycles has failed for some reason), I need to rollback all the transactions. Is there any way to do it? -
preferred way of designing model in Django
I have a very simple model in Django with 3 fields. The issue is that I have dozens of billions of data that needs to be stored in the table associated with that model in Postgresql database. I stored around 100 millions of rows, and then my server first got sluggish and then gave me "Nginx 505 bad gateway" when clicking on that table in Django admin or requesting data using API. I was wondering what is the best way to handle this simple scenario of having massive data in Django. What's the best model. Should I split my model in order to split my table? Thanks, -
Why does ChannelsLiveServerTestCase doesn't allow file upload
I am currently using ChannelsLiveServerTestCase to spin-up a runserver for my test, for some reason when I try to test my file upload feature it is failing but when I try using different "test server" (StaticLiveServerTestCase) it is working well. I opted to use ChannelsLiveServerTestCase because I need the websocket support which is not possible with StaticLiveServerTestCase. -
Can't login my users, they don't seem to be registering properly
I'm trying to login the users I registered in my registration view (where I get a 200 code that says POST request was successful) but I get "Unable to log in with provided credentials." when I try to log them in. When I check in the shell with User.objects.all(), I only get my superuser back so I think the users are not being saved to the database. I don't understand why this is happening so if anyone has an idea, it'd be appreciated. Here's the code. Models: from django.db import models, transaction from django.conf import settings from django.contrib.auth.models import BaseUserManager, AbstractUser class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) Serializers: … -
iterating issue in a for loop (Python3 + Django)
I am a newbie so please be kind, working on a blog app within my django project the idea is to check if there are articles , if there is list each article. if there is not articles show no articles found below is my view function, however when I test this it only list the first item in my list which mike, other names are not showing on the page or on source like they do not exist ??? any help with this would be great. thanks in advance def add(request): articles=["mike","sammy","ahmed"] if not articles : return HttpResponse("<body><h1>No Articles to display here</h1></body>") else: for article in articles: return HttpResponse(f"{article}") -
How can I allow a user to upload the template for a landing page for another user in Django?
I have the admin user able to upload via forms a landing page for a selected role (Student, Advisor, Admin) and I want to be able to get it to render properly. Right now, it renders properly the html and the css but prints out in plain text the {{ }}'s and the {% %}'s which isn't helpful. The view for the roles landing pages as of right now sends the plain text html (context['page'] = LandingPage.objects.get(role='adm', live=True)) stored in the database to the html stored in templates which has nothing in it except {{ page| safe}}. -
Add celery (tasker) To Django Admin panel on Search click
I am using the Admin panel of django for searching. Sometimes it can take 15 + minutes for search to finish and I get timeout (502). But search process still exist (consuming resources). I would like to show a progress bar waiting for task to finish when clicking: What is the best option for me ? -
django-channels: PUT request info not saving when user disconnects from websocket then reconnects
I have a problem. The app in question is basically complete, but there's a bug with the user PUT endpoint to edit the user info. If the websocket is disconnected, the endpoint works well. same if the websocket is connected. But If I edit the profile with the websocket connected, disconnect the websocket and connect it again, the changes I made are reverted. anyone know why? What's also weird is that the websocket is used only in chat, not for profile editing (chat is an entirely different app) Any help is appreciated -
Django HTML Email, Table List not working
Im working with Django HTML email. Sending Email with HTML template is working but my problem is the data not showing in table once already sent via email but in my localhost present. Please help me to fixed my issue,Thank You! This is the output when I show via localhost: This is the output when template already sent via email, The data in the table are missing. Here is my django email script: elif month == 4: cstatus = Regdata.objects.filter( Registration_month="APR", sent_email="No") s = "" for carreg in cstatus: print(carreg.PLATE_NO) s += carreg.PLATE_NO cstatus.update(sent_email="Yes") if s != "": subject = 'Hi' html_message = render_to_string('email.html', {'context':'value'}) plain_message = strip_tags(html_message) from_email = 'From <example@gmail.com>' to = 'example@gmail.com' mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) Html Email Template: <body> <h2>Hi,</h2> <p>Body message..........</p> <table id="example" class="display nowrap" style="width:100%"> <thead> <tr> <th>Plate Number</th> <th>CR Name</th> <th>Model</th> <th>Brand</th> </tr> </thead> <tbody> {% for object in apr_email %} <tr class="odd gradeX"> <td>{{ object.PLATE_NO }}</td> <td>{{ object.CR_NAME }}</td> <td>{{ object.MODEL }}</td> <td>{{ object.BRAND }}</td> </tr> {% endfor %} </tbody> </table> </body> -
removing default --------- option from radio button rendering in template
I am trying to remove the -------- value in my radio button display. The field is declared like this in models.py my_field = models.CharField(max_length=50, choices=MY_CHOICE, blank=True, null=True) I am using this ModelForm to apply some custom CSS forms.py class MyAppForm(ModelForm): class Meta: model = MyApp exclude = [] def __init__(self, *args, **kwargs): super(MyAppForm, self).__init__(*args, **kwargs) self.fields['my_field'].empty_label = None for i, f in self.fields.items(): f.widget.attrs['class'] = 'custom-class' I have seen this line self.fields['my_field'].empty_label = None suggested in multiple Answers on StackOverflow, but, it seem to have no effect in my setup. I am getting the value of the selected choice using this piece of code in views.py def app_view(request, fk_id): app_value = MyApp.objects.get(my_fk=fk_id) # my_fk is a fk from another model app_form = MyAppForm(instance=app_value) I am rendering this form by simply {% for value, text in my_field.my_field.field.choices %} <li> <input id="{{ value }}" name="{{ app_form.my_field.name }}" type="radio" value="{{ value }}" {% if app_value.my_field == value %}checked="checked"{% endif %}> <label for="{{ value }}">{{ text }}</label> </li> {% endfor %} What could I be doing wrong in this setup that is not removing the default select option, ------? -
"Unable to log in with provided credentials." when trying to login my user
I'm getting this error when I try to login a registered user. I read a bunch of answers in people asking the same question but none of them have solved my issue so I'm confused at to what's happening. I added some stuff to my settings like some comments said and changed some things and so far this is what I've written to no avail. Maybe some extra eyes can help. Thank you. I'll show here my serializers: user = get_user_model() class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta: model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords don't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password … -
Django error: ValueError at /cart/ -> The QuerySet value for an exact lookup must be limited to one result using slicing
I am getting a value error when adding the book to the cart. It points to for loop in views.py for orders. I am not able to figure a way to solve it. Any help is appreciated. bookstore-django/store/views.py", line 68, in cart for order in orders: Exception Type: ValueError at /cart/ Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing. models.py from django.db import models from django.db.models.query import prefetch_related_objects from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return "%s, %s" % (self.last_name, self.first_name) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField() publish_date = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.IntegerField(default=2) class Meta: verbose_name ='Book' verbose_name_plural = 'Books' db_table = 'book' #default is store_book class Review(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) publish_date = models.DateField(default=timezone.now) text = models.TextField() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) order_date = models.DateField(null=True) payment_type = models.CharField(max_length=100, null=True) payment_id = models.CharField(max_length=100, null=True) def add_to_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = BookOrder.objects.get(book=book, cart=self) preexisting_order.quantity += 1 preexisting_order.save() except BookOrder.DoesNotExist: new_order = BookOrder.objects.create( book=book, cart=self, quantity = 1 ) … -
I can't use cookies sent by a Django server
I created an authentication API on Django that sends csrf token in the response cookie when you send a request to a login endpoint. But it only works when I make these requests with Postman or directly from the browser: Postman login Postman Profile page access Response from a server to an axios request Here we see that there are no cookies in the browser: Cookies stored in the browser after request But here we clearly can see that server sent me cookies with csrf token and session id. Response cookies in the browser devtools But I can't access those cookies from the response object. There are not neither in document.cookies nor in response.headers['set-cookie']. I tried lots of things and unfortunately coundn't come up with anything. This is how I make requests: const login = (url) => { const creds = { "email": "example@gmail.com", "password": "hello" } axios.post(url + '/login', creds) .then( res => { console.log(res) } ).catch(err => console.log('ERROR: ' + err)) } const profile = (url) => { axios.get(url + '/profile', { withCredentials: true, }) .then( res => console.log(res) ).catch(err => console.log('ERROR: ' + err)) } And this is a login view in django: @api_view(['POST']) def login_user(request): user … -
Django Reverse Match Error with keyword arguments '{'pk': ''}' not found
I'm new to Django and programming in general. I'm going through the book Django For Beginners and have added my own flair in the forms section but have run into a problem. Below I have detailed the error and provided my code. ERROR NoReverseMatch at /drug/12/ Reverse for 'drug_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['drug/(?P[0-9]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/drug/12/ Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'drug_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['drug/(?P[0-9]+)/edit/$'] Exception Location: C:\Users\scott\django_sites\history_cloud1\history1_env\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: C:\Users\scott\django_sites\history_cloud1\history1_env\Scripts\python.exe Python Version: 3.8.3 models.py from django.db import models from django.urls import reverse class DrugInfo(models.Model): drug_name = models.CharField(max_length=75) patient_name = models.CharField(max_length=25, default='Enter Patient Name',) author = models.ForeignKey( 'auth.User',on_delete=models.CASCADE, ) def __str__(self): return self.drug_name def get_absolute_url(self): return reverse('drug_detail', args=[str(self.id)]) urls.py from django.urls import path from .views import ( drugListView, drugDetailView, drugCreateView, drugDeleteView, drugUpdateView, ) urlpatterns = [ path('drug/<int:pk>/delete/', drugDeleteView.as_view(), name='drug_delete'), path('drug/new/', drugCreateView.as_view(), name='drug_new'), path('drug/<int:pk>/', drugDetailView.as_view(), name='drug_detail'), path('drug/<int:pk>/edit/', drugUpdateView.as_view(), name='drug_edit'), path('', drugListView.as_view(), name='home'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import ( CreateView, UpdateView, DeleteView ) from django.urls import reverse_lazy from .models import DrugInfo class drugListView(ListView): model = DrugInfo template_name = 'home.html' class … -
Python django blog OperationalError
I want to enter the blog What should I do? enter image description here -
Django, use timedelta to add follow-up date to an invoice date
I've got this simple model that I'm using to practice various Django stuff: class Receivables(models.Model): agent = models.ForeignKey(Agents, on_delete=models.CASCADE, related_name='invoices') invoice_number = models.CharField(max_length=50) invoice_amount = MoneyField(decimal_places=2, default=0, default_currency='USD', max_digits=11) invoice_date = models.DateField() invoice_due_date = models.DateField() total_invoices = models.IntegerField(null=True) And I'm trying to create a follow-up date that is calculated to be 60 days from the invoice date. As I understand from researching, I need to use 'annotate' on my queryset, and so I tried this first: qry = Receivables.objects.annotate(follow_up_date=Receivables.invoice_date+timedelta(days=60)) And that threw a a TypeError for an unsupported operand for +: 'DeferredAttribute' and 'datetime.timedelta'. I found an anser on StackOverflow (to use an ExpressionWrapper), that I tried to work into my query like this: qry = Receivables.objects.annotate(follow_up_date=models.ExpressionWrapper(Receivables.invoice_date+timedelta(days=60))) But that throws the exact same error. Please help me understand what I'm doing wrong here. -
Webpack not creating bundle.js or error messages
I've tried installing webpack and babel-loader into my vue project. When I run 'npm run dev' in my terminal, I don't get any bundled files outputted to my dist folder and I get the following message: > vueproject@0.1.0 dev > webpack --watch --progress --mode=development Here's my file structure in my project: -vueproject -dist -src -deletethis.js package.json package-lock.json webpack.config.js babel.config.js package.json: { "name": "vueproject", "version": "0.1.0", "private": true, "scripts": { "test": "webpack", "dev": "webpack --watch --progress --mode=development", "prod": "webpack --mode=production", "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "@tailwindcss/line-clamp": "^0.2.0", "autoprefixer": "^9.8.6", "axios": "^0.21.1", "bcryptjs": "^2.4.3", "core-js": "^3.6.5", "mysql": "^2.18.1", "postcss": "^7.0.35", "postcss-loader": "^5.2.0", "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.0", "vue": "^3.0.0", "vue-router": "^3.5.1" }, "devDependencies": { "@babel/core": "^7.13.16", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/compiler-sfc": "^3.0.0", "autoprefixer": "^10.2.5", "babel-eslint": "^10.1.0", "babel-loader": "^8.2.2", "eslint": "^6.7.2", "eslint-plugin-vue": "^7.0.0", "path": "^0.12.7", "postcss": "^8.2.9", "postcss-cli": "^8.3.1", "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.0", "webpack": "^4.0.0", "webpack-cli": "^4.6.0" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/vue3-essential", "eslint:recommended" ], "parserOptions": { "parser": "babel-eslint" }, "rules": {} }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] } webpack.config.js: // webpack.config.js const path = require('path'); // Define the path module, which is used for handling and … -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__vacancies_company.owner_id error
I try to migrate and an error occurs: django.db.utils.IntegrityError: UNIQUE constraint failed: new__vacancies_company.owner_id from django.db import models from django.contrib.auth.models import User class Company(models.Model): name = models.CharField(max_length=64) location = models.CharField(max_length=64) logo = models.ImageField(upload_to="MEDIA_COMPANY_IMAGE_DIR") description = models.TextField() employee_count = models.IntegerField() owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name="owner_user") class Specialty(models.Model): code = models.CharField(max_length=32) title = models.CharField(max_length=32) picture = models.ImageField(upload_to="MEDIA_SPECIALITY_IMAGE_DIR") class Vacancy(models.Model): title = models.CharField(max_length=100) specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, related_name="vacancies") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="vacancies") skills = models.TextField() description = models.TextField() salary_min = models.FloatField() salary_max = models.FloatField() published_at = models.DateTimeField() class Application(models.Model): written_username = models.CharField(max_length=24) written_phone = models.CharField(max_length=12) written_cover_letter = models.CharField(max_length=300) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, related_name="applications") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="applications") python manage.py runserver result: OperationalError at / no such column: vacancies_company.owner_id -
Django File Structure
On my Admin page I click the 'view site' link and I get a Page not found (404) error. What exactly should I be seeing? My homepage or something else? Here is my Django file structure |--myWebsite |--myWebsite |--_pycache_ |--_init.py_ |--asgi.py |--settings.py |--urls.py |--wsgi.py |--home |--_pycache_ |--migrations |--static |--templates |--_init_.py |--admin.py |--apps.py |--forms.py |--models.py |--test.py |--tokens.py |--views.py |--db.sqlite3 |--manage.py Here is are my templates so far home page, login page, create account page, account page Others I plan to add in the future: reset password page, verify email page, forgot username/password page, etc. Main Homepage http://138.0.0.1:8000/home Thanks