Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize object field in django rest framework
I have Profile model, which is auth model. And I have Blog model. I want to serialize model as it will give me {author: {user_name:.., photo: photo_path}, blog_title:some_title, ..}. Shortly, I want use author field as inner serialiser. I have already ProfileSerialiser and BlogSerializer. Here's my BlogList serializer: class BlogListSerializer(serializers.ModelSerializer): author = MiniProfileSerializer() class Meta: model = Blog fields = ['title', 'content', 'like_count', 'author'] read_only_fields = ['views', 'author', 'like_count'] And MiniProfileSerializer: class MiniProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user_name', 'image'] and view: class BlogListAPIView(generics.ListCreateAPIView): serializer_class = BlogListSerializer queryset = Blog.published.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] -
Can't change background color of django form field
I'm trying to change background colors of django form field using attrs of form.widget like below. forms.py class MyForm(forms.Form): a_filed = forms.EmailField( widget=forms.EmailInput( attrs={'class':'black-input'})) It produces an html element in a template with classname 'black-input' as expected. html <input type="email" name="email" class="black-input" id="id_email"> Elements with the name 'black-input' should show up with black background as I set {background-color:black} in my css. main.css .black-input{ padding: 5px; background-color: rgba(1, 4, 9, .7); color: rgba(177, 177, 177, .8); border: none; border-radius: 8px; } But css doesn't change anything about background color. The weird part is that css changes other attributes of the element (border, border-radius, padding). -
How do i do user = request.user in views.py just because i have foreign key in my model
How do i update user field in views.py just because i have a view to edit and delete posts associated with the user. I also have a view that fetch products with user == request.user and show in the profile page. Almost my site is dependent on post creation.Please let me know how can I update that user foreign key while saving the form( ex:- product.user = request.user ) My Models.py ```class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150) details = models.TextField(default="...") ....``` My Forms.py ```class AddUserPacksForm(forms.ModelForm): user = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) title = forms.CharField(label='Title', widget=forms.TextInput( attrs={'class': 'form-control'})) details = forms.CharField(label='Description', widget=forms.Textarea( attrs={'class': 'form-control'})) image = forms.FileField(label='Thumbnail', widget=forms.FileInput( attrs={'class': 'form-control'})) sp = forms.IntegerField(label='Selling Price', widget=forms.NumberInput( attrs={'class': 'form-control'})) dp = forms.IntegerField(label='Discounted Price', widget=forms.NumberInput( attrs={'class': 'form-control'})) buy_link = forms.CharField( label='Buy Link ( i.e Instagram Link, Shorten Urls, Your Own Website Link Where Users can Buy This Pack, etc )', widget=forms.TextInput(attrs={'class': 'form-control'})) category = forms.ChoiceField(label='Category', choices=CHOICES, widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Product fields = ['title', 'details', 'image', 'sp', 'dp', 'buy_link', 'category']``` My Views.py ```def AddUserPacks(request): if request.method == "POST": userform = AddUserPacksForm(request.POST, request.FILES) if userform.is_valid(): userpacks = userform.save(commit=False) userform.user = request.user.get_profile() userpacks.save() messages.success(request, f'Successfully Uploaded the post') return redirect('home') … -
How To give optional parameter in DRF
Hi Everyone i am created one api, where i will city_id as parameter but i need id parameter for this api, means view data based on city_id or based on id, please help me out. serializers.py class CarNumberSerializer(serializers.ModelSerializer): model=CarModelNameSerializer() company=CarCompanySerializer() class Meta: model = Car fields = ['id','car_number','model','company'] views.py class CarNumberViewset(viewsets.ModelViewSet): queryset=Car.objects.all() serializer_class= CarNumberSerializer def retrieve(self, request, *args, **kwargs): params= kwargs params_list=params['pk'] car=Car.objects.filter(city=params_list) serializer=CarNumberSerializer(car,many=True) return Response(serializer.data) urls.py routers.register(r'gms/car_list',CarNumberViewset) -
Upload file to Django in Requests.POST
Trying to upload a text file (of molecules) to ADMETlab 2.0 and download the corresponding CSV output, from within python. Tried the following code: import requests fyle = 'infile.sdf' Headers = {"Referer" : "https://admetmesh.scbdd.com/service/screening/index", "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"} with open(fyle, 'rb') as f: r = requests.post('https://admetmesh.scbdd.com/service/screening/cal', files={fyle: f}, headers=Headers) print(r.text) Which led to this error: ValueError: invalid literal for int() with base 16: b I tried this fix and now, no error is raised but nothing except a blank new line is printed. Where am I going wrong? -
How to add default data to django model
I have a web app with the following model class Records(models.Model): alias = models.CharField(max_length=17, unique=True) status = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.alias def list_data(self): return [self.alias, self.status, self.created_at, self.updated_at] I want some default data to be populated into this model on creation. I went through the documentation and this StackOverflow question for doing the same. I first ran this command to create a migrations file (0001_initial.py) python manage.py makemigrations --empty main_app I then edited the migrations file as follows 0001_initial.py # Generated by Django 4.0.3 on 2022-04-23 05:57 from django.db import migrations def add_initial_data(apps, schema_editor): Records = apps.get_model('main_app', 'Records') for record in Records.objects.all(): record.alias = f'ACCORD1' record.status = True record.save() for i in range(2,6): record.alias = f'ACCORD{i}' record.status = False record.save() class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(add_initial_data) ] When I run the migrations with the following command python manage.py migrate I get the following error LookupError: No installed app with label 'main_app'. I tried adding the dependency to the migrations file as follows dependencies = [ ('main_app', '0001_initial') ] But this gives me the following error django.db.migrations.exceptions.CircularDependencyError: main_app.0001_initial I am not sure what I am doing wrong. -
Why data passed from frontend using ajax shows NonType in view function in Django
I have created a form in html which take some value from user on clicking submit button a JavaScript function is called which passes data using ajax to Django server. But instead of getting data in view function it shows NoneType error on backend. My html form:- <div class="cropDetail"> <form method="post"> {% csrf_token %} <div class="form__group"> <label htmlFor="name" class="form__label"> Nitrogen </label> <input type="number" id="nitrogen" name="nitrogen" class="form__input" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Potassium </label> <input type="number" id="potassium" class="form__input" name="potassium" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Phosphorus </label> <input type="number" id="phosphorus" class="form__input" name="phosphorus" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> PH </label> <input type="number" id="ph" class="form__input" name="ph" required /> <p className="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Rainfall </label> <input type="number" id="rainfall" class="form__input" name="rainfall" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> City </label> <input type="text" id="city" class="form__input" name="city" required /> <p class="error"></p> </div> <div class="form__actions"> <button onclick="passdata()">Submit</button> </div> </form> </div> My JavaScript function:- const nitro = document.getElementById("nitrogen"); const potass = document.getElementById("potassium"); const phos = document.getElementById("phosphorus"); const phi = document.getElementById("ph"); const rain = document.getElementById("rainfall"); const cityi = document.getElementById("city"); function passdata(event) { event.preventDefault(); const usernitrogen = nitro.value; const userpotassium … -
Chrome Incognito Mode 2GB download net::ERR_FAILED
Maybe you could share your piece of advise on the following trouble: Chrome Incognito Mode doesn't let download big files (2 Gb) with net::ERR_FAILED 200 error in console: The same download of the same file works fine without Incognito; the same same request with the same headers also work fine when loading a file via Curl; and other browsers' incognito mode also works fine. I wonder maybe there is some kind of a memory limit for file download using Chrome in Incognito mode? And what memory does Chrome use for downloading files in Incognito mode? Thank you! -
CSS doesn't work as expected in HTML files in Django
I want to know why static CSS files in Django always don't work as expected? I tried to include CSS styles in HTML tag, load static files in HTML. Only add styles directly in tag attributes worked. Some CSS code worked well in static folder, some don't. I can't even style an 's color through CSS files, which is one of the simplest styling things. Still can't find a perfect way that can solve this problem. Please help me with this >< -
django.core.exceptions.FieldError: Unknown field(s) (contact_number, address, user_type) specified for User
how to solve this error: django.core.exceptions.FieldError: Unknown field(s) (contact_number, address, user_type) specified for User. forms.py: from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','address','contact_number','user_type','username','password'] widgets = {'first_name': forms.TextInput(attrs={ 'class': 'form-control'}), 'last_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'address': forms.Textarea(attrs={ 'class': 'form-control' }), 'contact_number': forms.IntegerField(attrs={ 'class': 'form-control' }), 'user_type': forms.Select(attrs={ 'class': 'form-control' }), 'username': forms.TextInput(attrs={ 'class': 'form-control' }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control' }) } I am getting difficulty here please tell me what to do. -
How to correctly access parent form's field/s from inline form clean method during Update
I am a little perplexed. Using CreateView, When I try to get the data of a field in the parent table's form from the (child table's) inline form's clean method I can do that: def clean(self): super(CreateMyItemsForm, self).clean() cleaned_data = super(CreateMyItemsForm, self).clean() var_date = self.data.get('valid_to_date') # NOTE: **valid_to_date** is a field in the parent table However, during update (using UpdateView) the same method fails. Why? What am I doing wrong here? Thanks. -
Wagtail: Get data from promote tab?
When creating a new page, there's a "Promote" tab. Under the "for search engines" section there's a "title tag" and a "meta description" value. As I understand, the "title tag" sets the document's title and the "meta description" sets the document's meta description. But how would I actually use these values in my page template? I searched far and wide, but it seems that Wagtail's documentation explains nothing about the Promote tab or what purpose it serves. Are the values defined there available as template variables? How would I actually access a page's "title tag" or "meta description"? -
got an "django local variable 'form' referenced before assignment" error in django form
When I have only one form in view.py it works, but when I add another form I got this error. Error Forms.py Views.py -
Running Django's collectstatic in Dockerfile produces empty directory
I'm trying to run Django from a Docker container on Heroku, but to make that work, I need to run python manage.py collectstatic during my build phase. To achieve that, I wrote the following Dockerfile: # Set up image FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Install poetry and identify Python dependencies RUN pip install poetry COPY pyproject.toml /usr/src/app/ # Install Python dependencies RUN set -x \ && apt update -y \ && apt install -y \ libpq-dev \ gcc \ && poetry config virtualenvs.create false \ && poetry install --no-ansi # Copy source into image COPY . /usr/src/app/ # Collect static files RUN python -m manage collectstatic -v 3 --no-input The Dockerfile builds just fine, and I can even see that collectstatic is running and collecting the appropriate files during the build. However, when the build is finished, the only evidence that collectstatic ran is an empty directory called staticfiles. If I run collectstatic again inside of my container, collectstatic works just fine, but since Heroku doesn't persist files created after the build stage, they disappear when my app restarts. I found a few SO answers discussing how to get collectstatic to run inside a Dockerfile, but … -
ProgrammingError at /blog/ django project in ubuntu vps
I encountered this error after deploying the project on a Linux server. But when running it on localhost, I had no error like this in addition that I say, I have a blog application views.py from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by("-created_at") template_name = "blog/blog.html" class PostDetail(generic.DetailView): model = Post template_name = "blog/blogContent.html" urls.py from django.urls import path from . import views urlpatterns = [ path("", views.PostList.as_view(), name="blog"), path("<slug:slug>/", views.PostDetail.as_view(), name="post_detail"), ] blog.html {% extends 'base.html' %} {% load static %} {% block content %} <main class="main"> <div class="container blog_container"> <h2>وبلاگ</h2> <div class="content_container"> {% for post in post_list %} <div class="content"> <a href="{% url 'post_detail' post.slug %}"><img src="{{ post.image.url }}" alt="" ></a> <a href="{% url 'post_detail' post.slug %}" class="title">{{ post.title }}</a> <p>{{ post.author }} </p> <p>{{ post.created_at|timesince }}</p> <br> <p class="description">{{post.content|slice:":200" }} </p> </div> {% endfor %} </div> </div> </main> <!-- START FOOTER COMPONENT --> {% endblock content %} -
In django ,display all user with their corresponding profile picture on admin home page
I am new in django, I am working on a project I want to display users information with their corresponding profile picture on admin home page. I am using default User Model. I use userdata= User.objects.filter(is_superuser=False, is_staff=False) to display all user informations my Profile model is class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) forget_password_token = models.CharField(max_length=100) image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' i want to do like this enter image description here Please help me to achieve this. Thanks in advance -
No registered models were found when using django-simple-history in inhered model
I've created a class to inherit to my django models so I can use django-simple-history. However, when trying to generate migrations, it indicates that there are no changes detected class VersionableModel: history = HistoricalRecords() def getHistory(self): pass class SoftDeleteModel(models.Model): is_deleted = models.BooleanField(default=False, verbose_name='Deshabilitado') objects = SoftDeleteManager() all_objects = models.Manager() class DimensionAmenaza(SoftDeleteModel, VersionableModel): mombre_dimension_amenaza = LowerCharField(blank=False, unique=True, max_length=100) peso_dimension_amenaza = models.FloatField(validators=[validate_percent], null=False, blank=False) -
Change color scheme of django-baton admin interface
So I wanna change the color scheme of the interface, I've read the self-help stuff from https://otto-torino.github.io/django-baton but it's not making much sense to me, I've located the _variables.scss file, which I need to change to make it work, how do I go about this, would really appreciate your help thx! Django-baton package link: https://github.com/otto-torino/django-baton -
What does Herokus metric graph display?
I use Heroku, but I'm either too dumb or am looking in all the wrong places to get info on how the dynos work. I initially thought that a single dyno could run a bunch of different processes simultaneously. But I realized that if that were the case, then when I increased the dyno count, my memory usage would have gone down. Since that isn't the case, it must mean that the memory usage graph actually displays the most memory-intensive dyno. But that doesn't feel right because that doesn't seem to be mentioned anywhere. So my question is are any of my assumptions correct and/or is there a helpful resource for having a better understanding of dynos? -
Why does .env file isn't working in django docker?
I am working on django docker project. I added .env file, but I have this error: celery_1 | File "/project/core_app/__init__.py", line 5, in <module> celery_1 | from .celery import app as celery_app celery_1 | File "/project/core_app/celery.py", line 11, in <module> celery_1 | from core_app.settings import INSTALLED_APPS celery_1 | File "/project/core_app/settings.py", line 90, in <module> celery_1 | 'NAME': os.environ['DB_NAME'], celery_1 | File "/usr/local/lib/python3.9/os.py", line 679, in __getitem__ celery_1 | raise KeyError(key) from None celery_1 | KeyError: 'DB_NAME' It seems that I specified env_file in docker-compose correctly but error said that code doesn't see environment variables. How can I fix the problem? settings.py import environ import os env = environ.Env() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'db', 'PORT': 5432, } } .env -- just a few configs DB_USER=postgres DB_PASSWORD=post222 DB_NAME=lk_potok_4 DB_PORT=5444 DATABASE_URL=postgres://postgres:post222@db:5432/lk_potok_4" docker-compose.yml -- full file https://pastebin.com/0feAg5xq version: '3.9' services: django: build: ./project # path to Dockerfile command: sh -c " python manage.py makemigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" volumes: - ./project:/project - ./project/static:/project/static expose: - 8000 env_file: - .env environment: - DATABASE_URL=${DATABASE_URL}" - DEBUG=1 - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_NAME=${DB_NAME} db: image: postgres:13-alpine volumes: - pg_data:/var/lib/postgresql/data/ expose: - 5432 … -
Django model newly created object from pre_save signal handler disappears
In our Django app, in order to prevent users from randomly updating their profiles for compliance purposes, we need all profile updates to be reviewed. I added a pre_save signal to the User model and in the signal handler, I create an object to the table ProfileUpdateRequest using ProfileUpdateRequest.objects.create(...) and then raise an exception. The exception is then caught in the ViewSet to return a proper response. However, when I tested it, I found that every time I update the user profile, a new object of ProfileUpdateRequest was created but not applied to the database. I assigned the returned value of the create() method to a variable and logged it out. I saw the id of the new object increasing all the time, but there was no new object added to the table at all. I wonder whether the changes were not applied to the DB immediately and the exception broke the normal workflow which caused the changes not to be applied to the DB. -
Attempting to get C code to find size of directory to compile with Emscripten
I'm having an issue getting my C code to compile with emscripten; fun fact this my first stack overflow post, as most of the time when I have an issue regarding a system or programming language there is a pre-existing question on here I can reference to get an answer, however this is different. I'm attempting to display the size of my Django Root directory on the webpage, this is the C code I am attempting to compile. #include <stdio.h> #include <errno.h> #include <unistd.h> #include <ftw.h> #include <sys/types.h> #include <sys/stat.h> static unsigned int total = 0; int sum(const char *fpath, const struct stat *sb, int typeflag) { total += sb->st_size; return 0; } int main() { char *DJANGO_ROOT = "/usr/src/app"; if (!DJANGO_ROOT || access(DJANGO_ROOT, R_OK)) { return 1; } if (ftw(DJANGO_ROOT, &sum, 1)) { perror("ftw"); return 2; } printf("%s: %u\n", DJANGO_ROOT, total); return 0; } This is the output I receive when attempting to compile the file using "emcc dir_size.c -o dir_size.html" yalt@mainframe:~/Network/Mainframe/rabbithole_site/django_root/my_app/static/js/wasm/dir_size$ emcc dir_size.c -o dir_size.html error: undefined symbol: ftw (referenced by top-level compiled C/C++ code) warning: Link with `-sLLD_REPORT_UNDEFINED` to get more information on undefined symbols warning: To disable errors for undefined symbols use `-sERROR_ON_UNDEFINED_SYMBOLS=0` warning: _ftw may … -
Django - Can I delete an instance of object from a choices selection set (ModelChoiceField)?
I am newbie in the Django world, so i am wondering if its possible to get an instance from a selection set (choice field) and then delete it. In my case I want to pick a Profile, and then delete it. enter image description here views.py class SelectProfileFormView(views.FormView, LoginRequiredMixin): form_class = SelectProfileForm template_name = 'profile/delete-member.html' def form_valid(self, form): profile = Profile.objects.get(pk=self.kwargs['pk']) profile.delete() return super().form_valid(form) form class SelectProfileForm(forms.ModelForm): profiles = forms.ModelChoiceField( widget=forms.Select, queryset=Profile.objects.all(), # empty_label="----None----", ) # here you can filter for what choices you need class Meta: model = Profile fields = () I get this error: "KeyError at /profile/select/" "pk" How can I delete the chosen instance? Should I make a selection view and then a delete view separately? If so how can I redirect with the correct pk instance? Thanks in advance! -
How to modify a models to be able to give access to users in django
I am working on a classroom project and I am completely new to Django. How to modify my models (course,user) so that I can add students to the course in two ways 1)By entering the class code by students. 2)By sending join invitations to students from a list of all students by selecting some by the teacher and if the student confirms/accepts he will be added. i am attaching the models below user model class CustomUser(AbstractUser): email = models.EmailField() is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) Course Model class Course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(25)]) classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) slug=models.SlugField(null=True, blank=True) def __str__(self): return self.course_name def save(self, *args, **kwargs): self.slug = slugify(self.classroom_id) super().save(*args, **kwargs) def is_valid(self): pass -
Match between dictionaries in list
hello guys i have a question to how match between dictionaries i send 3 request to youtube api first to search second to video third to channel what i try to create is dic that have Title of the video Thumbnails of the video and the profile of the channel that make the video. here you can see the code and the requests i send: def get(self,request): search_url = "https://www.googleapis.com/youtube/v3/search" video_url = "https://www.googleapis.com/youtube/v3/videos" channel_url = "https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+commaSeperatedList+'&fields=items(id%2Csnippet%2Fthumbnails)&key={}".format(settings.YOUTUBE_DATA_API_KEY) para_search = { 'part': 'snippet', 'q': 'Learn Python' , 'key': settings.YOUTUBE_DATA_API_KEY, 'maxResults': 3, 'type': 'video' } search_response = requests.get(search_url,params=para_search) print(search_response.text) results = search_response.json()['items'] ids =[] for result in results: ids.append(result['id']['videoId']) para_videos = { 'part': 'snippet', 'key': settings.YOUTUBE_DATA_API_KEY, 'id':','.join(ids), } video_response = requests.get(video_url, params=para_videos) print(video_response.text) results = video_response.json()['items'] dict_youtube = {} list_youtube = [] channelIdList = [] for result in results: dict_youtube = { 'title': result['snippet']['title'], 'thumbnails': result['snippet']['thumbnails']['high']['url'], 'channelId': result['snippet']["channelId"], } channelIdList.append(result['snippet']["channelId"]) list_youtube.append(dict_youtube) param_channel = { 'part':'snippet,contentDetails,statistics', 'key':settings.YOUTUBE_DATA_API_KEY, 'id':','.join(channelIdList) } channel_response = requests.get(channel_url,params=param_channel) print(channel_response.text) results = channel_response.json()['items'] profile = [] profile_dic = {} for result in results: profile_dic = { 'channelId': result['id'], 'profile': result['snippet']['thumbnails']['default']['url'], } profile.append(profile_dic) print(profile) print(list_youtube) print(profile): [{'channelId': 'UC8butISFwT-', 'profile': 'https://yt3.ggpht.com/ytc/AifQn-nYNfkgLvVPkw=s88-********-no-rj'}, {'channelId': 'UCWv7*mDpPBA', 'profile': 'https://yt3.ggpht.com/tBEPr-zTNXEeae7VZK2PXSwzMBKVR7W0MI7gyND8=s88-c-k-c0x00ffffff-no-rj'}] print(list_youtube) [{'title': 'Learn Python - Full Course for …