Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Http Client requests
I would like to retrieve product data using the POST method and passing it the security key on the headers I get an HTTP 400 error def api(request): headers={'content-type':'application/json','security-key': 'valu-key'} url = 'http://api-content/product/GetProduct' x = requests.post(url, headers = headers) content=x.status_code return HttpResponse(content) -
Docker Django Postgres FATAL: password authentication failed for user "postgres
I am dockerizing my Django app. My configs are the following: csgo.env POSTGRES_NAME='postgres' POSTGRES_USER='postgres' POSTGRES_PASSWORD='postgres' POSTGRES_HOST='postgres_db' POSTGRES_PORT='5432' settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('POSTGRES_NAME', 'postgres'), 'USER': os.getenv('POSTGRES_USER', 'postgres'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'postgres'), 'HOST': os.getenv('POSTGRES_HOST', 'postgres_db'), 'PORT': os.getenv('POSTGRES_PORT', '5432'), } } docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile env_file: - csgo.env ports: - '8000:8000' volumes: - .:/code depends_on: - postgres_db postgres_db: image: postgres:13 restart: always ports: - '5432:5432' env_file: - csgo.env environment: - POSTGRES_NAME='postgres' - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' - POSTGRES_HOST='postgres_db' - POSTGRES_PORT='5432' When I run docker-compose up, I get the typical auth error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" and I am readdly stressed of it. I have been looking for a typo a day long and haven't figured it out. Please help me to debug! Note: I know that this kind of questions are overflowed on the Internet. My post is about finding a typo or a mechanical mistake by me. Thanks for understanding and not assigning the post as a duplicate one! -
KeyError: '__module__' when creating dynamically proxy models
I want to create dynamically proxy models with this code: from django.db import models class BaseId(models.Model): def __str__(self): return self.nom class Meta: app_label = 'sae' abstract = True NOMENCL_LIST = ['CAT', 'CATR', 'CCR', 'ESPIC', 'GRP', 'MFT', 'NAT', 'PERSO', 'STJ', 'STJR'] class Nomenclature(BaseId): code = models.CharField(max_length=20, unique=True) nom = models.CharField( max_length=250) class Valeurs_nomenclature(BaseId): nomenclature = models.ForeignKey(Nomenclature, on_delete=models.PROTECT, related_name='valeurs') code = models.CharField(max_length=20) nom = models.CharField(max_length=250) class NomenclatureManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(nomenclature__code=qs.model.__name__) for nomencl in NOMENCL_LIST: if nomencl not in globals(): meta = type('Meta', (BaseId.Meta,), { 'proxy':True }) model = type(nomencl, (Valeurs_nomenclature,), # this line causes the error { 'Meta':meta, 'objects':NomenclatureManager }) globals()[nomencl] = model This code raises a KeyError the before last line: module = attrs.pop("__module__") KeyError: '__module__' When I set explicitly "module", it works : model = type(nomencl, (Valeurs_nomenclature,), { 'Meta':meta, 'objects':NomenclatureManager, '__module__':'sae.models.id_models' }) My question: in what circumstance 'module' is set implicitly or not ? -
Django Static files Page not found (404)
I am trying to create a website using Django and in my models.py I am using Django's ImageField(upload_to=''), but these files are not being uploaded to their location and I don't know why. That file is empty. So I am getting this error Page not found (404) at http://127.0.0.1:8000/class/instructor_pics/2_c4iU33j.jpg. The other static files are fine like carousel banner and everything but these files are not being uploaded. What should I change to make this work? My models.py: class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) enrolled_students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='enrolled_students', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 285 or img.width > 201: output_size = (285, 201) img.thumbnail(output_size) img.save(self.image.path) img2 = Image.open(self.instructor_image.path) if img2.height > 40 or img2.width > 40: output_size = (40, 40) img2.thumbnail(output_size) img2.save(self.instructor_image.path) My settings.py: """ Django settings for Abrar_Class project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # … -
Django make the object create only once per day
Here is my Django model: class mymodel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) How can I make the object created only once per day? I know it's possible to do with unique_for_date but cannot understand how https://docs.djangoproject.com/en/4.1/ref/models/fields/#unique-for-date Also, I want to show an error if the user wanted to create more than once per day. -
WOPI issue in view and edit mode
I have implemented the wopi in my application, uploaded the new version of document while in the view mode then changed into edit mode new version of the document is not updated old version is displayed and different session is created for the same user -
Why user.has_perm print always True?
A user is assigned to a student group and from the group remove delete_permission, but the below code returns true. student_group = Group.objects.get(name='student') content_type = ContentType.objects.get_for_model(Department) department_permission = Permission.objects.filter(content_type=content_type) user = User.objects.get(email='test@gmail.com') student_group.user_set.add(user) for perm in department_permission: if perm.codename == "delete_department": student_group.permissions.remove(perm) print(user.has_perm("quiz.delete_department"), "Quiz Permission after") -
Change API_BASEURL
I'm doing a project on Django REST Framework. I need the project to run not on standard "http://127.0.0.1:8000 /", but on the server "http://localhost:8080 ". Please tell me where it needs to be corrected in my project files? -
django model AttributeError: 'str' object has no attribute 'clone'
two off my models in Django are getting the AttributeError: 'str' object has no attribute 'clone' while a run makemigration command class Statuses(models.TextChoices): publish = _('publish') archive = _('archive') draft = _('draft') category = models.ForeignKey(BlogCategory, on_delete=models.DO_NOTHING, verbose_name=_("blog category")) title = models.CharField(max_length=64, null=False, blank=False, verbose_name=_("blog title")) slug = models.SlugField(null=False, blank=False, allow_unicode=True, verbose_name=_("blog slug")) intro = models.TextField(null=False, blank=False, verbose_name=_("blog introduction")) body = models.TextField(null=False, blank=False, verbose_name=_("blog body")) created = models.TimeField(auto_now_add=True, verbose_name=_("blog creation time")) pubdate = models.TimeField(auto_now=True, verbose_name=_("blog publish time")) status = models.CharField(max_length=12, choices=Statuses.choices, verbose_name=_("blog publish status")) class Meta: ordering = ['-pubdate'] indexes = ['title'] verbose_name = _('blog') verbose_name_plural = _('blogs') and class Products(models.Model): productName = models.CharField(max_length=32, blank=False, null=False, verbose_name=_("product name")) productImage = models.ImageField(upload_to='medias/images/products/') category = models.ForeignKey(ProductCategories, on_delete=models.DO_NOTHING, verbose_name=_("product category")) weights = models.ForeignKey(Weights, on_delete=models.DO_NOTHING, verbose_name=_("product weights")) package = models.ForeignKey(Packages, on_delete=models.DO_NOTHING, verbose_name=_("product package")) class Meta: ordering = ['productName'] indexes = ['productName'] verbose_name = _('product') verbose_name_plural = _('products') and didn't find any good answer for the problem -
file.truncate doesn't clear file content
I'm using python and django for an application, and I have to stock informations in a text file. So I've done this : def write_in_file(data): stock_file = open(os.path.join(sys.path[0], "static/imported_data.txt"), "w") stock_file.truncate() stock_file.write(data) stock_file.close() It's working like I want and my file contains 'data'. But when I refresh the page, the content of the file is not cleared, and 'data' is rewrited at the end of the file. And when I print something to debug, I see that the function is called every time I refresh the page. The only time my file is properly cleared is when I modify the 'write_in_file' function. Does anyone know from where this might come from ? -
How to get pk from url in django rest framework?
I have 2 apps Ticket and Comment, with url: http://127.0.0.1:8000/api/tickets/<int:pk>/comments/<int:pk>/. comment.views class CommentAPIList(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (IsAuthenticatedOrReadOnly,) pagination_class = CommentAPIListPagination I want to get first int:pk in my url for filter my queryset, like: queryset = Comment.objects.filter(ticket=MY_GOAL_PK) comment.models class Comment(models.Model): text = models.TextField() ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.text ticket.models class Ticket(models.Model): title = models.CharField(max_length=150) text = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.title I don't know what other information I can give, but I can give it at your request. May be you have another solution for filtering my Comment.objects. Filtering should provide comments related only to this Ticket -
Expression expected.javascript error. The error is in the if statement and there are some errors in the terminal. Need assistance
//This is the JS Code for the Checkout page in a HTML File <script> document.getElementById('cart').innerHTML = sum; $('#itemsJson').val(JSON.stringify(cart)); //If order is placed then confirm the order with an ID {% if thank %} alert('Thanks for ordering with us. Your order id is {{id}}. Use it to track your order using our order tracker') localStorage.clear(); document.location = "/shop"; {% endif %} </script> -
Django - Can't send Whatsapp message in production mode
I am developing an app that should send msg by WhatsApp using pywhatkit. Running from Django Development Server works fine, but from Xampp it doesn't, I even tried opening whatsapp from the url directly in the project and it doesn't work either. Python 3.10.6 Django 3.2.0 def send_whatsapp(telefono, mensaje): try: pywhatkit.sendwhatmsg_instantly(telefono, mensaje, tab_close=True) print("Mensaje enviado") except Exception: print("Error") -
Order queryset based on condition from fields in different table
I have some resources that a user can subscribe to, for added advantages. My challenge is in sorting them, where the resources with subscriptions come first and the rest follow. Initially, the resources were stored like this. from django.db import models from django.utils import timezone class Entity(models.Model): has_subscription = models.BooleanField() created_at = models.DateTimeField(default=timezone.now) # other fields and I would sort them like this, Entity.objects.all()order_by("-has_subscription", "-created_at") which worked. I decided to move to a different way of storing it that would favor a time bound subscription. I came up with this. from django.db import models from django.utils import timezone class Entity(models.Model): created_at = models.DateTimeField(default=timezone.now) @property def has_active_subscription(self): if ( self.entity_subscriptions.filter( start_date__lte=timezone.now(), end_date__gte=timezone.now() ).count() > 0 ): return True return False class Subscriptions(model.Model): entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="entity_subscriptions", related_query_name="entity_subscription", ) start_date = models.DateTimeField() end_date = models.DateTimeField() How can I sort the queryset in such a manner that the resources with subscriptions come first. -
Django form - the same field multiple times
how can I process a form with a field: order = ModelChoiceField( required=False, queryset=OrderOd.objects.filter(Q(status='DN') | Q(status='DI')), widget=Select( attrs={ "class": "form-select form-select-md form-select-solid", "data-control": "select2", "data-multiple": "true", "multiple": "multiple", "data-placeholder": _("Vyberte objednávku ..."), "id": 'order' } ) ) In front-end, I can select multiple orders (looks like pills/tags) and in the request sent to the server it looks like this: movement: f2b7c234-fbdb-4059-bcb6-8ada46cef72c account: dbabefb7-f053-4edf-a2e3-787bf6bfc371 date: 2022-09-12 order: eb2fc726-3e97-4af2-a8b2-08f20771cfef order: 8398925b-fca6-4b25-8c48-e12940a5b5c3 order: bfa35391-5cf8-4ed8-8c44-a797da875cb4 order: 07be93ac-20b3-459c-8038-c8b023db6d66 When I inspect self.data, I got 'order': ['eb2fc726-3e97-4af2-a8b2-08f20771cfef', '8398925b-fca6-4b25-8c48-e12940a5b5c3', 'bfa35391-5cf8-4ed8-8c44-a797da875cb4', '07be93ac-20b3-459c-8038-c8b023db6d66'], but when I check the output of logger.info(self.data['order']), it gives me only the first UUID. [INFO] form.py 123: 07be93ac-20b3-459c-8038-c8b023db6d66 What I need is to access all UUIDs in the array (order) and process them instance by instance. Any idea, how to do it? Thanks -
Django: How to filter obejects in django?
I simply want to filter the most popular videos based on the views. So in the Model there is a field called views = models.IntegerField(default=0). now videos can have views like 10 42, 65, 2. So what i want to do is simply NOT filter by newest to oldest by highest number of views to the lowest number. What is the best way to achieve this? def Videos: videos = Video.objects.filter(user=channel.user, visibility="public") models.py class Video(models.Model): ... views = models.PositiveIntegerField(default=0) -
Xcode Preview not showing
I was following a YouTube tutorial about how to connect my django backend to Swift and when I finished following along, I just get a blank grey area where the phone preview should be. Anyone know why this would happen? Here's my Model file and my View. import Foundation struct Account: Codable, Hashable { var email: String var username: String var first_name: String var last_name: String var is_venue: Bool var date_joined: Date var last_login: Date var is_active: Bool var is_admin: Bool var is_superuser: Bool } And View import SwiftUI struct AccountView: View { @State var accounts = [Account]() var body: some View { ForEach(accounts, id: \.self) {item in HStack { Text(item.first_name) } }.onAppear(perform: loadAccount) } func loadAccount() { guard let url = URL(string: "http://127.0.0.1:8000/api/account/") // URL is the endpoint of API else { print("API is down") return } var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Basic amZsb3JlbmNlMEBnbWFpbC5jb206QmEka2V0YmExMUZsMEppbW15ITEh", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { if let response = try? JSONDecoder().decode([Account].self, from: data) { DispatchQueue.main.async { self.accounts = response } return } } }.resume() } } struct AccountView_Previews: PreviewProvider { static var previews: some View { AccountView() } } -
How to create a charfield with suggestions in django forms?
I want to create a charfield input in a django form that has suggestions. Essentially I want a choice field that also allows you to write your own value if needed. In other words a hybrid between a charfield and choice field input. Any suggestions on how to achieve this ? class PDFClassificationForm(forms.ModelForm): nature = forms.CharField(required=False) class Meta: model = Documents fields = [, 'nature',] labels = {,, 'nature':'Nature/Concerne:', } widgets = { 'dateenvoi' : DatePickerInput(), } def __init__(self, uuid_pdf, *args, **kwargs): super(PDFClassificationForm, self).__init__(*args, **kwargs) if Documents.objects.get(uuid=uuid_pdf).id_emetteur: nature_choices= Archivagerecurrencelibelle.objects.filter(Q(id_emetteur=Documents.objects.get(uuid=uuid_pdf).id_emetteur) & Q(source="Nature")).values_list('concerne','concerne') self.fields['nature'].choices = nature_choices -
Python requests
Can we consume an API, for example use the POST method to retrieve products. Note that we pass the security key in the body or data. it's possible ?? def api(request): url = 'https://datausa.io/api/data?product' x = requests.post(url,data={'securityKey':'valueKey') contenu=x.text return HttpResponse(contenu) -
how to use the ajax in django and how to avoid this kind of errors?
I am trying to use the ajax in my django application, but its not working. I cannot find that my codes are working or not. python or django did not show any error, but javascript showing some kind of error. I will provide my code and its error here, if my code is wrong, please give me the correct code. html form <form> <input type = "text" name = "user" id = "user"><br> <span id = "mess"></span><br> </form><br> ajax in html {% block javascript %} <script> $(document).ready(function() { $('#user').keyup(function() { let a = $('#user').val(); $.ajax({ url: '{% url "username" %}', type: "POST", data: {a: a}, // on success success: function (response) { if (response == true) { $('#mess').html("username is not available"); alert(response); } else { $('#mess').html("username is available"); alert(response); } } }); }); }); </script> {% endblock javascript %} urls.py path path('username', views.username, name = 'username'), views.py function def username(request): if request.is_ajax(): user = request.POST['a'] response = signup.objects.filter(user = user) # return JsonResponse(response) return HttpResponse(response) error username?a=enteredword:1 Request unavailable in the network panel, try reloading the inspected page Failed to load resource: the server responded with a status of 500 (Internal Server Error) Warning DevTools failed to load source map: … -
How to display the latest modified record first in python
How to display the all records but latest modified one needs to be displayed in first how we can do in python Here is my views.py def getHoto(request): Userdata=hototable.objects.filter(status=open) If request.method=='GET' Ser=addhotoSerializer(userdata,many=True) return jsonResponce (list(Ser.data)[::-1],safe=False) -
How to run custom django-admin commands as a cron job in docker?
I have a django-app sample. In this app I have created a file test.py and wrote my custom commands in it as mentioned in the django official documentation sample/ __init__.py models.py management/ __init__.py commands/ __init__.py test.py views.py test.py: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): # Sample content print("Hello World") I had run the command python manage.py test and it is working. What I need is that I want to run this command as a cron job in docker. I had tried this, created a cron file hello-cron. hello-cron: * * * * * root python /home/manage.py test >> /home/cron.log 2>&1 # Empty line Dockerfile: FROM python:3.10.6 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /home COPY requirements.txt /home/ RUN pip install -r requirements.txt COPY . /home/ RUN apt-get update && apt-get -y install cron COPY hello-cron /home/hello-cron RUN chmod 0644 /home/hello-cron RUN chmod 0744 /home/sample/management/commands/test.py RUN crontab /home/hello-cron RUN touch /home/cron.log CMD cron && tail -f /home/cron.log docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: restart: always build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/home ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - … -
Django Model with Oracle Database returns Error: ORA-00904 invalid identifier
i try to connect two database tables with a foreign key and i get the error ORA-00904: "A"."A_NR_ID": invalid identifier for the model: class A(models.Model): id = models.IntegerField(primary_key=True) a_nr = models.ForeignKey(B, models.DO_NOTHING) --> #anr = models.ForeignKey(B, models.DO_NOTHING, db_column="a_nr") f_b = models.CharField(max_length=1) ... class B(models.Model): id = models.IntegerField(primary_key=True) ... If i replace a_nr with the comment-line anr it works. And i have no idea why, since the name only uses single underscore. Also the column f_b seems to work perfectly fine. If i then run "makemigrations" it trys to delete the column a_nr and create anr, which also makes no sense to me, since i thought db_column="a_nr" would keep the actuall name in the oracle database the same. The second error is: ORA-00904: "D"."BEZEICHNUNG_ID": invalid identifier for the model: class C(models.Model): id = models.IntegerField(primary_key=True) bezeichnung = models.CharField() class D(models.Model): id = models.IntegerField(primary_key=True) bezeichnung = models.ForeignKey(C, models.DO_NOTHING) ... And here i can't figure out what's wrong. -
Django,based on model consecutive field value difference update new field value in same row
I'm trying to set stay column field value in TestLocation model table as stay or on_move by calculating difference between lat and longs using for loop to iterate between rows of model table and if condition where to set value of stay field as stay or on_move which depends on difference as shown in views.py. below is my model.py: class TestLocation(models.Model): LOCATOR_YES_NO_CHOICES = ((None, ""), (True, "Yes"), (False, "No")) longitude = models.FloatField() latitude = models.FloatField() processed = models.BooleanField( choices=LOCATOR_YES_NO_CHOICES, max_length=3, blank=True, null=True, default=None, ) stay=models.CharField(max_length=100,null=True) duration=models.FloatField(null=True) and views.py funtion to set value of stay field in above model: def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) # list_lat1 = [] # list_lat2 = [] # list_long1 = [] # list_long2 = [] for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude # list_lat1.append(lat1) lat2 = rowpairs[1].latitude # list_lat2.append(lat2) long1 = rowpairs[0].longitude # list_long1.append(long1) long2 = rowpairs[1].longitude # list_long2.append(long2) lat = abs(lat2 - lat1) long = abs(long2 - long1) a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) for rowpair in rowpairs: row_id = rowpair.id po … -
the "Children" of nested files
I'm doing a project (on Django REST Framework) dedicated to file storage. The project structure assumes that folders can be nested in other folders. And files can be nested in folders. I have prescribed the logic of the file link to the folder in which it is uploaded. However, I need that when I request the service via the API, I am given another field that includes the data of all subfolders and files (the "children") field. My model.py file: FILE='FILE' FOLDER='FOLDER' TYPE_CHOICES = [(FILE,"FILE"),(FOLDER,"FOLDER")] class Folder(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=255, choices=TYPE_CHOICES, editable=False, default='FOLDER') name = models.CharField(max_length=255) # size = models.IntegerField(blank=True, null=True, default = 0) date = models.DateField(auto_now=True) class File(models.Model): type = models.CharField(max_length=255, choices=TYPE_CHOICES, editable=False, default='FILE') id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) file = models.FileField(null=True, max_length=255) date = models.DateTimeField(auto_now =True) # user = models.ForeignKey(User, on_delete=models.CASCADE) parentId = models.ForeignKey(Folder, on_delete=models.CASCADE) def __str__(self): return str(self.file.name)