Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: How to get data from a post request at class based API views?
This is the simple api view: class ReceiveNewData(APIView): def post(self, request): return Response('response') When we are posting some data to somewhere, we can send some data with it. For example: request.post(url, data={//the data will be sent}) Or from the body section in Postman program. The question is: how can I receive any data at my api view like that? -
Django Tutorial. Page not found
I already search for any answer which could help me before write this question, but I haven't found anything that helps. The thing is that I follow the tutorial and I can't see the view that I created. Now I'm going to share my code: project urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls urls.py: from django.urls import path from . import views urlpatterns = [ path(" ", views.index, name='index'), #127.0.0.1/polls/ ] polls views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): HttpResponse("Welcome to de Polls Universe Index") -
Why is my Boostrap-Card header not filling entire width of the card?
I am new to Bootstrap and Django. I am trying to style a card, but card header (background) does not fill entire width of the card. Here is an example: Here is the code: <div class="container"> <div class="grid"> <div class="row"> {% for list, content in content.items %} <div class="card col-md-6 shadow-lg"> <a href="{{user_name}}/{{list}}"> <div class="card-header bg-secondary text-white">{{list}}</div> <div class="card-body"> <ul> {% for row in content %} <li>{{row}}</li> {% endfor %} </ul> </div> </a> </div> {% endfor %} </div> </div> </div> -
Getting the error : ImportError: cannot import name 'to_const'
getting the following import error in my Django application, is there a workaround ? from graphene.utils.str_converters import to_camel_case, to_const ImportError: cannot import name 'to_const' -
how to put radio button from admin.py?
one question is that I am using admin.py to make my profile edition page; I had to do it like this to add more fields and customize it. Everything works fine, except for one thing: I don't know how to format a form field (it's called country) to be a radio button and have the options "canada", "USA" and "other" does anyone have an idea? how to do it? I am using UserCreationForm and UserChangeForm but I don't know how to edit forms that are already preset admin.py class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form=UserChangeForm model=CustomUser list_display = ['pk','email','username','first_name','last_name'] add_fieldsets = UserAdmin.add_fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) fieldsets = UserAdmin.fieldsets+( (None,{'fields':('email','first_name','last_name','image','location','phone1','phone2','fax','website', 'socialMedia1','socialMedia2','socialMedia3','alternativeContact','country','address', 'city','state','zip')}), ) admin.site.register(CustomUser) -
MyPy, Django, VSCode. ModuleNotFound Error
I really need your help here! I am using VSCode and MyPy extension to type check the Django code that I am writing. I have installed all the necessary requirements for Django like: pip install mypy pip install django-stubs-ext pip install django-stubs I have installed the extension for the VSCode to check my code as well. However, whenever I try to use this extension it outputs the following error: ModuleNotFoundError: No module named 'md_project.settings' I have attached the screenshots of the .ini and .json files of my project. Moreover, I have attached the screenshot of the project tree. I just dont know whats going on with the MyPy. By the way, I am using Windows 10. mypy.ini settings.json project tree -
How to send 'image' via POSTMAN? (Django Image Field)
I'd like to send image via postman like this and save to 'media' directory but don't know how to do this. enter image description here And these are my codes that I use. models.py class Article(models.Model): emotion = models.TextField() location = models.TextField() menu = models.TextField() weather = models.TextField() song = models.TextField() point = models.IntegerField() content = models.TextField() image = models.ImageField(default = 'media/coffee_default.jpg', upload_to = "%Y/%m/%d") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(default = now) liked = models.BooleanField(default = False) num_liked = models.IntegerField(default = 0) views.py @api_view(['POST']) @permission_classes([]) def post_articles(request): user = request.user body = json.loads(request.body) article = Article( emotion = body['emotion'], location = body['location'], menu = body['menu'], weather = body['weather'], image = body['image'], song = body['song'], point = body['point'], content = body['content'], user = user) article.save() serializers = ArticleSerializer(article) return JsonResponse({ "success": True, "data": serializers.data }) serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked'] -
Pycharm - FastAPI issue with static files
I am struggling to reference my static css files in my template index.html file In my head tag in index.html I have: <link href="{{ url_for('static', path='./styles.css') }}" rel="stylesheet"> It is giving me this error "Cannot resolve directory" In main.py I have the files mounted like so: app.mount("/static", StaticFiles(directory="static"), name="static") Folder Structure: ├── Project_name ├── main.py ├── static │ ├── styles.css ├── Templates │ ├── index.html What could be the cause of this, how can I specify the correct path? -
password_reset_confirm and password_reset_complete in Django
I have used Django's built-in password reset functionality. everything is working fine but when I open the password reset link from Gmail browser redirects me to Django's built-in "password_reset_confime " template instead of my custom template I don't know where I have done mistake in rendering custom template please help me to do that its really appreciated usrl.py Code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] And I also want to implement a feature while entering an email id into the input field, I want to check if the user's entered email exists or not, if do not exist I want to show an error message "this email id is not existed" please help me to implement this feature and provide a solution for rendering my custom password_reset_confirm.html and password_reset_complete.html pages -
How to send several fields in the response with a PUT request?
I would like when my PUT request is successful it returns me a response with all the fields in my PlantSerializer because currently the response returns me this: { "id":48, "name":"Jar", "width":"50", "height":"50", "exposure":"None", "qr_code":"", "garden":65, "plant":[ 7 ] } But, I would like the response to return this instead: { "id":48, "name":"Jar", "width":"50", "height":"50", "exposure":"None", "qr_code":"", "garden":65, "plant":[ "id":7, "name":"Artichoke", "image":null ] } How can I achieve this result? Here is my serializers and my model class : class Plot(models.Model): name = models.CharField(max_length=50) garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) width = models.CharField(max_length=50, blank=True, null=True) height = models.CharField(max_length=50, blank=True, null=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) # Here is my serializers : class GardenSerializer(serializers.ModelSerializer): class Meta: model = Garden fields = ('id', 'name',) class PlantSerializer(serializers.ModelSerializer): class Meta: model = Plant fields = ('id', 'name', 'image') class ReadPlotSerializer(serializers.ModelSerializer): garden = GardenSerializer(required=True) plant = PlantSerializer(many=True) id = serializers.IntegerField(read_only=True) class Meta: model = Plot fields = '__all__' read_only_fields = [fields] class WritePlotSerializer(serializers.ModelSerializer): class Meta: model = Plot fields = '__all__' And here is my views : class PlotViewSet(viewsets.ModelViewSet): queryset = Plot.objects.all() def create(self, request, *args, **kwargs): serializer = WritePlotSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): snippet … -
The easiest way to add attachment in an email - Django
What is the easiest way to add an attachment in a sent e-mail from a model object. If it impossible how look example with EmailMessage. Models.py class File(models.Model): file = models.FileField() Views.py topic = 'Title message' massage = 'Content message' to = ['recipient@example.com', ] attachment = File.objects.last() send_mail(topic, massage, 'bsender@example.com', to, attachment) -
In Django forms I can't use regex validators
Good day. I want to use regex validator for my full_name field in Django 1.11.10. But when I run the below code it doesn't work. How can I fix it? forms.py class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) self.fields['orderorbarcode'].widget.attrs['readonly'] = True self.fields['orderorbarcode'].label = "Order ID or Item Barcode" self.fields['full_name'].label = "Full Name" self.fields['phone_number'].label = "Phone Number" self.fields['full_name'].widget = forms.TextInput(attrs={'placeholder': '*required'}) self.fields['email'].widget = forms.TextInput(attrs={'placeholder': '*required'}) self.fields['phone_number'].widget = forms.TextInput(attrs={'placeholder': '*required'}) class Meta: model = Customer fields = ( 'orderorbarcode','full_name','company','email', 'phone_number','note') AlphanumericValidator = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') full_name = forms.CharField(max_length=50, validators=[AlphanumericValidator]) -
Django MIgrations Issues
I'm facing Django migrations problems for a very long time and used to solve that problem using the --fake keyword but then I realized that it's not a good approach and even creates more problems, so after that whenever I faced that issue so I remove the DB and recreate it and then applied migrations and it was working fine but now our data is important and can't remove the DB. The problem is I've created a new Django app in my project and generated the migrations and applied them and working fine at the local but it throws the error I attached below related to migrations. I tried to apply them using the --fake keyword because the feature needs to be at that time but again it was not working I checked the migrations using python manage.py showmigrations and the migrations is there but when I checked django_migrations table in my DB and not a single migration file of that app is not found there, what's the best solution to overcome this issue? error: ProgrammingError at .... column .... does not exist -
django-filter more results when explicitly setting a filter value
I am trying to understand what happens what a field specified in the filterset_fields of the viewset is not specified. My viewset is the following: class DetectionTrainingViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Detection.objects.all() serializer_class = DetectionSerializer filterset_fields = ( 'annotation_set__annotator__id', 'annotation_set__bbox__annotator__id', ) I am making the following GET calls my endpoint http://127.0.0.1:8000/api/v1/detections/: ?annotation_set__annotator__id=2 -> I get 4 results ?annotation_set__annotator__id=2&annotation_set__bbox__annotator__id=2 -> I get 16 results I expected the second call to return a subset of the following one. What's happening here? How can I specify that when a parameter is not explicitly specified any value (if it does not exist) should match the query? -
Static Files not being served with nginx + gunicorn + doker + django
I am making a docker image of a django application with nginx and gunicorn. The configuration files are given below. This server serves static files with ease in development but fails to do so in docker container. What changes do I need to make to serve files in docker? docker-compose.yml version: '3.7' services: segmentation_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - segmentation_gunicorn volumes: static: requirements.txt FROM python:3 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./segmentation_site /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] requirements.txt DJANGO==4.0.4 gunicorn==20.0.4 tensorflow django-resized pillow==9.1.0 django-crispy-forms==1.14.0 entrypoint.sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn --bind 0.0.0.0:8000 segmentation_site.wsgi:application Dockerfile for nginx FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf default.conf upstream django { server segmentation_gunicorn:8000; } server { listen 80; client_max_body_size 100M; location / { proxy_pass http://django; } location /static/ { alias /static/; } } settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") -
How to create nested serialization from mutliple models uisng django rest framewrok
I am trying to create nested relationship from more than two models in Django Rest Framework. Thank you in advance for helping me. I succeed with two models but when I'm trying with three models unable to create nested serialization. from django.db import models class Project(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=255) def __str__(self): return self.name class Site(models.Model): site_id = models.AutoField(primary_key=True) site_name = models.CharField(max_length=255) project_id= models.ForeignKey(Project, related_name="projectid", on_delete=models.CASCADE) def __str__(self): return self.site_name class Aggin(models.Model): assign_id = models.AutoField(primary_key=True) site_id = Models.ForeginKey(Site, relate_name="siteid", on_delete=models.CASCADE) from rest_framework import serializers from .models import Song, Artist class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('__all__') class SiteSerializer(serializers.ModelSerializer): class Meta: model = Site fields = ('__all__') class AggignSerializer(serializers.ModelSerializer) class Meta: model = Aggin fields = ('__all__') -
How Can I develop FaceMask Detecion Using Django FrameWork
I prepared the facemask detection model but I don't know to program and integrate Django with my model???? please help me -
User can only see his data Django
Im building a contract management system, and i want to the user to only the companies, clients and users that he registered, now when i register a new user, he can also see the data companies that other users registered. How can i make it see only his own clients, companies and contracts? views.py # List the companies @login_required def client_company_list(request): clients = ClientCompany.objects.all() pending_payments_total = ClientCompany.objects.aggregate(sum=Sum('pending_payments'))['sum'] or 0 received_payments_total = ClientCompany.objects.aggregate(sum=Sum('received_payments'))['sum'] or 0 client_count = ClientCompany.objects.filter().count() return render(request, 'list_client_company.html', {'clients': clients, 'pending_payments_total': pending_payments_total, 'received_payments_total': received_payments_total, 'client_count': client_count}) # Crate a new company @login_required def new_client_company(request): # Start post add the company to the DB using POST or start a new form using None form = ClientCompanyForm(request.POST, request.FILES, None) # Check if the form is valid if form.is_valid(): form.save() return redirect('companies_list') return render(request, 'client_company_form.html', {'form': form}) models.py # Company client class ClientCompany(models.Model): company_name = models.CharField(max_length=30) company_cnpj = models.IntegerField() phone = models.IntegerField(null=True, blank=True) email = models.EmailField(null=True, blank=True) pending_payments = models.DecimalField(blank=True, null=True, max_digits=12, decimal_places=2) received_payments = models.DecimalField(blank=True, null=True, max_digits=12, decimal_places=2) description = models.TextField(blank=True, null=True) # To return the name of the company on the django admin def __str__(self): return self.company_name class UserManager(BaseUserManager): # Create standard user def create_user(self, email, full_name, password=None, is_active=True, … -
How to serializer data outside of view in Django REST
I am working on a Chat system which utilizes Django-Channels. Therefore, I need to serialize data outside of views, then return this serialized data. Problem occurs where I am getting an error. Method for creating and serializing data: @database_sync_to_async def create_message(self, message, sender, uuid): with tenant_context(sender.company): # Update the chat's updated_on field by saving it self.chat.save() serializer = ChatMessageSerializer(data={ 'message': message, 'sender': sender, 'chat': self.chat }) if serializer.is_valid(): serializer.save() return serializer.data else: raise serializer.errors Error: ERROR: null value in column "chat_id" of relation "discussions_chatmessage" violates not-null constraint It seems that it is not creating the ID for this object. How should I go about creating the serialized object correctly? Thanks in advance! -
Passing data from post form to FileResponde view
I recently started using Django and I managed to create two views, one to submit a form and another to return a FileResponse, separately, they work fine. Now, I need to integrate both, when the client submit the form, I want to redirect to the another view using the fields submitted at the previous form. How can I do that? Here is my form view: def submitForm(request): if 'report' in request.POST: date_start = request.POST.get('date_start') date_end = request.POST.get('date_end') state = request.POST.get('state') return render(request, 'comissao.html') Here is my view that creates a pdf file def createPdf(request): date_start = '20220301' date_end = '20220331' state = 'G00471' body = "some html" options = { 'quiet': '' } pdfkit.from_string(body, options=options) file = open('file.pdf', 'rb') return FileResponse(file) As you can see, I need the information passed at my first view, to use at second view, I tried something like this, but I think I'm mistaking the concept, return reverse('pdf', kwargs={'state':state, 'date_start':date_start, 'date_end':date_end}) -
How to use Nginx + Gunicorn + Django to authenticate Kerberos users?
I refactored my project code, we used apache + Django, and now use Nginx + gunicorn + Django replace But I met an issue, after use "spnego-http-auth-nginx-module"(https://github.com/stnoonan/spnego-http-auth-nginx-module) in Nginx for Kerberos authentication, but after Nginx is authenticated, Django cannot authenticate. display: "Authentication credentials were not provided." I want to use Kerberos user for all authentication. after Nginx authenticated, Django should also be authenticated. Do any guys know how to set Django to accept the Nginx authentication result? -
Getting two values from the same annotation query
I have two related models: class ProductSKUs(BaseModel): STATES = [(1, "New"), (2, "Open Box"), (3, "Refurbished")] shop_id = models.SmallIntegerField(default=1, blank=True, verbose_name="Shop ID") sku = models.IntegerField(verbose_name="SKU") product_id = models.ForeignKey( "Products", on_delete=models.CASCADE, ) state = models.SmallIntegerField(choices=STATES, default=1, null=True, verbose_name="State") featured = models.BooleanField(default=False, blank=True) class ProductOffers(BaseModel): sku = models.ForeignKey( "ProductSKUs", on_delete=models.CASCADE, db_column="product_sku_id", related_name="product_offers", related_query_name="product_offer", ) price = models.FloatField() price_promo = models.FloatField( null=True, blank=True, verbose_name="Promotional Price" ) What I am trying to do is get a ProductSKUs queryset with the correct shop_id, and then also get the price and price_promo from the ProductOffers with the lowestprice_promo value. I have tried the following queryset below, but the issue is that I want the same price and price_promo from the same product offer but it is getting the values from two different objects. featured_product_skus = ( ProductSKUs.objects.filter(shop_id=1, featured=True) .select_related("product_id") .prefetch_related("product_offers") .annotate( min_price_promo=Min("product_offer__price_promo"), min_price=Min("product_offer__price"), ) ) So if one ProductOffer has price = 500 and price_promo = 2000 and the other ProductOffer has price = 100 and price_promo = 3000, it will annotate min_price = 100 and price_promo = 2000, whereas I want price = 100 and price_promo = 3000. How would I go about doing this? -
It is good practice to get all object in RetrieveUpdateDestroy Method?
Why we need to get all object in RetrieveUpdateDestroy Method? In real project can I do it just like this Without fear even if there is large data? -
Nginx Proxy Manager and django with nginx
I have a stack Django+Gunicorn+nginx running in docker containers. It is accessible from outside by domain and Port, like web.example.com:1300 . Also, there is Nginx Proxy Manager (NPM) running (uses ports 80 and 443) and succesfully managing some other resources (for example nextcloud). But it doesn't proxy to my django project at port 1300, shows "502 Bad Gateway". In the Proxy Hosts of NPM I've added config: domain names: web.example.com Forward Hostname / IP: nginx_docker_container_name (this way it works with other resources) Forward Port: 1300 Other settings: tried multiple combinations without success (like with and without SSL certificates etc.) Is it possible to proxy using NPM? Sorry if I missed to write some information, actually I do not know what else to state. -
Invalid syntax with Django manage.py createsuperuser remote Terminal Mac
I'm trying to create a superuser on a remote django server. I am running a Mac. On two separate terminals (not within VSCode or any IDE) I have run the following code using ssh and sftp: cd my_dir/src ls # to confirm manage.py is present python manage.py createsuperuser python3 manage.py createsuperuser sudo python manage.py createsuperuser sudo python3 manage.py createsuperuser On ssh, the python commands result in: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax On ssh, the python3 commands result in: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? On sftp, both python and python3 commands result in Invalid command. I have also tried: python manage.py shell (here) sudo -i (here) Any other ideas? Thank you in advance!