Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to print this model data in template djnago?
i have a model named item as follows: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() i have a model named as Bargain as follows: class Bargain(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) item = models.ForeignKey( Item, on_delete=models.CASCADE ) bprice = models.FloatField() class Meta: constraints = [ models.UniqueConstraint( fields=['item', 'user'], name='unique_user_item') ] and i am passing this model data in the template "product.html" as follows; class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_bargain(self, request): if request.user.is_authenticated(): print("this is the user ", self.user.pk) return Bargain.objects.filter(item=self.object, user=request.user).first() and i want to access the "bprice" in the template "product.html" so i am doing this on template : This is the Bprice :{{ view.get_bargain.bprice }} but **it shows nothing ** and i also have one object in bargain model named "Bargain object(3) with all neccesory values example : user: admin item:mattalicdot bprice:1799 and i am logined with user admin . can anyone tell me that what is the issue? -
Execute javascript code present inside child template after the main template is rendered
I've a base template which serves as a common structure for child templates. Inside this base template, I've the jQuery library included right before the closing body tag. base template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> . . </head> <body> {% block content %} {% endblock %} <script src="path/to/jQuery/library"></script> </body> </html> Now my child template has the following code child template {% extends 'base_template.html' %} {% block content %} <h1>How you doing?</h1> <script type="text/javascript"> // this code is specific to this template, may not be used in another template // but can't use jQuery here since the library hasn't loaded yet </script> {% endblock %} So how would I go about running javascript code inside child template only after the base template has finished loading the jQuery library? -
Is it possible to remove CommonPasswordValidator when you register an account in Django?
When a password is too common, Django raises the "The password is too common" error. I wanna remove this validation. Is it possible? And how to do it? -
Footballer(model name) matching query does not exist
views.py from django.shortcuts import render from .models import Footballer from django.http import JsonResponse import json def madrid_list(request): player = Footballer.objects.all().order_by('name') return render(request, "players/madrid_list.html", {"players":player}) def madrid_detail(request,slug): players = Footballer.objects.get(slug=slug) return render(request, "players/madrid_detail.html", {"players": players}) def json(request): data = list(Footballer.objects.values()) return JsonResponse(data, safe=False) why it's not showing me the JSON path when I put it in my server? -
How to pass a constructed payload to a ModelViewSet create method
I have a ModelViewSet, of which I have overriden the create function like below - class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, *args, *kwargs): req_data = json.loads(request.body) x = req_data.get('x') response = super().create(request, *args, **kwargs) book_id = response.data['id'] do_foo(book_id, n=x) return response Now in another function I am trying to call this ViewSet's create function. @api_view(['POST',]) def bar(request, *args, **kwargs): req_data = request.data rf = RequestFactory() payload = {'name': "Book1", 'author': "Helen"} mock_req = rf.post('/book', json.dumps(payload), content_type='application/json') vs = BookViewSet() return vs.create(mock_req) This is giving me an error - AttributeError: 'WSGIRequest' object has not attribute 'data' at this line - response = super().create(request, *args, **kwargs) -
How can I Display data of Model field last_bid(Foreign Key) to template
I am working on an Auction website using Django. I am trying to display data of the Last_bid field which is connected to Bid table with a foreign key. I tried many ways but nothing worked out. The models.py file is: from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.base import Model from django.db.models.deletion import CASCADE from django.db.models.fields import CharField from django.utils import timezone class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return f'{self.category}' class AuctionListing(models.Model): item_name = models.CharField(max_length=100) item_image = models.ImageField(upload_to="products", null=True, blank=True) detail = models.TextField() price = models.IntegerField() last_bid = models.ForeignKey('Bid', on_delete=models.CASCADE, blank=True, null=True, related_name='lst') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='publisher_listing', null=True, blank=True) watchers = models.ManyToManyField(User, blank=True, related_name='watched_list') pub_date = models.DateTimeField(auto_now=True, null=True) deadline = models.DateTimeField(null=True) list_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='sortion') closed = models.BooleanField(default=False) def __str__(self): return f'{self.item_name} - {self.price}' class Bid(models.Model): bid = models.IntegerField() user = models.ForeignKey(User, on_delete=CASCADE) auction = models.ForeignKey(AuctionListing, on_delete=CASCADE) bid_date = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.bid}-{self.auction}' class Comment(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) com = models.TextField() pub_date = models.DateField() com_item = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name='get_comment') def __str__(self): return f'{self.user} - {self.pub_date}' Views.py: from django.contrib.auth import authenticate, login, logout # from django.contrib.auth.decorators import login_required from django.db import IntegrityError, reset_queries from django.http import HttpResponse, HttpResponseRedirect from … -
add filed automatically to form in dajngo CreateView
I have Major model and Course model. when I add course to the course model using ModelForm and CreatView class, I want to add the field automatically. I tried to use form_valid method but it get me this Error: NOT NULL constraint failed: quizes_course.major_id this is the major model: class Major(models.Model): name = models.CharField(max_length=50) years = models.IntegerField(validators=[minMaxVal]) def __str__(self): return self.name def get_absolute_url(self): return reverse("majors") class Meta: verbose_name_plural = "1. Majors" and this is the course model: class Course(models.Model): major = models.ForeignKey(Major, on_delete=models.CASCADE) year = models.IntegerField(validators=[minMaxVal]) name = models.CharField(max_length=100) def __str__(self): return f'{self.major.name}_{self.year}_{self.name}' def get_absolute_url(self): return reverse("courses", kwargs={"pk": self.major.pk}) class Meta: verbose_name_plural = "2. Courses" and this is the view: class CreateCourse(CreateView): model = Course form_class = CourseCreateForm template_name = 'quizes/create.html' def form_valid(self, form): form.save(commit=False) major = get_object_or_404(Major, id=self.kwargs['pk']) form.major = major.id return super().form_valid(form) -
Set initial values in form passing parameters (kwargs) with view
I want to prefill a form with values taken in a table. First I pass the PK relative to the line where I wan't to get values and build the kwargs list: views.py def NavetteToFicheCreateView(request, pk): navette = Navette.objects.get(id=pk) ref = navette.id attribute_set = navette.famille.pk cost = navette.cost qty = navette.qty etat = navette.etat etat_ebay = navette.etat.etat_ebay ean = get_last_ean() form = NavetteToFicheForm( request.POST, ref=ref, attribute_set=attribute_set, cost=cost, qty=qty, etat=etat, etat_ebay=etat_ebay, ean=ean, ) [...] then I retrieve the kwargs in the form.py and setup my initial values class NavetteToFicheForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.ref = kwargs.pop('ref', 'noref') self.attribute_set = kwargs.pop('attribute_set', 9999) self.cost = kwargs.pop('cost', 0) self.qty = kwargs.pop('qty', 0) self.etat = kwargs.pop('etat', 0) self.etat_ebay = kwargs.pop('etat_ebay', 9999) self.ean = kwargs.pop('ean', 9999) super(NavetteToFicheForm, self).__init__(*args, **kwargs) self.fields['ref'].initial = self.ref self.fields['attribute_set'].initial = self.attribute_set self.fields['cost'].initial = self.cost self.fields['qty'].initial = self.qty self.fields['etat'].initial = self.etat self.fields['etat_ebay'].initial = self.etat_ebay self.fields['ean'].initial = self.ean [...] My problem : some fields like "ref" or "attribute_set" are foreignKeys and are not transmitted when i display the form. For checking my values : print(self.ref) print(self.attribute_set) output 34 2 noref 9999 questions : Why does the "print" displays 2 couples of values ? This looks like as if the "noref" and "999" are taken … -
How to jump to a related model object via Django admin's list_display?
I do have a model Comment that relates to the model Poller via FK relationship. Is there any way I can jump to this related object via the Django admin interface from the Comment's overview? # Models.py class Comment(models.Model): """ A Class for comments made by users to a specific Poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment') user = models.ForeignKey(Account, on_delete=models.CASCADE) vote = models.ForeignKey(Vote, on_delete=models.CASCADE) # Admin.py @admin.register(Comment) class PollerCommentAdmin(admin.ModelAdmin): list_display = ('user', 'created_on', 'poller', 'comment', 'flag_count', 'upvote_count', 'downvote_count', 'is_public', 'is_removed') Now I would like to make the 'poller' column clickable which will then redirect me to this poller object in the admin. -
update in serializer: django rest framework
I have a doubt, how to use update() in serializer? serializers.py def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.is_free = validated_data.get('is_free', instance.is_free) instance.keyarea = validated_data.get('keyarea', instance.keyarea) instance.subject = validated_data.get('subject', instance.subject) beneficiary_data = validated_data.get('beneficiary', instance.beneficiary) instance.beneficiary.set(*[beneficiary_data]) section_data = validated_data.get('section', instance.section) instance.section.set(*[section_data]) instance.image = validated_data.get('image', instance.image) instance.instructor = validated_data.get('instructor', instance.instructor) instance.relevance = validated_data.get('relevance', instance.relevance) instance.difficulty = validated_data.get('difficulty', instance.difficulty) instance.contributor = validated_data.get('contributor', instance.contributor) instance.general_status = validated_data.get('general_status', instance.general_status) instance.review_status = validated_data.get('review_status', instance.review_status) instance.save() return instance I use a lot of lines here to update the course model, is there any other way to simplify this? -
upload multiple files into media-library in django/mezzanine
I'm newbie with mezzanine and I was told to fix the media-library upload problem met by our customers. In the production site of the django-1.8/mezzanine-4.2 application it is possible to upload just one file at time, meanwhile in the developemnt side I can upload as many as I want to. Just noticed that the working development side has a multiple attribute within the input-tag whereas production side doesn't have. Can it be the reason for this and could there be means to fix it be changing configuration ? <div class="file-input-wrapper"> <div class="file-input-result"> <div class="progress hide show-in-progress show-done"> <div class="progress-inner"></div> </div> <div class="button button-error cancel-button hide show-selected"> Remove </div> <span class="status hide show-selected show-in-progress show-done"></span> </div> <label class="button hide-in-progress hide-done"> Browse <input name="Filedata" type="file" multiple /> </label> </div> -
Django - Ordered ManyToManyField
I have 2 models in my Django app: Operation and Job. Job model has a many-to-many relationship with Operation model. I use Job model to run multiple Operations in one go. But I need those Operations to be executed in a specific order. I can use JSONField to store foreign keys in specific order to do this, but is there a better solution for this? Here are my models: class Operation(models.Model): name=models.CharField(verbose_name='Operation name',max_length=50) merger_operation=models.BooleanField(verbose_name='Merger operation',default=False) parser_action=models.ForeignKey(ParserAction,on_delete=models.CASCADE,verbose_name='Parser action') class Job(models.Model): name=models.CharField(verbose_name='Job name',max_length=50) operations=models.ManyToManyField(Operation,verbose_name='Pre-request operations') -
How to print values of model joined through foreign key in django?
I have one Model named as item as follows: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and have a product page called " product.html" which shows the current product information as shown in image :the product page image and i am getting all this data on product.html by the view as follows : class ItemDetailView(DetailView): model = Item template_name = "product.html" and on product.html i am getting data by syntax : <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> this is the one story which is working fine no issues till there **problem starts when i create this Bargain model below ** class Bargain(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) item = models.ForeignKey( Item, on_delete=models.CASCADE ) bprice = models.FloatField() class Meta: constraints = [ models.UniqueConstraint( fields=['item', 'user'], name='unique_user_item') ] *let me explain the purpose of this bargain model. actually this model used to bargain the price of the product and it takes input price from user and updates to the bargain model with the following values User, Item and "bprice" which is … -
Psycopg2 can't adapt type 'tuple' issue occurring intermittently
Recently we upgraded Django & Python version to following Python 3.9.5, Django 3.2, Psycopg2 2.9.1, Httpd 2,4.2, Postgres 12.8 Observed that the Application was failing intermittently with psycopg2.ProgrammingError: can't adapt type 'tuple' error Below are the Query and Params logged before the cursor.execute() is executed {'employer_id': 200176, 'approximate_age_band': ('30-39', '50-59') SELECT month_key as cadence_val, sum(eligible_count) as eligible FROM xyz_table_name WHERE employer_id = %(employer_id)s AND approximate_age_band IN %(approximate_age_band)s GROUP BY 1 ORDER BY 1; Below is complete stacktrace 2021-10-27 05:00:52,280 [ERROR] django.request: Internal Server Error: mobile_report/reports Traceback (most recent call last): File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: can't adapt type 'tuple' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/var/www/service_rest/service/api/views.py", line 375, in mobile_visits data = get_report_data(request, "VisitsReport", src_employer_id) File "/var/www/service_rest/service/api/views.py", line 453, in get_report_data data = get_data(src_employer_id, filter_params, report_key, **params) File "/var/www/service_rest/service/api/views.py", line 466, in get_data data = report_obj.get_data(employer, filter_values, **params) File "/var/www/service_rest/service/reports/pulse/mobile.py", line 49, in get_data rows1, cadence_list = self.get_rows_from_query(cursor, sql1, employer_id, table_name, File "/var/www/service_rest/service/reports/__init__.py", line 1415, in get_rows_from_query cursor.execute(sql, params) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/var/www/pulse_preprod/service/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line … -
Django Admin query with postgres
I have model class TmaskMda02(models.Model): ... class Meta: managed = False db_table = 'public.tmask_mda02' And reponse http ProgrammingError at /admin/rest_app/tmaskmda02/ relation "public.tmask_mda02" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "public.tmask_mda02" ^ Request Method: GET In PGadmin ERROR: relation "public.tmask_mda02" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "public.tmask_mda02" ^ SQL state: 42P01 Character: 35 but if I use this select in PGadmin but without "" resonse is OK SELECT COUNT(*) AS "__count" FROM public.tmask_mda02 -
Django inlineformset - NOT NULL constraint failed: forecasting_forecast.forecast_cost
I have a CreateView with an inline formset that has a forecast_month & forecast_cost for each month of the year, I want it to save all 12 forecasts for each month but I keep getting this error. Ideally it should save 12 Forecast's one for each month Error: NOT NULL constraint failed: forecasting_forecast.forecast_cost (I have deleted & rerun migration) Models.py class Forecast(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) forecast_month = models.CharField(verbose_name="Month", max_length=200) forecast_cost = models.DecimalField(verbose_name="Forecast", decimal_places=0, max_digits=11) Views.py class ForecastCreateView(LoginRequiredMixin, CreateView): model = Forecast fields = ["project"] login_url = "/login/" success_url = '' def get_context_data(self, **kwargs): financialYears = ["July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May", "June"] initial = [{'forecast_month': forecast} for forecast in financialYears] ForecastChildFormset = inlineformset_factory( Project, Forecast, fields=('project', 'forecast_month', 'forecast_cost'), can_delete=False, extra=len(financialYears), widgets={'forecast_month': forms.Select(attrs={'disabled': True})}, ) data = super().get_context_data(**kwargs) if self.request.POST: data['forecast'] = ForecastChildFormset(self.request.POST, initial=initial) else: data['forecast'] = ForecastChildFormset(initial=initial) return data def form_valid(self, form): context = self.get_context_data() forecast = context["forecast"] form.instance.creator = self.request.user if forecast.is_valid(): self.object = form.save() forecast.instance = self.object forecast.save() else: return self.form_invalid(form) return super(ForecastCreateView, self).form_valid(form) -
Django + Postgresql, new instance of a model rewrites previous
I have Order model and OrderDetails model which represents product related to the order. One Order can have many OrderDetails. So I create new order and press button to add new product and this button redirects me to the 'Add product' page powered by OrderDetailsCreateView. I fill form with desired product and press 'add', success.. But not so fast. Now if I check database it has new OrderDetails row related to my order. When I add another product I assume that it must create another row, because primary key is order_id + product_id, but instead it overwrites previous row. I want it to add new rows and not touch previous. OrderDetails model class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING, primary_key=True) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) def get_absolute_url(self): return u'/orders/%d' % self.order.pk OrderDetails form class OrderDetailCreateOrUpdateForm(forms.ModelForm): def __init__(self, already_selected_products, *args, **kwargs): super(OrderDetailCreateOrUpdateForm, self).__init__(*args, **kwargs) self.fields['product'].queryset = self.fields['product'].queryset.exclude(id__in=already_selected_products) class Meta: model = OrderDetails fields = ['product', 'unit_price', 'quantity', 'discount'] OrderDetailsCreateView class OrderDetailsCreateView(LoginRequiredMixin, CreateView): model = OrderDetails template_name = 'orders/orderdetails_create.html' form_class = OrderDetailCreateOrUpdateForm def get_form_kwargs(self, **kwargs): form_kwargs = super(OrderDetailsCreateView, self).get_form_kwargs(**kwargs) emp = get_current_users_employee(self.request.user) … -
django async if else use a thread or sync_to_async
I don't know where the error is if data['msg']: print('in') model = await DB.Myself.filter_data(name__contains='') print('ok') else: print('else') model = await DB.Myself.filter_data(name__contains='') print(model, 'model') In if log in ok In else log else You cannot call this from an async context - use a thread or sync_to_async. Why? Can you help me? -
Why am I getting 'ImageFieldFile' object has no attribute 'pk' when I login?
I am building a backend authentication in Django-Rest_framework using django-rest-auth and REST framework JWT Auth and when I login I keep getting this error. What am I doing wrong? AttributeError at /api/auth/login/ 'ImageFieldFile' object has no attribute 'pk' Request Method: POST Request URL: http://127.0.0.1:8000/api/auth/login/ Django Version: 3.2.8 Exception Type: AttributeError Exception Value: 'ImageFieldFile' object has no attribute 'pk' Exception Location: D:\Python Workspace\Rest_Gama\venv\lib\site-packages\rest_framework_jwt\utils.py, line 86, in jwt_create_payload Python Executable: D:\Python Workspace\Rest_Gama\venv\Scripts\python.exe Python Version: 3.9.7 This is my models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): profile = models.ImageField(default='user_default_m.png', upload_to='profile/', blank=True) dob = models.DateField(auto_now=False, auto_now_add=False, blank=True) This is my serializers.py from rest_auth.serializers import LoginSerializer as RestAuthLoginSerializer from rest_framework import serializers from users.models import CustomUser class CustomUserDetailsSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('pk', 'first_name', 'last_name', 'email', 'profile', 'dob', 'date_joined', 'last_login') read_only_fields = ('pk', 'email', 'date_joined', 'last_login') class LoginSerializer(RestAuthLoginSerializer): username = None -
DRF patch update value in an elegant mannar
I'm trying to implement a patch API using drf. Inside my ViewSet model, I've something like this: def patch(self, request, id: int, format=None) -> Response: # type:ignore profile: Profile = Profile .objects.get(user__id=id) if "username" in request.data: profile.username= request.data["username"] if "dp" in request.data: profile.dp= request.data["dp"] if "location" in request.data: profile.location.append(request.data["location"]) profile.save() I'm quite sure that, this is not the appropriate way. Can anyone suggest to me, how I can implement PATCH in, appropriate manner? If I don't query and send the ID in the request and try to save, it gives me errors regarding relation that, that specific field is not present. Surely it is not, I'm not trying to update it. -
Using Sendgrid and Azure : 550, b'Unauthenticated senders not allowed'
I am trying to send a password reset email to users, via an App we are developping with Django. When trying the App locally, the user can select to reset a pwd if forgotten , input his email into a field and submit, in order to receive an email. The sender email is a business email address. Checking into Sendgrid, I can see the activity log that the email has been processed and delivered. So it seems working. However, when trying to do the same passing via Github, Azure, on https://XXXXXX.azurewebsites.net/en/password_reset/, I get the following : SMTPSenderRefused at /en/password_reset/ (550, b'Unauthenticated senders not allowed', 'nicolas@XXXXX.com') in the log I get the following as well: raise SMTPSenderRefused(code, resp, from_addr) Is there something I am missing with Azure, another key to include. I read through many similar issues, but could not find a suitable response to my problem. The fact Sendgrid works in local but not with Azure make me think I am missing a connection at that level. Otherwise, All other aspects of the App works when hosting it on Azure.. Below are the codes I am using: in settings.py import os ALLOWED_HOSTS = ['XXXXXX.azurewebsites.net'] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') … -
How to properly extend Create method in Model Serializer?
So I wanted to add some information for model fields during saving the object. For example I wanna upload an image and it should be the only required field, so i wanted the rest of the fields (e.g. width, height, name and so on) to be filled during saving the instance. I take it that create method in serializer is where the instance of model is being saved. But it seems to me that copy and past all code from the initial create method seems kinda excesive. I don't want to simply override the method because in that case there's a high chance I lose some validations or something. So are there any ways to extend create method using super() for example? So here is my model: class ImageUpload(models.Model): name = models.CharField(max_length=150, default='test') url = models.URLField(default='None') picture = models.ImageField(upload_to='images/') width = models.IntegerField() height = models.IntegerField() parent_picture = models.IntegerField(default=0) and here's my view: class UploadImageView(generics.CreateAPIView): serializer_class = ImageUploadSerializer And here's my sereializer: class ImageUploadSerializer(serializers.ModelSerializer): class Meta: model = ImageUpload fields = '__all__' def create(self, validated_data): name = 'SomeName' width = 'Width of the uploaded image' height = 'Height of the uploaded image' super().create(validated_data) instance = ImageUpload.objects.create(**validated_data, name=name, width=width, height= height) return … -
Django:Error trying to add data in postgres database
I get an error(The view crud.views.insertEmp didn't return an HttpResponse object. It returned None instead.) whenever I try to insert data to my database through the insert.html template. I;m using postgres as my database. Any assistance in identifying the bug will be highly appreciated. models.py from django.db import models class Employee(models.Model): emp_name = models.CharField(max_length=100) email = models.CharField(max_length=100) occupation = models.CharField(max_length=100) salary = models.IntegerField() gender = models.CharField(max_length=1) class Meta: db_table = 'employee' views.py from django.shortcuts import render, redirect from crud.models import Employee from django.contrib import messages def showEmp(request): employee = Employee.objects.all() context = {"data": employee} return render(request, "index.html", context) def insertEmp(request): if request.method == "POST": if request.POST.get('emp_name') and request.POST.get('email') and request.POST.get('occupation') and request.POST.get('salary') and request.POST.get('gender'): saveRecord = Employee() saveRecord.emp_name = request.POST.get('emp_name') saveRecord.email = request.POST.get('email') saveRecord.occupation = request.POST.get('occupation') saveRecord.salary = request.POST.get('salary') saveRecord.gender = request.POST.get('gender') saveRecord.save() messages.success(request, "Employee " + saveRecord.emp_name + " is added succesfully.") return render(request, "insert.html") else: return render(request, "insert.html") inser.html <center> <h1>Insert data into Postgresql</h1> <hr> <form method="POST"> {% csrf_token %} <table border=""> <tr> <td>Employee Name</td> <td><input type="text" placeholder=" Enter employee name.." name="emp_name""></td> </tr> <tr> <td>Email</td> <td><input type=" text" placeholder="Enter email" name="email"> </td> </tr> <tr> <td>Occupaton</td> <td> <select name="occupation"> <option selected disabled=true>-- Select occupation --</option> <option value="">Programmer</option> <option value="">HR</option> … -
Django: Return URL with modified request object, with new params while keeping the old ones
I'm building a product view page which has a working pagination system. After user clicks on a page button, the back-end should generate a URL which is equal to the current one, but the request.GET params are changed, so for e.g http://localhost:5500/computers/laptops/?manufacturer=Lenovo As you can see there's no page defined, so we have to define it by adding the &p=2 if the user has clicked on the second page, but how can we do it? I've tried to modify the request.GET params, but how then I can generate the url with those new params? def set_page(self, page=1): request = self.request request.GET._mutable = True request.GET["p"] = page -
django: download filtered data as csv
Hej! I have my data from a model in a table (created in the template) and want to download it as csv. My problem is that I can't get my filters applyed in the downloaded csv, it'll always give me the whole list. And I can't get the name of the parent_instititution only '1' if there is one. Does anyone know how to achieve that? Or knows what I'm doing wrong? Any help is appreciated! :) # views.py def download_csv(request): institutions = Institution.objects.all() filter = InstitutionFilter(request.GET, queryset=institutions).qs response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="institutions.csv"' writer = csv.writer(response) writer.writerow(['Name', "Abbreviation", "Parent Institution", "Phone Number"]) for institution in filter.values_list('name', 'abbreviation', 'parent_institution', 'contact_details'): writer.writerow(institution) return response # filters.py class InstitutionFilter(django_filters.FilterSet): name = CharFilter(field_name="name", lookup_expr="icontains") class Meta: model = Institution fields = "__all__" <!-- template.html --> <br> <div class="row collapse {% if show_form %} show {% endif %}" id="form-holder"> <div class="row"> <div class="col"> <div class="card card-body"> <form method="get"> {{myFilter.form.as_p}} <button class="btn-primary" type="submit">Search</button> </form> </div> </div> </div> </div> </br> <div class="row"> <div class="col-md"> <div class="card card-body"> <table class="table table-sm"> <tr> <th>Name</th> <th>Abbreviation</th> <th>Parent Institution</th> </tr> {% for institution in institutions %} <tr> <td>{{institution.name}}</td> <td>{{institution.abbreviation}}</td> <td>{{institution.parent_institution.name}}</td> </tr> {% endfor %} </table> </div> </div> </div>