Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slicing a for loop in Django
I'm trying to make this for loop iterating through the blog posts that have been published today and I just want the user to have an overview of the LAST three posts. It is turning out to be very difficult :( {% for post in object_list %} {% if date == post.postday %} <b>{{ post.name }} {{ post.surname }}</b> </br> {% endif %} {% endfor %} I have tried to slice the iteration as follow: {% for post in DeathDay_list|slice:":3" %} {% if date == post.postday %} <b>{{ post.name }} {{ post.surname }}</b> </br> {% endif %} {% endfor %} However, the problem is that it get the full list than it checks if the day matches with today and then it slices the first three element which are not from today and it does not show anything on the views. Please :) -
Disable related object links in django admin delete confirmation page
I'm looking for a way to remove the links to related objects on the delete confirmation page of the django admin. I can see that I can override the delete_selected_confirmation.html, I don't see how I can change the content of the deletable_objects in the template. https://github.com/django/django/blob/stable/2.2.x/django/contrib/admin/templates/admin/delete_selected_confirmation.html This appears the be the related code that generates the deletable_objects rendered in the template: https://github.com/django/django/blob/bb64b99b78a579cb2f6178011a4cf9366e634438/django/contrib/admin/utils.py#L104 I can just remove the objects section in the template, but I'd like to display the names (__str__) if possible. Is there an easy way to override/replace the section of code that generates the deleteable_objects used in the delete_selected_confirmation.html template? -
Error when migrating to heroku postgres db: multiple default values specified for column "id"
I am currently deploying my django application to Heroku and I keep getting an error when migrating my database table to the Postgresql database. I get the following error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "planning_location" I already tried the solution specified in this post: django.db.utils.ProgrammingError: multiple default values specified for column "_id" of table "Asset_movie". However, that didn't solve it unfortunately.. This is the structure of the planning_location model: class Location(models.Model): name = models.CharField(primary_key=True,max_length=200, unique=True) locationid = models.UUIDField(default=uuid.uuid4, editable=False) slug = models.SlugField(max_length=200, editable=False) description = models.TextField(blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): # create slug from name when saving for the first time if not self.slug: self.slug = slugify(self.name) super(Location, self).save(*args, **kwargs) The name is the primary key, which is essential for another part of the application. Since I do not have another id field I created an UUID field which serves kind of as a second id, without being a primary key. Does anybody know why this does not work, and what can be changed to make it succeed? -
How to solve circular import in django model?
I have created one apps in django: lecture The code in lecture.models class SchoolDepartment(models.Model): id = models.AutoField(primary_key=True) class Professor(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey(SchoolDepartment) class Lecture(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey(SchoolDepartment) When i run, this code raise error. ImportError: cannot import name 'SchoolDepartment' from partially initialized module 'lecture.models' (most likely due to a circular import) I have got to know, the error is because of the circular import. So i change this code like this. class SchoolDepartment(models.Model): id = models.AutoField(primary_key=True) class Professor(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey('lecture.SchoolDepartment') class Lecture(models.Model): id = models.AutoField(primary_key=True) school_department = models.ForeignKey('lecture.SchoolDepartment') But still raise error ImportError: cannot import name 'SchoolDepartment' from partially initialized module 'lecture.models' (most likely due to a circular import) How can I fix it? -
How to add the fake data to mysql using django-seed
i have one project "mainreview" and inside this project i have one app called "products" please below the models image i made in products; [enter image description here][1] and i made user_seed to make fake data into mysql using django-seed below is my directory tree [enter image description here][2] last image is the problem i can not solve . i made the "seed_users " to make fake data into mysql db but it happened error when i write "python manage py seed_user --number 10" that error is [enter image description here][3] [1]: https://i.stack.imgur.com/t90j9.png [2]: https://i.stack.imgur.com/Uhpqh.png [3]: https://i.stack.imgur.com/XYPPc.png i wonder why it error happend.. if i do not use the method to use django-seed let me know how to write it. -
what is diffrences between CASCADE and CASCADE()
In django models for deleting an object in model we use on_delete=models.CASCADE but why we do not use models.CASCADE() I mean what is differences between CASCADE AND CASCADE() and why we do not use CASCADE() -
Keep recieving server error after hosting on heroku
i have been trying to host my django application on heroku, i've made several attempts and they all proved null, initially i was encountering failure in serving my staticfiles, then i disable staticfiles and was able to deploy the site, but then when i try to visit my newly deployed site i keep encountering Server Error, i have followed the steps in heroku documention, for deploying django sites and even installed django-heroku, but still get the same error, can i get a suggestions please??? -
Django Rest Framework Extra kwargs fields for Password and Unique Email
I tried creating serializers for my Model and tried serializing Model I want password field be typed in **** format when I try entering password and Email to be unique from Extra kwargs fields how can I do that? here is my serializers I tried. User = get_user_model() class AddBusCompanyUserSerializer(serializers.ModelSerializer): position = serializers.PrimaryKeyRelatedField(queryset=StaffPosition.objects.all()) class Meta: model = User fields = ( 'phone_number', 'password', 'position', 'email', ) extra_kwargs = {'password': {'write_only': True},'email':?} } what validator should I try making email being unique and password field being typed in **** format? -
POST register credentials to Django from Unity with C#
I have a Unity app with a custom made registration form. I want users to succesullyregister to a Django Backend at a url http://example/register/.com. I have a c# script (see below) that posts the information to the url. the script: using System.Collections; using System.Text; using System.Text.RegularExpressions; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class DjangoRegisterPost : MonoBehaviour { public TMP_Text resultText; public Button btnClick; public TMP_InputField inputUser; public TMP_InputField inputName; public TMP_InputField inputSur; public TMP_InputField inputEmail; public TMP_InputField inputPassword; public TMP_InputField inputPasswordConf; public string postURL = "http://example/register/.com"; private void Awake() { resultText.text = "Getting results from: " + postURL +"\n"; // simpleResultText.text = "Getting results from: " + localSimpleURL +"\n"; } private void Start() { //attach button event btnClick.onClick.AddListener(GetInputOnClick); } public void GetInputOnClick() { Debug.Log("Username = "+ inputUser.text); Debug.Log("Name = "+ inputName.text); Debug.Log("Surname = "+ inputSur.text); Debug.Log("email = "+ inputEmail.text); Debug.Log("Password = "+ inputPassword.text); Debug.Log("ConfPassword = "+ inputPasswordConf.text); resultText.text += "Loading results .... \n"; StartCoroutine(GetWebResult(resultText)); } public IEnumerator GetWebResult(TMP_Text results) { WWWForm form = new WWWForm(); form.AddField("username", inputUser.text); form.AddField("name", inputName.text); form.AddField("surname", inputSur.text); form.AddField("email", inputEmail.text); form.AddField("password", inputPassword.text); form.AddField("password confirmation", inputPasswordConf.text); //doLogin.SetRequestHeader ("referer", "https://dividedsky.herokuapp.com/accounts/login/"); //doLogin.SetRequestHeader ("cookie", "csrftoken=" + csrfCookie); //doLogin.SetRequestHeader ("X-CSRFToken", csrfCookie); string searchURL = postURL; //Unity will retain Cookies … -
syntax error at or near "WITH ORDINALITY" error when trying to migrate postgreSQL
I was using MySQL on my computer and when I wanted to host my app on a server I could not do it because the mysqlclient package needs root priviliges!! so I had to use something else so I used the postgreSQL database and It connected and ran the makemigrations but when I tried to run the migrate it gave me the 'syntax error on or at "WITH ORDINALITY"'. Does someone know what is causing the problem?? every time I try to run migrate it give me this error!! -
django admin User and Group models fields in a model
i have a model Transaction and i havent add a group field, However i want to make kind of system that uses Group, User models . i want each group to have users . and each group can access its own Transaction model in the admin pannel. eg: users from group1 can only see Transactions made by users in same group. and so on for other groups.... models.py class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.Group = request.user.groups.all() print(obj.Group) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(group__name__in=request.user.groups.all()) i know i have to add User or Group field to Transaction, or maybe not.. since i dont want users to choose the group each time they make a Transaction. So what is the good approach of doing it? i need to modify save_mode and get_queryset but i dont know how -
How to run django on a server where php is already running
I have a new ec2 instance, where I installed Django and made the website running. But I want to upload the website on a server where rest of webs are PHP. I followed the same steps, but I am unable to run Django app. There is no error on console. So could any one guide me the steps I need to follow? -
can we upload images directly to database and can fetch that also without creating static_media and media_root, just sweet and simple
models.py of app to create models for database. name = models.CharField(max_length=200) img = models.ImageField(null=True,blank=True) desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default=False) settings.py where i am defining root of the media, i dont want this, i just want to upload image directly to database and fetch whenever i need. dont want to create any folder to keep those. # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assests') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') main urls.py , i dont know what i am doing, but i also dont want to do this, is there any shortcut way , also i dont want to store images in local folder i want to upload them direct to database and fetch when i need. """bhushan URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. … -
Django: update model’s field before save
I want to automatically change the status field of my project model once the system detects that all associated tasks are finished my model class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) resume = HTMLField() pub_date = models.DateTimeField(auto_now_add = True) category = models.ManyToManyField(Category) state = models.BooleanField(blank=True, null = True, default = False) weighted = models.IntegerField(blank=True, null = True) def change_state(self, *args, **kwargs): if self.todo_set.all().count() == 0: return percentage_notes = round(self.todo_set.filter(state = True).count() * 100 / self.todo_set.all().count()) if percentage_notes == 100: self.update(state = True) super().save(*args, **kwargs) return class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) I create the change_state definition so that it determines if all the tasks of the project are finished, but does not save the changes in the state fields in my project model -
Django related object in save_model
I want a simple created_by field for an entity in Django 3.0: Snippet from Model: class Event(models.Model): created_by = models.ForeignKey(CustomUser, verbose_name=_('Created by'), on_delete=models.CASCADE, null=False, blank=False, related_name='created_events', editable=False) (Migrations applied.) class EventAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if obj is not None and obj.created_by is None: obj.created_by = request.user super().save_model(request, obj, form, change) On saving from the adminpage I get this error: RelatedObjectDoesNotExist at /......./Events/event/add/ Event has no created_by. What am I doing wrong? -
AES encryption and decryption of file path with django
I am trying to encrypt the file path when users upload images to the database and decrypt the images when displaying it on the web page. Both encryption/decryption require the usage of AES algorithm. Do I need to install some sort of library to do this in Django and how do I go around doing it in my code? I'm assuming I have to add the encryption parameter in obj = ImagefieldModel.objects.create() and decryption parameter in allimages = ImagefieldModel.objects.all(). models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" views.py def imgupload(request): context = {} if request.method == "POST": form = ImagefieldForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data.get("name") img = form.cleaned_data.get("image_field") obj = ImagefieldModel.objects.create( title = name, img = img ) obj.save() print(obj) messages.info(request, f"image uploaded successfully!") return redirect("main:basehome") else: form = ImagefieldForm() context['form'] = form return render( request, "main/image_upload.html", context) def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/view_and_download.html',{'images': allimages}) image_upload.html {% extends "main/header.html" %} {% block content %} <head> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </body> {% endblock %} view_and_download.html {% extends "main/header.html" %} {% load static %} {% block content %} … -
Comparison of objects in django
Models class Weapon_Class(models.Model): title = models.CharField(max_length = 50) description = models.TextField() def __str__(self): return self.title class Gun(models.Model): weapon_type = models.ForeignKey(Weapon_Class, on_delete = models.CASCADE) name = models.CharField(max_length = 50) magazine_size = models.IntegerField(default = 0) damage = models.IntegerField(default = 0) fire_rate = models.IntegerField(default = 0) description = models.TextField() def __str__(self): return self.name Views class Weapon_class_view(ListView): model = Weapon_Class template_name = 'weapon_class.html' # print(Weapon_Class.objects.all()[1].headline) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['items'] = Weapon_Class.objects.all().count() context['weapons'] = list(Weapon_Class.objects.all()) context['arm'] = (Gun.objects.all()) return context Template {% for weapon in weapons %} <div class = "wepbox" > <a href="#"><div class = "boxy">{{ weapon.title }}</div></a> </div> {% for g in arm %} {% if g.weapon_type == weapon.title %} <h1 style="color: yellowgreen;">{{g.name}}</h1> {% endif %} {% endfor %} {% endfor %} It displays nothing on the browser but it should display the name of different guns like type 25 which is the assault rifle or MW11 which is the pistol -
Populate dropdown in template from model choices using Django Rest Framework
I have the model, serializer, viewset and html as follows: GENDER = ( ('MALE', 'Male'), ('FEMALE', 'Female'), ('OTHERS', 'Others'), ) class Client(BaseModel): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256, default="", blank=True, null=True) designation = models.CharField(max_length=256, default="", blank=True, null=True) gender = models.CharField(max_length=20, choices=GENDER, null=True, blank=True) class ClientSerializer(QueryFieldsMixin, DynamicFieldsModelSerializer): name = serializers.SerializerMethodField() def get_name(self, obj): return getattr(obj, "first_name", "") + " " + getattr(obj, "last_name", "") class Meta: model = Client fields = '__all__' @method_decorator(login_required, name='dispatch') class ClientViewSet(viewsets.ModelViewSet): model = Client queryset = model.objects.all() serializer_class = ClientSerializer @action(detail=True, methods=['post','get'], renderer_classes=[renderers.TemplateHTMLRenderer]) def update_client(self, request, *args, **kwargs): object = self.get_object() context = {"operation": "Update", "object_id": object.id, "events": Event.GetEventsForObject(object)} template_name = 'contact-client.html' response = Response(context, template_name=template_name) <div class="row"> <div class="columns medium-5 medium-text-left"> <div class="select2-full select-2-full--sm input-rounded"> <label for = "gender" style="text-align: left;" >Gender</label> <select id="gender" class="js-select2 input-height-sm element-contact" name="gender" validated="false"></select> <option></option> </div> <div id="gender_error" style="display:none"> <p class="help-text"> <span class="form-action-icon error-icon"></span>Please select gender.</p> </div> </div> <div class="columns medium-5 medium-text-left"> </div> </div> When I instantiate the ClientSerializer in shell like this ClientSerializer() then that gender field is shown along with its choices. But I am not able to show it in the template. All the other fields are being passed correctly. How can I populate the dropdown with … -
TypeError when using AWS S3 Bucket with Django
I'm brand new to Django and AWS S3 and seem to have hit a wall. This is all on localhost at the moment. I'm trying to add a new product through my own admin app for a Art Gallery website i'm working on, all worked fine originally when adding a product, but since using AWS S3 i receive the following TypeError: The error states that it's expecting "...a string or bytes-like object." and refers to the following lines of code in both my mixins.py and my staff views.py mixins.py: from django.shortcuts import redirect class StaffUserMixin(object): def dispatch(self, request, *args, **kwargs): if not request.user.is_staff: return redirect("home") return super(StaffUserMixin, self).dispatch(request, *args, **kwargs) views.py: class ProductCreateView(LoginRequiredMixin, StaffUserMixin, generic.CreateView): template_name = 'staff/product_create.html' form_class = ProductForm def get_success_url(self): return reverse("staff:product-list") def form_valid(self, form): form.save() return super(ProductCreateView, self).form_valid(form) As I stated at the start i'm very new to both Django and AWS S3, so if this is just a schoolboy error, please forgive me but any help would be fantastic. And if any additional info is needed i'll be happy to provide. Thanks! -
Difference between TruncDay and Cast, extracting date from datetime
What are the differences between these two methods(extracting date from datetime): #1 User.objects.annotate(date=TruncDay('date_joined')).values('username','date') #2 User.objects.annotate(date=Cast('date_joined', output_field=DateField())).values('username','date') Resulted Query: #1 SELECT "users_user"."username", DATE_TRUNC('day', "users_user"."date_joined" AT TIME ZONE 'UTC') AS "date" FROM "users_user" #2 SELECT "users_user"."username", ("users_user"."date_joined")::date AS "date" FROM "users_user" I noticed that TruncDay also takes consider the timezone information while Cast not. Are there any difference between the use of these two methods for extracting date out of datetime both in sql level and django level, which one is prefered usually? -
Connecting Django docker to remote database
I have a Django application running on docker connected to a database in another container on the same host. This seams to work fine, but when I try to change the connection to a database on another server, it fails to connect. Not only that, but when I try to connect to the Django application in the browser(like admin or api) I get no response, and see no activity in the output log. The application runs fine with the remote database if I run it outside the container, and the database is set to accept all IPs for the user I am trying to connect with. Any Ideas as to why I am not getting a connection? Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN apk add mariadb-dev python3-dev postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app_django COPY ./app_django /app_django WORKDIR /app_django COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] docker-compose.yml version: '3.7' services: db: build: mysql/ environment: MYSQL_ROOT_PASSWORD: … -
Django Rest Framework: Unable to set custom header
I have two custom header keys, api-key and api-secret. On passing it still gives me the error for not having required headers. Below is the code: from rest_framework.test import APITestCase from .models import App, Wallet from .stellar import * # Create your tests here. class WalletTestCase(APITestCase): app_id = 0 app = None def test_create_wallet(self): response = self.client.post( '/wallets/', data={'app_id': self.app_id, 'customer_id': 'A-001'}, # headers={'HTTP_API_KEY': 'test-api', 'HTTP_api-secret': 'test-api-password'} ) self.client.credentials(HTTP_X_API_KEY='test-api', HTTP_X_API_SECRET='test-api-password') data = json.loads(response.content) print(data) self.assertEqual(data['status'], 'OK') -
Is it possible that define pdf attach file in django framework?
We use Title = models.CharField(max_length = 60) For char fields. Is it possible simply use PdfField or FileField in model.py for uploading pdf files? For example: Title = models.CharField(max_length = 60) Document = models.FileField(upload_to='documents/') I do not want to use form and... Extra codes -
django OperationalError when trying to migrate with docker
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known That is the error I get when running docker-compose exec web python manage.py migrate my docker-compose.yml contains: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 This Is what I put for DATABASE in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } I have tried running docker-compose up -d --build and then docker-compose exec web python manage.py migrate But that doesn't work. -
Do some task before Django project stops
How can I do some tasks like clear Redis cache objects before my Django project stops? Is there any way to find this moment inside a Django project so that there is no need for extra config and commands in the server such as Nginx server?