Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django initialization stuck at import netrc
My django app starts very slowly. I ran python -v manage.py check and it stucks at line import 'netrc' # <_frozen_importlib_external.SourceFileLoader object at 0x7efff40f3d30> I found this related question : Django "Performing System Checks" is running very slow Here it says he removed the elastic beanstalk urls from ALLOWED_HOSTS and it fixed. I did that too but my app still stucks at that import statement. What else can cause that? -
DRF add computed field based on requesting user
I have a model which has specific many to many fields to the user model. Now, to prevent information leaking, I do not want to return the whole related field though the rest framework. But, I want to create some kind of computed field, such that it return True if the requesting user is in the related field, and False otherwise. Is there a way to make this work? For example, as it stands now, the rest framework will list the users for "user_like" and "user_bookmark", which I dont want to happen, hence I want to exclude them from the serialized. But I want to have a field, say, named is_liked, which will be true if request.user is in user_like, and false otherwise. My current setup: model class Post(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='dream_photos') description = models.TextField(max_length=500) date_added = models.DateTimeField(auto_now_add=True) user_like = models.ManyToManyField(User, related_name='likes', blank=True) user_bookmark = models.ManyToManyField( User, related_name='bookmarks', blank=True) total_likes = models.PositiveIntegerField(db_index=True, default=0) tags = TaggableManager() serialiser class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Dream fields = ('title','user', 'image','description','date_added', 'tags', 'total_likes' ) views class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.prefetch_related('user').all() serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=False, methods=['get'], url_path='current-profile', url_name='current-profile') def current_user_posts(self, … -
How can I get Loged in user details from different Mdels as arguments
I am trying to integrate a payment system in my Django project and I models for profile, and submitted. The issue is that I want a situation where when a user clicks on pay button the system should check whether he/she has submitted application and if so; grab the username, email, phone, amount and pass them as arguments into my process_payment view where the payment is going to be done. here is code for Profile model: class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=16, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') here is code for Scholarship model: class Submitted(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() approved = models.CharField(max_length=20, null=True) date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.application == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application}-{self.applicant}' Here is my view code: @login_required(login_url='user-login') def scholarship_detail(request, pk): data = Scholarship.objects.get(id=pk) if request.method=='POST': applicant= request.user email = 'henry@gmail.com' amount = 2 phone = 8034567 return redirect(str(process_payment(applicant,email,amount,phone))) … -
how to filter the model we use in model.ForeignKey in django
I have model in django that has some instaces in itself: class Account(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) #some instances... is_agent = models.BooleanField(default=False) agent = models.ForeignKey("self", verbose_name=('agent'), on_delete=models.SET_NULL, blank=True, null=True) i want to pass only Accounts objects that is_agent set to True in my model.ForeignKey() method. i don't want to use inheritence for some reasons. -
getting error while I run this code(django,rest_framework)
I am learning django rest_framework , But here's the problem, I get the following error. What am I doing wrong?I've done a lot of research on trying to resolve the jsondecodeerror. However, I'm not finding a solution. import requests import json URL = "http://127.0.0.1:8000/studentapi/" def get_data(id=None): data = {} if id is not None: data = {'id':id} json_data= json.dumps(data) r= requests.get(url = URL , data = json_data) data = r.json() print(data) get_data()``` error--- python myapp.py Traceback (most recent call last): File "C:\Users\P.ARYAPRAKASH\Documents\Djangovs\fun_api_view\myapp.py", line 15, in <module> get_data() File "C:\Users\P.ARYAPRAKASH\Documents\Djangovs\fun_api_view\myapp.py", line 12, in get_data data = r.json() File "C:\Users\P.ARYAPRAKASH\AppData\Roaming\Python\Python39\site-packages\requests\models.py", line 910, in json return complexjson.loads(self.text, **kwargs) File "C:\Python39\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
Django RestFramework - Test View failing with 400
right now I'm trying to create a simple test-file for a ListCreateAPIView inside my views.py: views.py: class AuthorListCreateView(ListCreateAPIView): queryset = Author.objects.all() serializer_class = AuthorSerializer serializers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' urls.py: urlpatterns = [ path('author/', AuthorListCreateView.as_view(), name='author-list'), ] models.py from django.contrib.auth import get_user_model USER = get_user_model() class BaseModel(models.Model): id = models.BigAutoField(primary_key=True, editable=False, unique=True) created_by = models.ForeignKey(USER, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True get_latest_by = 'created_at' class Author(BaseModel): class Gender(models.TextChoices): NO = 'NO', 'No gender chosen' DIVERSE = 'DI', 'Diverse' FEMALE = 'FE', 'Female' MALE = 'MA', 'Male' first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) born = models.DateField(null=False, blank=False) died = models.DateField(null=True, blank=True) passed = models.BooleanField(default=False) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.NO) slug = models.SlugField(null=False, blank=False, unique=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name='unique_name_constraint'), ] indexes = [ models.Index(fields=['last_name', 'first_name'], name='index_unique_name'), ] verbose_name = 'Author' verbose_name_plural = 'Authors' def __str__(self) -> str: return f'{self.first_name} {self.last_name}' def save(self, *args, **kwargs): self.passed = True if self.died is not None else False self.slug = slugify(f'{self.last_name}-{self.first_name}') if not self.slug else self.slug super(Author, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('author-detail', kwargs={'slug': self.slug}) def clean(self): if self.died is not None … -
Django - TypeError at /api/v1/latest-products/ FieldFile.save() got an unexpected keyword argument 'quality'
I don't know why, but every time I try to go to the API URL, I keep getting this error message, I think the problem is in one of these modules, but I don't know what to change. models.py module found in the product package from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if self.thumbnail: return 'http://127.0.0.1:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.make_thumbnail(self.image) self.save() return 'http://127.0.0.1:8000' + self.thumbnail.url else: return '' def make_thumbnail(self, image, size=(300,200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() image.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail I think the problem is found in the make_thumbail function or the get_thumbnail function? serializers.py module found in … -
Gunicorn is throwing Out of Memory with max request and max requests jitter
Gunicorn is throwing Out of Memory I have tried to add max request and max requests jitter but still getting Out of Memory. Gunicorn is being controlled by supervisor exec gunicorn myproject.wsgi:application --bind unix:/webapps/run/myproject/gunicorn.sock --max-requests 500 --max-requests-jitter 50 --workers 3 --timeout 300 --user=root --group=webapps I have tried to check the gunicorn process ID it consumes 95% of memory out of 20GB and started 18 hours ago what I am doing wrong. Any help appreciated -
Can I check my backend code on Django without a frontend?
I'm new to Django and this might be a silly question, but basically for the project I'm building currently, the UI has been developed on React Native, and I'm coding the backend on Django. I haven't integrated the frontend and backend yet. So basically, how do I check if my Django backend code is working without integration? -
MultiValueDictKeyError at /rapport
any solutions in this django problem ? im trying to display hex2 and it marked that 'data' is a multivaluedictkeyerror . but in my console the code works normally and print the result without problemes i need to figure how to solve this display probleme thank you views.py def search(request): context = {} hex1="" hex2="" if request.method == 'POST': hex2, hex1 = request.POST['data'].split("+") print(hex2,hex1) context['hex2']=hex2 return render(request,"p33/rapport.html",context) photo rapport.html <table class="table"> <tbody> <tr> {%for hex in hex2.items%} {% csrf_token %} <tr class="table-row"> <td>{{hex}}</td></tr> {%endfor%} </tr> </tbody> </table> </div> urls.py path('rapport',views.search,name="rapport"), -
How to add Product details logic like amazon in an ecommerce website using Django
I am trying to build an e-commerce website using Django but I am not able to figure out how companies like Amazon and Flipkart store product details like this. I can hardcore this thing by making each attribute in the database but I think it is not the most efficient way to do this. There gonna some other way to do the same thing so please give me some valuable suggestions -
How to check the filter object is returning any data or not django
I have a model named Rooms. Now I want to check if a specific row exists in the model or not by this line of code: checkroom = Rooms.objects.filter(building_id=building_id, room_no=room_no).first() If the row doesn't exist, then I want to print some text: How Can I check the condition? I have used if checkroom: this condition to check if it exists. but now I want to check if it doesn't exist separately. -
Django-cors-headers not working though all the configuration seems correct
I tried many ways configuring the django-cors-headers But unfortunately it is not working for me even after meeting the requirements for the package as. Django Version - 3.2.13 Python Version - 3.7/3.10 (Tried both) I have the following configuring in my settings.py INSTALLED_APPS = [ 'employee.apps.EmployeeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] And even tried setting the config to CORS_ALLOW_ALL_ORIGINS = True Even trying after all of these configurations I was not able to make it work. Please help me with this issue. -
Why is Django setting default values to all existing model attributes?
I have a model called Book. Book has the following attributes: title, release_date and condition where condition has a default value set to "new". I created some of Books in django admin site. After I created a new attribute for this model called category which it has a default value set to Non-fiction. Why is django setting category = "new" to all existing books instead of "Non-fiction". With the books that I add after the migration Django set them correctly. Why is this happening. class Book(models.Model): class ConditionType(models.TextChoices): USED = "Used" NEW = "New" class Category(models.TextChoices): ACTION_ADVENTURE = "Action and Adventure" CLASSIC = "Classic" MYSTERY = "Mystery" FANTASY = "Fantasy" HORROR = "Horror" LITERERY_FICTION = "Literary Fiction" SCIENCE_FICTION = "Science Fiction" NON_FICTION = "Non-Fiction" NO_CAT = "No category" title = models.CharField( max_length=150, null=False, ) release_date = models.DateField() condition = models.CharField( max_length=12, choices=ConditionType.choices, default=ConditionType.NEW, ) category = models.CharField( max_length=40, choices=Category.choices, default=Category.NO_CAT, ) After the first migration I added the category field btw. -
instance is not popping from validated_data
I am building a simple blog app and I am trying to save two models with one of them ForeignKey with other, so I was trying to save both records so I tried to use validated_data.pop But it showed Got AttributeError when attempting to get a value for field images on serializer BlogSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'images'. But I have checked the response by printing like :- print(validated_data) It is successfully showing { 'images': [ OrderedDict([('image_text', 'First Image'), ('blog', <Blog: First Blog>)])], 'blog_title': 'First Blog', 'owner': <User: user_1> } As you can see, It is showing images in validated_data But it is not working when I use pop models.py class Blog(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) blog_title = models.CharField(max_length=100) class Image(models.Model): blog = models.ForeignKey(Blog, related_name='blog', on_delete=models.CASCADE) image_text = models.CharField(max_length=100) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class BlogSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Blog fields = "__all__" def create(self, validated_data): images = validated_data.pop("images") return validated_data I have tried many times but it is still showing the same Any suggestions would be … -
Django get_language_info_list in template is empty
I am making a website where the user can decide to view the website in either English or Dutch. I would like to do this with a dropdown menu, and for this I have added the following: settings.py: from django.utils.translation import gettext_lazy as _ MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'snvs/locale/' ] LANGUAGES = ( ('en', _('English')), ('nl', _('Nederlands')) ) urls.py (main one) urlpatterns = i18n_patterns( path('', views.home, name='home'), path('i18n/', include('django.conf.urls.i18n')), path(_('admin') + '/', admin.site.urls, name='admin'), path(_('agenda') + '/', include('agenda.urls'), name='agenda'), path(_('winkel') + '/', include('store.urls'), name='store'), ) my base template: {% load i18n %} ... {% get_language_info_list for LANGUAGES as languages %} {% if languages|length > 1 %} <form action="{% url "set_language" %}" method="post" class="d-flex"> {% csrf_token %} <select name="language" class="form-select" onchange="this.form.submit()"> {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}> {{ language.name_local }} </option> {% endfor %} </select> </form> {% endif %} However the LANGUAGES, languages or get_language_info_list tag in the template always is an empty list, whereas it should return the LANGUAGES information as described in settings.py (documentation) … -
Django Middleware object is not callable
I'm trying to write custom middleware for catching exceptions and returning the proper HTTP Response object. But for some reason, I'm getting a "middleware object is not callable" error. I'm raising an exception in view layer like below class MyView(APIView): def post(self, request): result = some_func(request) #this func raises an exception return Response({"status": "Success", "data": result}) logs. backend_1 | INFO:django:BEGIN -> c25db666-e89c-43a5-9f28-48001e301829 - /myapp/settings/create backend_1 | {"message": "Internal Server Error: /myapp/settings/create", "exc_info": "Traceback (most recent call last):\n File \"/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py\", line 47, in inner\n response = get_response(request)\nTypeError: 'MyAppResponseMiddleware' object is not callable", "status_code": 500, "request": "<WSGIRequest: POST '/myapp/settings/create'>"} backend_1 | ERROR:django.request:Internal Server Error: /crystal/settings/create backend_1 | Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner backend_1 | response = get_response(request) backend_1 | TypeError: 'MyAppResponseMiddleware' object is not callable files #myapp/middleware.py class MyAppResponseMiddleware: def __init__(self, get_response): self.get_response = get_response def process_exception(self, request, exception): absolute_path = request.get_full_path() print(absolute_path) print(exception.__class__.name) print(exception.message) #settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", ... ... <some custom middleware> ... "myapp.middleware.MyAppResponseMiddleware", ] I've added middleware in the last so that my middleware catches the response/exception before other middleware process the response. -
How to format timzone.now() in Django in models.py?
I have a DateField in my models.py, which is set to timezone.now(). How can I change the date format that it is saved in? I appreciate that I can change it in the template easily enough, but this won't solve my particular problem. I have tried adding the below into my settings.py, but nothing has changed. USE_L1ON = True DATETIME_INPUT_FORMATS = ('d-m-Y') I would be very grateful for any help here. -
Turbolinks + Django: Page is requested multiple times when the "prevoius" button is pressed in the browser
I have finally got Turbolinks to work fine and dandy and handle all of the requests going through my application (PJAX). However, the main issue that arises is the fact that the "back/previous" button is broken. The normal page request when normally navigating through a turbolink should be as follows: Normal Network activity However, when pressing on the "previous" button all hell gets loose as follows: When clicking the previous button in the browser The page named "11" should load one time only. However, it loads multiple times for some reason. I know turbolinks is famous with the Rails framework so any answers are welcome. Also, I'm inexperienced with how caching works with Turbolinks, so if this is a cache issue please refer me on how to mitigate it. -
Form data is not transferring from views.py to html table in Django
I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API and it's working too. But I am facing an issue in transferring back the form data in the HTML table. It's not going back to the table at all. Without the fetch API form submission, the data are getting transferred back to the HTML table as it's supposed to. But I am not able to do the same after implementing fetch API in my app. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST.get['dropdown_val'] value=request.POST.get['val'] print(options_value,value) context={"options_value":options_value, "value" : value} return render(request, 'index.html',context) **index.html" <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" … -
how to pass file from local storage to html - django
so i want get my file from local storage to show in html using django. but i don't know how to get it. the file is audio mp3. i was using form NOT MODALS. i need reference of example code. if you need my code form.py here's : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) i was try using formset, but i don't know how to use it. here's my views.py code : def song(request): songmp3 = formset_factory(Audio_store) if request.method == 'POST': formset = songmp3(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = songmp3() return render(request, 'homepage.html', {'formset': formset}) -
How do I make text "bold" in email body in python?
How can I make text bold in the email body in python? I am using the following code to send mail : from django.core.mail import send_mail send_mail(subject, message, sender, [email], fail_silently=False) I want to make some important text bold. Using the following code I have received the whole string as a message. message = " Hi Customer,<br> Your OTP is <b>****</b>" But it works when I try \n as <br>. What can I do to make the text bold? -
Custom form in Django shows ids instead of string
guys! I'm struggling with django forms. Default ones represent models as expected (returning __ str __ values). However, my custom form (Event_form_for_Admin) shows ids instead of string in admin panel and on the site. What am I missing? models.py class Position(models.Model): name = models.CharField(max_length=800) level = models.CharField(max_length=50) def __str__(self) -> str: return f'{self.level} {self.name}' class Person(models.Model): name = models.CharField(max_length=300) def __str__(self) -> str: return self.name class Event(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) position = models.ForeignKey(Position, on_delete=models.RESTRICT) def __str__(self) -> str: return f'{self.action} {self.position}' forms.py class Event_form_for_Admin(forms.ModelForm): person = forms.CharField(widget=forms.TextInput, label='Name') position = forms.CharField(widget=forms.TextInput, label='Position') class Meta: model = Event fields = ['person','position'] output on site as well as in admin panel: -
Allow all ips in CSRF_TRUSTED_ORIGIN django
How to allows all/ any ips in CSRF_TRUSTED_ORIGIN of django Backend django restapi are running and frontend is on angular in one system and we are trying to access with system ip in another system, i am able to access frontend and while accessing backend POST method API's are not working it's showing not found in card trusted origins. In settings.py i made get dynamic ips. import socket def get_ipaddress(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) return "http://"+ip_address+":4200" ALLOWED_HOSTS=["*"] CSRF_TRUSTED_ORIGINS=[get_ipaddress()] Tried to use csrf_excempt , but it's not working. Version of django4.0.1, Angular 16 -
How do I access image URL from one django model to another? How do I put it on a template?
I am using two models Forum and User. User model.py: class User(models.Model): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) profile_img = models.ImageField(upload_to='images/', null=True, blank=True) I wanted to access the url of User's profile_img and display it to my template in Forum. How should I code this in my Forum's model.py?