Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django, how can I access the request object in the form's clean method when using a CreateView?
I'm following the answer from this question, but the request object isn't actually being passed into it: How do I access the request object or any other variable in a form's clean() method? I'm getting this error when I try to submit the form: 'NoneType' object has no attribute 'user' Here is my form code: class MyModelForm(ModelForm): class Meta: model = MyModel fields=['question',] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyModelForm, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = self.cleaned_data['question'] user = self.request.user if user.author.number_of_questions < 1: raise ValidationError("You don't have any questions left") return data Here is my CreateView: class MyModelCreate(generic.CreateView): model = MyModel fields=['question',] def form_valid(self, form): # Code return super(MyModelCreate, self).form_valid(form) def get_success_url(self, **kwargs): # obj = form.instance or self.object return reverse_lazy('articles:thank-you') def get_form_kwargs(self): kw = super(MyModelCreate, self).get_form_kwargs() kw['request'] = self.request # the trick! return kw def get_context_data(self, **kwargs): #Code return context It's my understanding that the get_form_kwargs method in the CreateView is passing in self.request into the request kwarg of the form, which is then being accessed in the clean method of MyModelForm, but when I run this code, I get the error: 'NoneType' object has no attribute 'user' I have no idea why the … -
How to override UpdateView get_queryset django
I'm new to django, and I'm trying to make a simple update form where you can enter the PK of the object to be modified, and have the fields to be modified of the object in the same form, without entering the pk through the url, instead enter the PK from the form previously opened by the url http://127.0.0.1:8001/update/, I am using UpdateView and I try to cancel the get_queryset method, so far what I have achieved is to cancel the method and open the form but I must pass a pk if not it doesn't open I don't know how to make the form open blank. Model: class Lote(models.Model): lote = models.CharField(verbose_name='Lote', max_length=10, primary_key=True) codigo = models.CharField(verbose_name='Codigo', max_length=10, blank=True, null=True) producto = models.CharField(blank=True, max_length=50, null=True, verbose_name='Producto') timestamp= models.DateTimeField(auto_now_add=True) Forms: class LoteForm(forms.ModelForm): class Meta: model = Lote fields = ["lote","producto","codigo"] class LoteFormView(forms.Form): lote = forms.CharField(max_length=20) producto = forms.CharField(max_length=20) codigo = forms.CharField(max_length=20) View: class Update(UpdateView): model = Lote template_name = 'lote/updateview.html' fields = ['lote', 'codigo', 'producto'] success_url = '/update/' def get_object(self, queryset=None): return Lote.objects.get(pk=11111) url : url(r'^update/$', Update.as_view(), name='update'), Result: enter image description here what I want enter image description here I want to open the blank form and then pass … -
Django: Custom User Model Not Showing Profiles with StackedInLine
I have a custom user model which I am trying to associate a profile with. However I've been following other code to do this and I just cant seem to get it to work. admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Trickster_User, User_Profile class ProfileInline(admin.StackedInline): model = User_Profile fields = ['User', 'SkillLevel', 'UserDIfficultyLevel', 'LearnedTricks', 'Follows'] class UserAdminConfig(UserAdmin): model = Trickster_User inLines = [ ProfileInline ] search_fields = ('Email', 'Username', 'FirstName', 'LastName') list_filter = ('Email', 'Username', 'FirstName', 'LastName', 'is_active', 'is_staff') ordering = ('-DateOfJoining',) list_display = ('Email', 'Username', 'FirstName', 'LastName','is_active', 'is_staff') fieldsets = ( ('Personal Info', {'fields': ('Email', 'Username', 'FirstName', 'LastName')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('Email', 'Username', 'FirstName', 'LastName', 'password1', 'password2', 'is_active', 'is_staff')} ), ) admin.site.register(Trickster_User, UserAdminConfig) admin.site.register(User_Profile) models.py: class CustomUserManager(BaseUserManager): def create_superuser(self, Email, Username, FirstName, LastName, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(Email, Username, FirstName, LastName, password, **other_fields) def create_user(self, Email, Username, FirstName, LastName, password, **other_fields): if not Email: raise ValueError('You must provide an email address') Email = … -
How to create dataset from code and "inject" multipolygon to it with Geonode-project?
I have created a new django app form my geonode-project In this app I have a Project Model with a geom (Multipolygon field), It also has a OneToOneField to Dataset. What I want to achieve is: 1 - When a Project is created a new dataset must be created showing the same multipolygon of the project. (Keep reference project-dataset through the dataset OneToOneField field) 2 - When the project geom field is updated, the dataset must update its geometry (Multipolygon) as well I want to know which methods/functions I can use to create a new dataset and “inject” that multipolygon that is coming from project. I want to know how to update the dataset so it can show the new Multypolygon Here is my model definition: from django.utils.translation import gettext_lazy as _ from django.conf import settings from geonode.layers.models import Dataset from django.contrib.gis.db import models class Project(models.Model): name = models.CharField(_("Nombre"), max_length=50, unique=True) geom = models.MultiPolygonField(verbose_name=_("Localización"), srid=4326, blank=True, null=True) dataset = models.OneToOneField(Dataset, verbose_name=_("Dataset"), on_delete=models.CASCADE, related_name="proyecto", blank=True, null=True) -
How to use authenticate method with AbstractUser model django
I`m wrirting site on Django and I need to make a system for registration and authorization of work peepers, for this I use the Django AbstractUser model, registration works well, but authorization does not work, and the authenticate method returns None Here is my JobseekerRegsiterInfo model: class JobseekerRegisterInfo(AbstractUser): username = first_name = last_name = None id = models.BigAutoField(primary_key=True) phone_number = PhoneNumberField() email = models.EmailField(unique=True) full_name = models.CharField(max_length=120) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['phone_number', 'full_name', 'hashed_password'] def __str__(self): return self.full_name My login form: class JobseekerLoginForm(forms.Form): email = forms.EmailField(label='Введіть ваш Email: ', widget=forms.EmailInput(attrs={'class': 'form-control'})) password = forms.CharField(label='Ваш пароль: ', widget=forms.PasswordInput(attrs={'class': 'form-control'})) def clean_email(self): email = self.cleaned_data['email'] # if not select_field_value_from_model(JobseekerRegisterInfo, 'email', email): if not JobseekerRegisterInfo.objects.filter(email=email): raise forms.ValidationError('Неправильно введені email або пароль') return email and view function: def jobseeker_login_view(request): title = 'Авторизація' context = {'title': title} if request.method == 'POST': form = JobseekerLoginForm(request.POST) context['form'] = form if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(request, email=email, password=password) print(generate_password_hash(password)) if user: print(user) else: print('USER IS NONE') else: form_errors = form.errors.as_data() custom_error = custom_error_service(form_errors) context['list_first_error'] = custom_error else: form = JobseekerLoginForm() context['form'] = form return render(request, template_name='jobseeker/jobseeker_login.html', context=context) But only USER IS NONE is displayed in the console, no matter what I do … -
Multiple permission to view/add/change a model class object
I am trying to edit permissions from the admin-site for a specific group in my project. (Specifically the Manager group) I noticed that for this one model class named DeliveryOrderForm, contains two instances of one permission. For example : deliveryorder| delivery order form | can add delivery order form deliveryorder| delivery order form | can add delivery order What I understand is that the first part 'deliveryorder' is referencing the application name, the second part is referencing the model's class name, but I am unsure what the 3rd part is referencing to. These are the attributes for my class DeliveryOrderForm model class DeliveryOrderForm(models.Model): deliveryOrderID = models.AutoField(unique=True,primary_key=True) vendorName = models.CharField(max_length=30) vendorAddress = models.CharField(max_length=200) recipientName = models.CharField(max_length=30) recipientPhone = PhoneNumberField(blank=False) recipientAddress = models.CharField(max_length=200) deliveryOrderStatus = models.IntegerField(default=Status.pending,choices=Status.choices) deliveryOrderDate = models.DateTimeField(default=timezone.now()) I hope someone can help me understand this cause I'm afraid if my model is actually screwed up. -
Can C++ do web development?
Most of the backend languages like python, PHP, java and many more develop websites but can C++ do such. According to me, I think it can't but I'm not sure about that. -
Paginator not resticting number of post that needs to be shown on page Django?
I'm working on my Django blog, and when I go to categories I listed all posts in that category, but for some reason I cannot manage to work pagination. Everything works except one thing, on all pages I can see all posts, but I want to see only 6 posts per page. This is pagination.html that is included in category detail page <div class="mb-30"> <nav aria-label="Page navigation example"> <ul class="pagination justify-content-start"> {% if category_page.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ category_page.previous_page_number }}"><i class="ti-angle-left"></i></a></li> {% else %} <li class="page-item"><a class="page-link" href="#"><i class="ti-angle-left"></i></a></li> {% endif %} {% for i in category_page.paginator.page_range %} {% if category_page.number == i %} <li class="page-item active"><a class="page-link" href="#">{{ i }}</a></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if category_page.has_next %} <li class="page-item"><a class="page-link" href="?page={{ category_page.next_page_number }}"><i class="ti-angle-right"></i></a></li> {% else %} <li class="page-item"><a class="page-link" href="#"><i class="ti-angle-right"></i></a></li> {% endif %} </ul> </nav> </div> This is category_detail.html {% for post in posts %} <article class="col-lg-10"> <div class="background-white"> <div class="post-thumb"> <a href="{{ post.get_absolute_url }}"> <img class="border-radius" src="{{ post.image.standard.url }}" alt=""> </a> </div> <div class="pl-10"> <div class="mb-15"> <a class="meta-2" href="{{ post.category.get_absolute_url }}"><span class="post-in">{{ post.category}}</span></a> </div> <h5 class="mb-15"> <a href="{{ post.get_absolute_url }}">{{ post.post_title … -
Django - Annotate within for loop - what is the difference between my two codes
I am trying to sum up two columns in a view with values() and annotate(). Column 1 Column 2 5 0 5 -2 Currently calling "total" will return the total for each row and not the overall total. Returning in template 5 3 I believe this is because I print the total in a for loop. What confuses me is that I have an almost similar code working perfectly fine in another view. How can I get the total of the several rows together? views def function(request, userprofile_id): venue = UserProfile.objects.filter(user=request.user).values('venue') points_cummulated_per_user_per_venue = Itemised_Loyalty_Card.objects.filter(user=userprofile_id).filter(venue=request.user.userprofile.venue).values('venue__name','timestamp').annotate(sum_points=Sum('add_points')).annotate(less_points=Sum('use_points')).annotate(total=F('add_points')-F('use_points')).order_by('-timestamp') return render(request,"main/account/venue_loyalty_card.html",{'venue':venue,'points_cummulated_per_user_per_venue':points_cummulated_per_user_per_venue}) template {%for model in points_cummulated_per_user_per_venue %} Total: {{model.total}} {%endfor%} -
Creating an "incomplete" Django class for a user to fill in
I have a database representing financial transactions. Columns representing payee and category are non-optional. However, part of my app's functionality will be to ingest external spreadsheets of transactions which do not already have payee and category information. I would then populate a form where the user will select correct payees and categories through drop-down menus, and then save the completed information to the database. Is the correct approach to simply create two separate but equivalent classes (see below)? Or is there some way to make one a sub-class to another, despite the fact that one is connected to a database and the other is not. # An initial class representing a transaction read from an Excel sheet # Payee and category information are missing at this stage, but will be filled # in by the user later on class TransactionFromSpreadsheet: def __init__(self, date, amount): self.date = date self.amount = amount self.payee = None self.category = None # The Django class that will be instantiated once all the user has completed all # necessary information class Transaction(models.Model): date = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2) category = models.ForeignKey('Category', on_delete=models.CASCADE) payee = models.ForeignKey('Payee', on_delete=models.CASCADE) -
Django and use calculated values in QuerySet
I have a function to convert net to gross price like this. taxRate is the tax value. e.g. 23, 8, 5, 0 def gross(netValue, taxRate: int, currencyPrecision=2): if taxRate > 0: return round(netValue * (100 + taxRate) / 100, currencyPrecision) else: return round(netValue, currencyPrecision) In my model I have a class that is order items with fields: netPrice and taxId. class OrderPosition(models.Model): posNumber = models.AutoField(auto_created=True, primary_key=True, editable=False, blank=False) order = models.ForeignKey(OrderHeader, on_delete=models.PROTECT) product = models.ForeignKey(Product, on_delete=models.PROTECT) quantity = models.DecimalField(blank=False, max_digits=3, decimal_places=0) netPrice = MoneyField(blank=False, max_digits=6, decimal_places=2, default=Money("0", "PLN")) taxId = models.IntegerField(blank=False, default=0) The value of the entire order with a given ID can be calculated as follows: def getNetValue(self): posList = OrderPosition.objects.filter(order_id=self.orderID) if posList: return str(posList.aggregate(netValue=Sum(F('quantity') * F('netPrice'), output_field=MoneyField()))['netValue']) else: return "0" Question: Can I use my function "gross()" in a query to calculate the gross value of an order in a similar way to calculate the net worth? I suppose the aggregation function is performed on the database side (mySQL in my case) and we can only use what is understandable at the database and SQL level. -
Im making a project where im using django as backend and react as frontend and im receiving following error when i run server in django
The frontend is supposed to be showing products but its not and the error in django is this: [enter image description here](https://i.stack.imgur.com/hCjRE.jpg) X-----------------------------------------------------------------------------------------------X These are few important components of my settings.py file where i think the error is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.Common.Middleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] / STATIC_URL = '/static/' CORS_ALLOW_ALL_ORIGINS = True I tried searching for error but havent found a solution. -
tr:nth-child(even) not working with xhtml2pdf
I'm trying to add a background color to even rows in a table in HTML. I'm using xhtml2pdf to convert the html to pdf to serve with a django backend. The styles on the even rows don't seem to be working <html> <head> <style type="text/css"> tr:nth-child(even) { background-color: blue; } </style> </head> <body> <main> <table> <thead> <tr> <th>Heading/th> <th>Heading</th> <th>Heading</th> </tr> </thead> <tbody> {% for result in data.results %} <tr> <td>{{result}}</td> <td>{{result}}</td> <td>{{result}}</td> </tr> {% endfor %} </table> </main> </body> </html> -
how to show month fields with Salesmen commission in ordering product
serializer.py[view.py]|(https://i.stack.imgur.com/sSfir.png)[error]|(https://i.stack.imgur.com/UObDc.png) how to show month fields with order -
model form doesn't render form again when form is not valid
I added Min and Max Value validators to my Django model and then when I enter a value out of this range, instead of rendering form again,it raises a value error. ValueError: The view cars_form.views.rental_review didn't return an HttpResponse object. It returned None instead. [14/Jan/2023 21:44:50] "POST /cars_form/rental_review/ HTTP/1.1" 500 74599 It should be HTTP/1.1" 200 This is my Code models.py: from django.db import models from django.core.validators import MinValueValidator,MaxValueValidator class Review(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) forms.py : from django import forms from .models import Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = "__all__" views.py: from django.shortcuts import render,redirect from django.urls import reverse from .forms import ReviewForm def rental_review(request): if request.method=='POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('cars_form:thank_you')) # my template else: form = ReviewForm() # making an object return render(request,'cars_form/rental_review.html',context={'form':form}) if the form is not valid it must go on else statement but it doesn't and idk why. -
Doesn't "__str__()" work properly in "admin.py" for Django Admin?
For example, I define __str__() in Person model as shown below: # "models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): # Here return self.first_name + " " + self.last_name Then, I define Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, the full name is displayed in the message and list in "Change List" page: But, when I define __str__() in Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def __str__(self): # Here return self.first_name + " " + self.last_name Or, when I define __str__() then assign it to list_display in Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('__str__',) # Here def __str__(self): # Here return self.first_name + " " + self.last_name The full name is not displayed in the message and list in "Change List" page: So, doesn't __str__() work properly in Person admin? -
Django filter by related field with annotating the last added items
I have one model with two foreignkeys my model : class Price(models.Model): part= models.ForeignKey(Part, on_delete=models.CASCADE, null=True, blank=True) seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True) price = models.FloatField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True, blank=True) I have 4 vendors [seller], each [item] has an unlimited price history [price\date] that gets added every day individually. I need the right query to get : [Latest price ordered by date for each seller per item] So the query should return only 4 items Example : qs = Price.objects.values('part__name', 'seller__name').annotate(new_price=Max('date')) result : <QuerySet [{'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__name': 'Amazon', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pac k of 8 Spark Plugs (TR55)', 'seller__name': 'Carid', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__nam e': 'Ebay', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__name': 'Rockauto', 'new_price': datetime.dat e(2023, 1, 14)}]> Is the corrent qs but i can't access [price] field, if you include it in values the qs returns more than 4 results. -
How to deploy a pywebio application using Flask, (so that I can deploy in websites like heroku etc)
I have my pywebio application running on localhost. ` import openai import pyperclip from pywebio.input import * from pywebio.output import * from pywebio.session import * from pywebio.pin import * import pywebio openai.api_key = "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" def home(): put_image('https://upload.wikimedia.org/wikipedia/commons/4/4d/OpenAI_Logo.svg',width='50%',height='50%') evenorodd() def evenorodd(): engines_dict={"text-davinci-003":3200, "text-curie-001":1600, "text-babbage-001":1600, "text-ada-001":1600} myinp=input_group("ASK GPT-3",[ input("", placeholder='Enter any question', required=True,help_text="",name="question"), radio("Choose an engine",name="engine", options=["text-davinci-003", "text-curie-001", "text-babbage-001", "text-ada-001"],required=True)]) put_text(myinp["question"]).style('color: green; font-size: 20px;font-weight: 600; padding-top:20px') with put_loading(shape='grow',color='success'): response = openai.Completion.create( engine=myinp["engine"], prompt=myinp["question"], temperature=0.5, max_tokens=engines_dict[myinp["engine"]], top_p=1, frequency_penalty=0, presence_penalty=0 ) toast("Success") put_button("copy",onclick=lambda:(toast("Copied"),pyperclip.copy(response.choices[0].text)),color='success',outline=True).style('float: right') put_text(response.choices[0].text).style('background-color: rgb(240, 240, 240);padding: 10px;border-radius: 8px;') put_button("Ask another Question",onclick=evenorodd).style('position: relative;bottom: 0') pywebio.start_server(home,port=90, debug=True) ` How to convert this into Flask and deploy ?? I tried to search on net but they are rendering various templates in Flask. Help me with this I tried running on my localhost, but many errors are occurring. Anyone help me with this. -
Can I set a models.imageURL as background image in a html container?
I'm trying to create a blog on Django in my learning process and I was wondering if it's possible to use a models.imageUrl as a background image for a post template. I'm not even sure it's possible to do so, is it? thanks in advance! this is my styles code insinde my html div: <div class="showcase" style="background-image: url(/static/media/image.jpeg); background-size: cover; background-position: center; padding: 140px;"> -
command docker-compose build
how fix this problem docker run as administrator, containers works, but command @docker-compose build@ nope error - acces is denied (i working pycharm) I tried to run Linux through ubuntu and immediately thought that the problem was in the docker, so I surfed the Internet for a long time in search of a solution to the problem, but I did not find it -
Setup multiple private repositories cpanel
How can I setup access for multiple private repositories in Cpanel? I've tried many tutorials and documentation. Here is one of them: https://docs.cpanel.net/knowledge-base/web-services/guide-to-git-set-up-access-to-private-repositories/ But I'm always got this error: Permission denied (publickey). fatal: Could not read from remote repository. It seems like we can only use the default name (id_rsa). I've tried this code: ssh-keygen -t rsa -b 4096 -C "username@example" It works fine. But it will generate the default (which is id_rsa). This means that we can't deploy multiple private repos, right? Because we can only use "id_rsa". So is it possible to create an ssh key without a default name? Also, how to create multiple private repos in Cpanel? -
don't show images in django crud
don't show images in django crud this is the html view and models tanks for help enter image description here <tbody> {% for emp in employees %} <tr> <th scope="row">{{ emp.emp_name }}</th> <td>{{ emp.emp_email }}</td> <td>{{ emp.emp_contact }}</td> <td>{{ emp.emp_role }}</td> <td>{{ emp.emp_salary}}</td> <td> <a style="margin-right: 30px;" href="{% url 'edit-employee' emp.id %}">EDITAR</a> <a href="{% url 'delete-employee' emp.id %}">ELIMINAR</a> </td> <td> {%if venue.venue_image%} {{venue.venue_image.url}} {%endif%} </td> </tr> {% endfor %} </tbody> class Employee(models.Model): emp_name = models.CharField(max_length=200) emp_email = models.EmailField() emp_contact = models.CharField(max_length=20) emp_role = models.CharField(max_length=200) emp_salary = models.IntegerField() venue_image = models.ImageField(null=True, blank=True, upload_to="images/") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.emp_name i want put a image here enter image description here -
The 'image' attribute has no file associated with it. Django serilizer
this is my code class Brand(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(upload_to=generate_filename_brand_image) #over write add_to_explore = models.BooleanField(default=False) def __str__(self): return self.name class Item(models.Model): brand = models.ForeignKey('core.Brand', on_delete=models.CASCADE, null=True ,blank=True) class ItemSerializers(serializers.ModelSerializer): brand_logo = serializers.CharField(source='brand.logo.url') class Meta: model = Item fields = ['id','brand_logo'] if image None I got this erorr The 'image' attribute has no file associated with it. How to handel this erorr -
save file in media folder on server django
so i´ve created a pdf document which should be saved in media/postings. the path is already in the function, but the pdf is not saved there but in the main project folder. what did i overlook here? a little explanation for the def: the post is created and uploaded to the feed, while the image in the post is renamed and put into another folder. Also, a pdf is created, containing the posted material. How do i determine where this pdf goes on the server? i thought it is solved with the path_name and path_file but it doesn't work. thanks in advance. def post_create(request): if request.method == 'POST': form = PostCreateForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['num_post'] = Post.objects.count() + 1 Post.objects.create(**form.cleaned_data) else: form = PostCreateForm() return render(request, 'index.html', {'form': form}) def upload(request): if request.method == 'POST': image = request.FILES.get('image_upload') caption = request.POST['caption'] num_post = Post.objects.count()+1 new_post = Post.objects.create(image=image, caption=caption, num_post=num_post) new_post.save() #create pdf buffer = io.BytesIO() x_start = 100 y_start = 10 folder_path = f"media/postings/post{num_post}.pdf" folder_name = os.path.basename(folder_path) print(folder_path) p = canvas.Canvas(folder_name, pagesize=A4,) #p == request.FILES.get('postings') p.drawImage(ImageReader(image.file), x_start, y_start, width=420, preserveAspectRatio=True, mask='auto') p.drawString(150, 650, new_post.caption) p.drawString(100, 650, "caption:") p.drawString(100, 170, str(new_post.created_at)) p.drawString(200, 700, str(num_post)) p.drawString(100, 700, "post no.:") p.drawString(250, 700, "//") … -
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max"
I changed the data type of a field "max" in my model from text to float and I got this error when I run python3 manage.py migrate after makemigrations. What's the solution please? Running migrations: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max". The above exception was the direct cause of the following exception: django.db.utils.DataError: invalid input syntax for type double precision: "max my original model: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.TextField(blank=True, null=True) max = models.TextField(blank=True, null=True) unit = models.TextField(blank=True, null=True) my model after the change:: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.FloatField(blank=True, null=True) max = models.FloatField(blank=True, null=True) unit = models.TextField(blank=True, null=True)