Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fromisoformat: argument must be str
I have this date that formatted like this 2022-08-25 17:59:46.95300. messageDate = value['MessageDate'] //2022-08-25 17:59:46.95300// newDate = datetime.strptime(messageDate, '%Y-%m-%d %H:%M:%S.%f' saverecord.created_at = newDate When I run the function, I'm having this error in parse_date return datetime.date.fromisoformat(value) TypeError: fromisoformat: argument must be str -
django mod_wsgi and apache: module not found error
I am trying to move my django project to production using apache2 and mod_wsgi. I keep getting a wsgi_error "ModuleNotFoundError" in the apache logs. I run on ubuntu 22.04. After going through the various posts on the web I still am not getting anywhere, so I have now started from scratch by creating a new example django app. The same error occurs. PS, When I use "runserver" the django app displays fine in the browser. Also a simple wsgi "hello_world" app runs fine in apache. So I think the basic setup is fine. I have created a django test application "mytest" with django-admin startproject mytest The project is created in /home/user/myprojects/mytest, the group of all directories is www-data In mytest I have the usual django structure home/user/myprojects/mytest manage.py mytest asgi.py __init__.py settings.py urls.py wsgi.py The wsgi.py is: (The django/python runs in a virtual environment I found that I needed to add code to the wsgi to actually activate the virtual environment) """ WSGI config for mytest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ python_home='/home/user/.virtualenvs/myproject' activate_this= python_home + '/bin/activate_this.py' with open(activate_this)as f: code=compile(f.read(),activate_this,'exec') exec(code, dict(__file__=activate_this)) import os … -
Django - If statement with request.user
I have a problem with an if-statement. I just want to check on a page if the user who requests the listing page is the same one as the user who won the listing on that page. My view looks like this: def show_closed_listing(request, listing_id): closed_listing = InactiveListing.objects.get(id=listing_id) field_name = "winning_user" winning_user = getattr(closed_listing,field_name) message = False print(request.user) print(winning_user) if request.user == winning_user: print("This is good") message = "You have won this listing!" else: print("Not good") return render(request, "auctions/closed_listing.html", { "closed_listing" : closed_listing, "message" : message }) When I visit a page, signed in as Test2, when Test2 has won the listing, my terminal shows as follows: Test2 Test2 Not good As also can be seen here I don't get why request.user and winning_user look the same, but the if-statement is false? If needed, here is my model: class InactiveListing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=512, default="") winning_user = models.CharField(max_length=128) winning_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.01) def __str__(self): return self.title -
django.db.utils.OperationalError: no such column: authentication_user.name
I was trying to add a new field to my User authentication model. But whenever I'm trying to run python manage.py makemigrations, the console is showing, django.db.utils.OperationalError: no such column: authentication_user.name Here is a part of my Model: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, max_length=36, default=uuid.uuid4, editable=False,blank=False, null=False) cus_id = models.CharField(max_length = 250, null=True, blank=True, default=increment_cus_number) email = models.EmailField(max_length=255, unique=True, db_index=True) username = models.CharField(max_length=250, blank = True, null = True) name = models.CharField(max_length=250, default = '', blank = True, null = True) first_name = models.CharField(max_length=250, blank=True, null=True) last_name = models.CharField(max_length=250, blank=True, null=True) mobile = models.CharField(max_length = 100, null = True) date_of_birth = models.DateField(blank=True, null=True) address = models.TextField(blank=True, null=True) picture = models.ImageField(blank=True, null=True) gender = models.CharField(max_length=100, blank = True, null= True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) business_partner = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email any suggestions/tips regarding this issue would be a great help. -
for loop in django template input is only fetching the last one
I have a for loop in django templates and each iteration must save to two different instances. templates <p><label>{% trans "Payment Method" %}</label> {% for rs in shopcart %} <select class="input" name="payment" id="id_payment{{forloop.counter}}"> <option value="COD" data-description="Item 1" selected="selected">{% trans "COD" %}</option> <option value="Bank Transfer" data-description="Item 2">{% trans "Bank Transfer" %}</option> </select> <p id="description{{forloop.counter}}"></p> <script> $('#id_payment{{forloop.counter}}').change(function(){ var $selected = $(this).find(':selected'); $('#description{{forloop.counter}}').html($selected.data('description')); }).trigger('change'); </script> {% endfor %} views form = OrderForm(request.POST) if form.is_valid(): for rs in shopcart: d = Order() d.payment = form.cleaned_data['payment'] d.save() else: messages.warning(request, form.errors) form = OrderForm() context = { 'form': form } return render(request, 'Order.html', context) I wanted the payment choice to be made for each product in shopcart, but the last choice is fetched and given to all the products in the shopcart. Any advice would be nice. Thankyou in advance! -
Django: get all objects with a defined set of related objects
Let's say we have a many2many relationship as follows: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author, related_name="books") and now I have a known set of Authors: authors = Author.objects.filter(...) How can I get all the books that are authored by that exact set of authors? books = Book.objects.filter(X) what is X? Such that I have all the books authored by exactly that set of authors? I have tried, just because: books = Book.objects.filter(authors__in=authors) But nah, that returns the books to which any of those authors contributed it seems. I want the books that all of those authors contributed to and only those authors. Thus far, this has stumped me. -
Problem to show contact detail page - Django and Vuejs
I'm trying to learn how to use vuejs in a django project (i'm not using DRF) and I'm having trouble configuring my url to display a detail page view. So far i have configured urls.py like shown below: app_name = 'contacts' urlpatterns = [ path('', views.contacts_all, name='contacts_all'), path('<int:contact_id>/', views.contact_details, name='contact_details'), ] Also i have a views.py like shown below: def contacts_all(request): # Check if an Ajax Request if request.headers.get('X-Requested-With') == 'XMLHttpRequest': contacts = list(Contact.objects.values()) return JsonResponse(contacts, safe=False, status=200) return render(request, 'contacts/all-contacts.html') def contact_details(request, contact_id): contact_detail = get_object_or_404(Contact, id=contact_id) context = { 'contact_detail': contact_detail } return render(request, 'contacts/contact-detail.html', context) Also i successfully getting all contacts from django server: <script> const app = new Vue({ delimiters: ['[[', ']]'], el: '#contact-app', data: { contacts: [], }, methods: { // Get all contacts from server async getContacts(){ const response = await axios({ url: 'http://127.0.0.1:8000/contacts/', method: 'get', headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(response => { console.log(response.data); this.contacts = response.data }).catch(err => { console.log(err) }); }, }, async created(){ await this.getContacts(); } }); </script> And in template i'm successfully showing all contacts data like shown below: <div class="flex-row-fluid ml-lg-8 d-block" id="contact-app"> <div class="card card-custom card-stretch"> <div class="card-body table-responsive px-0"> <div class="list list-hover min-w-500px" data-inbox="list" v-if="contacts.length" > … -
I am unable to get round toggle in my django template
I have a table which contains for loop and if tag using jinja this table shows some data but in last column I want round toggle button but I only get a checkbox, I am unable to find the error please help me. <tbody> {%for student in students%} {%if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year%} <tr> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <label class="switch "> <input type="checkbox" id="" value="" checked> <span class="slider round"></span> </label> </td> </tr> {% endif %} {%endfor%} </tbody> OUTPUT Output Image -
in django set default image to ImageField as Default object
I have a model in the model and Imagefield is there. class Job(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to=" jobOpeningImages", default=' jobOpeningImages/1_oKH7Co9.jpeg', blank=True) But I am not getting any current image URL in the localhost. I am expecting this type of result So how can we achieve the below? in first image Currently: jobOpeningImages/1_oKH7Co9.jpeg -
useEffect fires and print statements run but no actual axios.post call runs reactjs
I have a useEffect function that is firing due to yearsBackSettings changing and the console.log statements inside useEffect fire too: useEffect(() => { console.log("something changed") console.log(yearsBackSettings) if (userId) { const user_profile_api_url = BASE_URL + '/users/' + userId const request_data = { searches: recentSearches, display_settings: displaySettings, years_back_settings: yearsBackSettings } console.log("running user POST") console.log(request_data) axios.post(user_profile_api_url, request_data) .then(response => { console.log("user POST response") console.log(response) }) } }, [recentSearches, displaySettings, yearsBackSettings]) As the image shows, changing yearsBackSettings causes this to run, which SHOULD make a post request with all the new settings: However, for some reason there is nothing happening on the server except the stock search running: the last updated time for stock ibm before save: 08/25/2022 08:13:30 stock was updated within the last 5 minutes...no need to make an api call the last updated time for stock ibm after save: 08/25/2022 08:13:30 [25/Aug/2022 08:17:25] "POST /users/114260670592402026255 HTTP/1.1" 200 9 [25/Aug/2022 08:17:25] "GET /dividends/ibm/3/5 HTTP/1.1" 200 4055 the last updated time for stock ibm before save: 08/25/2022 08:13:30 stock was updated within the last 5 minutes...no need to make an api call the last updated time for stock ibm after save: 08/25/2022 08:13:30 [25/Aug/2022 08:17:26] "GET /dividends/ibm/27/5 HTTP/1.1" 200 8271 the last updated … -
Django url path regex: capturing multiple values from url
How do I capture multiple values from a URL in Django? Conditions: I would like to capture ids from a URL. The ids vary in length (consist of numbers only), and there can be multiple ids in the URL. Check out the following two examples: http://127.0.0.1:8000/library/check?id=53&id=1234 http://127.0.0.1:8000/library/check?id=4654789&id=54777&id=44 The solution may include regex. urlpatterns = [ path("", view=my_view), path("<solution_comes_here>", view=check_view, name="check_view"), ] P.S. all solutions I found on this platform and Django documentation only explain cases for capturing single values from the URL -
How to make import using unique_together?
I need to make an import using not only the id field but also the brand field. So that products can exist with the same ID but a different brand class Part(models.Model): brand = models.CharField('Производитель', max_length=100, blank=True, default='Нет производителя') id = models.CharField('Артикул', max_length=100, unique=True, primary_key=True) name = models.CharField('Название', max_length=100, blank=True, default='Нет имени') description = models.TextField('Комментарий', blank=True, max_length=5000, default='Нет описания') analog = models.ManyToManyField('self', through='ContactConnection',blank=True, related_name='AnalogParts') analog = models.ManyToManyField('self',blank=True, related_name='AnalogParts') images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True) images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True) def __str__(self): return str(self.id) return self.name class Meta: verbose_name = 'Запчасть' verbose_name_plural = 'Запчасти' unique_together = [['id', 'brand']] class PartConnection(models.Model): to_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='to_parts') from_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='from_parts') -
When a button is clicked I want ajax to redirect towards a url but it is not working
I am trying to create a SPA, using django and javascript, I have a home page with two buttons on it (Sign up and sign in), I want that when signup button is clicked, ajax redirects towards signup url Here is my code js $('#id_register').click(function(){ $.ajax({ url: 'register', method:"GET", success: function(data){ console.log(data) }, error: function(error){ console.log(error) } }) }) Here is my html <div class="banner"> <div class="content"> <h3 id="home">Feeling Hungry?</h3> <h4 id="home_para">Order right now!</h4> <div> <button id="id_sign" type="button">Sign In</button> <button id="id_register" type="button">Sign Up</button> </div> </div> </div> </body> It is successfully returning me the data but not redirecting towards the required url. here is my urls.py urlpatterns =[ path('register', RegisterView.as_view()), path('login', LoginView.as_view(), name="login"), path('', HomeView.as_view(), name="home") ] I will be very thankful for the help -
Django: Add model object to aggregated queryset
Is there a way to add object to aggregated queryset? For example: qs = Model.objects.filter(title="abc").aggregate(likes=Count('likes')) and i want to do something like: qs = Model.objects.filter(title="abc").aggregate(likes=Count('likes')).get(pk=1) -
Django serving build with many MIME Type errors (sveltekit)
index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="/static/icons/tabIcon.svg" /> <link rel="stylesheet" href="/static/posty.css" /> <meta http-equiv="content-security-policy" content="" /> <link rel="modulepreload" href="/static/_app/immutable/start-6f351e07.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/index-d9a79891.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/index-d827f58a.js" /> <link rel="modulepreload" href="/static/_app/immutable/chunks/singletons-eca981c1.js" /> </head> <body> <div> <script type="module" data-sveltekit-hydrate="45h" crossorigin> import { set_public_env, start, } from "/static/_app/immutable/start-6f351e07.js"; set_public_env({}); start({ target: document.querySelector('[data-sveltekit-hydrate="45h"]') .parentNode, paths: { base: "", assets: "/static/" }, session: {}, route: true, spa: true, trailing_slash: "never", hydrate: null, }); </script> </div> </body> </html> svelte.config.js import adapter from '@sveltejs/adapter-static'; import preprocess from 'svelte-preprocess'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: preprocess(), kit: { adapter: adapter({ assets: 'build/assets', out: 'dist', fallback: 'index.html', precompress: false }) } }; export default config; settings.py # ... DEBUG = True STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/assets') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # ... Errors The resource from “http://127.0.0.1:8000/_app/immutable/pages/__layout.svelte-bd484656.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://127.0.0.1:8000/_app/immutable/assets/__layout-ce6f71c3.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “http://127.0.0.1:8000/_app/immutable/chunks/index-d9a79891.js” … -
Manager isn't accessible via User instances
I m trying to insert email but there is an error Manager isn't accessible via User instances. here is the my code below from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from rest_framework import serializers from rest_framework.validators import UniqueValidator from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models import Trip, User class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) group = serializers.CharField() def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): group_data = validated_data.pop('group') group, _ = Group.objects.get_or_create(name=group_data) data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] user = self.Meta.model.objects.create_user(**data) user.objects(validated_data['email']) user.groups.add(group) user.save() return user class Meta: model = get_user_model() fields = ( 'id', 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'group', 'photo', ) read_only_fields = ('id',) class LogInSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) user_data = UserSerializer(user).data for key, value in user_data.items(): if key != 'id': token[key] = value return token -
Pytest test failing when run with other tests but passes when run by itself
I very basic test that checks if a user that is not logged in can connect to my websocket that is as follows: @pytest.mark.asyncio async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator): connected, subprotocol = await unauthenticated_websocket_communicator.connect() assert subprotocol == 3000 # subprotocol 3000 is Unauthorised assert connected is False This test passes when i test it by itself from the cli using pytest -k test_unauthenticated_cant_connect_to_websocket but fails when i use pytest from the cli my consumer connect function is as follows: async def websocket_connect(self, event: dict) -> None: if self.scope["user"].is_anonymous: await self.close(code=3000) else: await self.accept() I have a number of other async tests with similar types of code but they all pass. Any suggestions would be much appreciated -
access foreignkey field from other field which is foreign key to other
I have model 3 models model 1 2 and 3 i need to access model 1 from model 3 model 2 has foreign key relation with model 1 and model 3 to model 2 how can access model 3 to model 1 class Record(models.Model): name = model.CharField(max_length=255) class Task(model.Model): name = models.CharField(max_length=255) record = models.ForeignKey(max_length) class Subtask(models.Model): name = models.CharField() subtask_of = models.Foreignkey('Task') I need to access the record name from Subtask how can i achieve that -
Django models multiple inheritance, class meta
I have my models in my app but I can play with the inheritance. This is a tree of my models :enter image description here We can see a double inheritance on ParticulierV, PaticulierF, AssociationF, EntrepriseF and EntrepiriseV. I need to be able to find a user by his statut (FournisseurStatut or VendeurStatut), but also to access to parameters (like email, username...) from Base, because some actioons apply to all type of user (exemple : check email). I don't need a data table for base, FournisseurStatut and VendeurStatut. I don't know how I have to configure my meta class for that. Here my models : # -*- coding: utf-8 -*- import uuid from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils import timezone class Base(models.Model): """ basic model - email - password - id - date joined - last_login """ id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) email = models.EmailField(unique=True, db_index=True) # check email validate_email = models.BooleanField(default=False) # review password place password = models.CharField(db_index=True, max_length=50) # hacher date_joined = models.DateTimeField(_("date joined"), default=timezone.now) last_login = models.DateTimeField(_("last login"), blank=True, null=True) class Meta: abstract = True class SupplierStatus(models.Model): """ Supplier status id supplier """ id_SupplierStatus = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) # do a … -
can I add my script/apis to my Django project? If so how can I do this
So I am building a Django web app, and I want to allow users to search for their desired crypto currency and then return the price. I plan on getting the price from coinbase or some other site that already presents this information. How would I go about this. I figure I would have to wrote the script to get the price under views.py. What would be the best approach? Can I add a web scrapping script that already does this to django? Or would I have to connect say coinbases api to my Django project. If so how do I do this? -
Fetch and return category and all related objects
I have a Bookmark and a BookmarkCategory object. I'd like to be able to fetch JSON that looks like this: GET -> localhost:8000/api/bookmarks [ "python": { "title": "Python", "bookmarks": [ { "title": "Python Documentation", "url": "https://docs.python.org" } ] }, "javascript": { "title": "Javascript", "bookmarks": [ { "title": "Python Documentation", "url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript" } ] } ] Here's my models: class BookmarkCategory(models.Model): title = models.CharField(max_length=255) class Bookmark(models.Model): title = models.CharField(max_length=255) url = models.CharField(max_length=255) category = models.ManyToManyField(BookmarkCategory) Here's how I would query all the BookmarkCategory objects: from .models import BookmarkCategory bookmarks = BookmarkCategory.objects.all() The JSON doesn't have to look exactly like this. I just need to get all my BookmarkCategory objects along with all the related Bookmark objects so I can iterate over them after I make a GET request to fetch them. -
Django TIME_ZONE is set but correct default is not set for datetime field
I set TIME_ZONE = 'Asia/Tehran' into project settings also i have datetime field into my models like below from django.utils import timezone class SomeModel(models.Model): ... datetime = models.DateTimeField(default=timezone.now) but the correct default value is not set for datetime field. I did the same thing before and it was correct, maybe it could be from nginx? code is running into linux(Ubuntu) server -
Django serializer not raising exception over model constraints
I have this dummy model from django.db import models class ChertModel(models.Model): username = models.CharField(gettext_lazy('username'), max_length=150, unique=True) o2 = models.CharField(gettext_lazy('username2'), max_length=150,editable=False, default='lllss') and with serializer class ChertSer(serializers.ModelSerializer): class Meta: model = ChertModel fields = ['username','o2'] note I have an instance with username='sd' and o2='434as' so when in the view I want to update the o2 fields which is supposedly editable=False it doesnt update it which is ok but the problem is that it doesnt raise exception over model constraints. note I have checked this configuration with editable=True and the serializer applies changes thus there is no problem with serializer. class ChertView(views.APIView): def get(self, request): lt1=ChertModel.objects.get(username='sd') print('1',lt1.o2) ser=ChertSer(instance=lt1, data={'username':'sd','o2':'newo2'}, partial=True) print(ser.is_valid()) ser.is_valid(raise_exception=True) ser.save() lt1=ChertModel.objects.get(username='sd') print('2',lt1.o2) since it would make problem of changes of user not applied to model instance without acknowledging it to user. so my question is how to detect the times the updating object is not applied due to model constraints? of course I can manually detect it by checking ser.data=={'username':'sd','o2':'newo2'} but is there any more formal or common way to handle this? -
Virtual Environment for FastAPI
A quick question, do we need to create virtual environment for installing and using FastAPI. We use venv for Django right? So why not in FastAPI? -
Django Inline admin
Hi i have a model called "Files" registered with the admin it has two fields "file" and "filename" and in the same page we are showing another model fields in "JobsInline".This inline have "device ", "Lang"," AI_field" it is Multiple Select Field. I want to create multiple inline objects based on the choices selected in The multipleSelectField on saving objects of files, behind the scene. Let's say user selected file and filename , and then device is selected.I want on selecting one device and if 5 choices are selected then 5 objects of inline should be created. If you didn't understand the problem, please tell me , i am a newbie, So please ignore my mistakes if any.