Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Missconfigures Django settings, ModuleNotFoundError: No module named 'DeveloperRoad'
I'm making a django blog app and I created a Custom User, modifying the AUTH_USER_MODEL constant in the settings.py file. But the database drop an IntegrityError, so I though it was that the configuration file wasn't being imported, and I did the following command,with virtualenv activated: export DJANGO_SETTINGS_MODULE=DeveloperRoad.settings My project app is named DeveloperRoad and the settings file is settings,so I'm not sure what I'm doing wrong. My project structure is the following: DeveloperRoad ├── blog │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── templates │ │ └── blog │ │ ├── add_category.html │ │ ├── add_post.html │ │ ├── author.html │ │ ├── categories.html │ │ ├── categories_list.html │ │ ├── delete_post.html │ │ ├── details.html │ │ ├── edit_post.html │ │ └── index.html │ ├── templatetags │ │ ├── extra_filters.py │ │ ├── __init__.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── DeveloperRode │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── members │ ├── admin.py │ ├── apps.py │ ├── backends.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ … -
preventDefault doesn't always work and the event is executed
I have encountered such a problem that the cancellation event of the form submission does not always work, namely in 30% of cases the event is not cancelled. I send a request by GET method to Django server and get json from it. In 70% of the cases I get the json and my function is already called which handles that json. But in the other 30% I get the json and it is immediately displayed on the screen and I get this text in the console: "content.js:200 JSON Formatter: Type "json" to inspect." Can you please tell me why this happens and how to fix it? let form=document.querySelector('form') form.onsubmit=(e)=>{ e.preventDefault(); setTimeout(()=>{ fetch(form.action, { method: "GET", }) .then(response => response.json()) .then(function(json) { if (json.status){ caseFormation(json) } }) .catch(function(error) { console.log(error) }); },1000) } -
django reathenticate middleware
as a relative noob to django I have been creating a users app. I would like a logged in superuser to have to reauthenticate if they access the admin area having used the rest of the app. I am trying this custom middleware that I have written. Is there a django integrated solution to this problem already, and are there any issues that you can see with my code? from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth import logout import re class ReauthenticateMiddleware: def __init__(self, get_response): self.get_response = get_response self.pages = [] # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_superuser: match = re.match(r'/admin/', request.path) if len(self.pages) and self.pages[-1] is not None and match is not None: referred = re.match(r'/admin/', self.pages[-1]) if referred is None and match is not None: messages.add_message(request, messages.INFO, 'You must reauthenticate') logout(request) self.pages = [] return redirect('/admin/login/') if request.path[-1] == '/': self.pages.append(request.path) response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response I have the custom middleware on the python path and have added it to settings … -
'relation "django_site" does not exist' only when running Django tests in GitHub Actions
I have a Django 3.1 project with an Admin class like this really simple example: from django.contrib import admin from .models import Book class BookAdmin(admin.ModelAdmin): def book_title(self, obj): return obj.title admin.site.register(Book, BookAdmin) And I test that class: from django.contrib.admin.sites import AdminSite from django.test import TestCase from myapp.admin import BookAdmin from myapp.models import Book class BookAdminTestCase(TestCase): def test_book_title(self): book = Book(title="Hello") book_admin = BookAdmin(Book, AdminSite()) self.assertEqual(book_admin.book_title(book), "Hello") This works fine when I run tests (./manage.py test) on my local development site. But when I run tests in a GitHub Action step... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...while other tests all work fine, tests using the AdminSite() call fail with: psycopg2.errors.UndefinedTable: relation "django_site" does not exist 196 LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... These tests use the same Django settings as when run locally. If I run migrations in the GitHub Actions step before I run the tests... - name: Run Tests run: | pipenv run ./manage.py collectstatic --verbosity=0 --noinput pipenv run ./manage.py migrate --verbosity=0 --noinput pipenv run ./manage.py test env: DJANGO_SETTINGS_MODULE: config.settings.tests # etc ...this error doesn't occur, so I can get round this, but … -
charfield Connect to another model charfield (django)
I have a question answer quiz. I have 2 models of question and answer. The answer model I have related to the reading model. But in html I could not figure out how to build it properly. I want something like that. Show the question and below the question be the answer model charfield "answer" then check if the answer is equal to the question answer "answer_question". How do I guess I have a problem in vieweb. If you can help me, thanks in advance. for example (image) this is code -> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def _unicode__(self): return unicode(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if … -
Search by foreign key in admin
models.py class Supplier(models.Model): name = models.CharField(blank=True, max_length=50,) city = models.CharField(blank=True, max_length=50) email = models.CharField(blank=True, max_length=50) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=100) DDT = models.FileField(upload_to="DDT/%Y/%m/%d") fattura = models.FileField(upload_to="DDT/%Y/%m/%d") admin.py @admin.register(Supplier) class SupplierModelAdmin(admin.ModelAdmin): model = Supplier @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): model = Product list_display = ['supplier'] search_fields = [ 'supplier'] when i search for a supplier , django return an error : Related Field got invalid lookup: icontains -
Django twitter clone Following and Follower problem
Hy, I am trying to make a twitter clone using django however I am having issues implementing following and follower system. Suppose I have 2 users A and B. If A follows B, B should be in user A following List furthermore user A should be in user B followers List. However my code seems to implement the reverse and I am confused. e.g I if I follow elon musk he would be in my following list but I would be in his followers list Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True, max_length=30) profile_picture = models.ImageField(upload_to="images/profile/",default='default.png') following = models.ManyToManyField(User, symmetrical=False, blank=True,related_name='all_following') followers = models.ManyToManyField(User, symmetrical=False, blank=True, related_name='all_followers') def __str__(self): return str(self.bio) def get_absolute_url(self): return reverse('home') def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print('Profile Created') post_save.connect(create_profile,sender=User) def update_user_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() print('Profile Updated') post_save.connect(update_user_profile, sender=User) def profile_picURL(self): try: url = self.profile_pic.url except: url = " " return url HTML CODE SNIPPET <div class="column3"> {% for user in users%} {% if not request.user == user%} <div class="follow-users"> <h5>{{user.username}}</h5> <div class="follow-user"> <div> <span>{{user.all_followers.all.count}} followers</span> <span>{{user.all_following.all.count}} following</span> <p><a href="{% url 'view_user_profile' user.id %} ">View {{user.username}} profile</a></p> </div> <form action="{% url 'follow_unfollow_user' user.id %}" method="POST" … -
divisibleby requires 2 arguments error in django
i am probably making a dumb mistake but why does the divisibleby template tag give me an error that it needs two arguments for me when i have seen many others use one argument and get it to work. here is the full error: divisibleby requires 2 arguments, 1 provided templates: {% for item in posts %} {% if item in ads and forloop.counter|divisibleby 5 %} //print ads {% endif %} //print products {% endfor %} -
Django Signal For Updating User
View def transfer(request): if request.method == 'POST': t_form = TransferForm(request.POST, instance=request.user.profile) if t_form.is_valid(): t_form.save() messages.success(request, f'Amount sent!') else: t_form = TransferForm(instance=request.user.profile) context = locals() return render(request, 'transfer.html', context) Models.py from django.contrib.auth.models import User from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=400, default='Hi! I am new :D') image = models.ImageField( default='default.png', upload_to='profile_pics') balance = models.IntegerField(User, default=10) def __str__(self): return f'{self.user.username} Profile'``` class Transfer(models.Model): to_user = models.ForeignKey(User, related_name='receiver', on_delete=models.CASCADE) from_user = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) amount = models.IntegerField(default=0) def __str_(self): return f'{self.to_user.username} Transfer' def transferred(sender, instance, **kwargs): Transfer.to_user = User.objects.first() Transfer.amount = 35 Transfer.amount += Transfer.to_user.profile.balance Transfer.to_user.save() post_save.connect(transferred, sender=Transfer) Form: class TransferForm(forms.ModelForm): class Meta: model = Transfer fields = ['to_user', 'from_user', 'amount'] What's wrong here? What to do so that when I enter the transfer class fields using TransferForm, the to_user's (who is the user whom im sending the amount) balance field updates with the amount we sent? -
Prevent Dropdown menu from closing if I click a menu item
I have a drop down menu in sidebar and it has links as menu items. When I click a menu item(link) then link works fine but drop down menu gets closed. But I want that dropdown menu stay opened even after clicking a menu item. HTML Code: <button class="dropdown-btn button">Products <i class="fa fa-caret-down"></i> </button> <div class="dropdown-container"> <a href="{% url 'shop:admin_products_list' %}">View Products</a> <a href="{% url 'shop:admin_product_create' %}">Add New Product</a> </div> I tried these two following ways: $('div.dropdown-container a').on('click', function(e) { e.preventDefault(); }); $('div.dropdown-container a').on('click', function(e) { e.stopPropagation(); }); But these two ways did not work. Please help me to resolve it. -
How to extend user model for Social_auth uisng pipeline?
I have successfully implemented the social_auth package for django and it is successfully populating the fields in postgres. I am trying to extend the user models so that i can add some additional data while creating the account by user. This is what i could come up with, till now. I have almost tried all the available resources online available but are not very helpful in this case. settings.py #pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'django_social_app.pipeline.requestprofiledata', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) models.py from django.db import models from django.contrib.auth.models import User, auth # Create your models here. class profiledata(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) #first_name =models.CharField(max_length=120) #last_name =models.CharField(max_length=120) #email =models.CharField(max_length=120) registeredemail = models.CharField(max_length=120) mobile = models.CharField(max_length=10) instname = models.CharField(max_length=10) idproof = models.FileField(upload_to='documents/') profiledatacomplete = models.BooleanField() views.py def getprofiledata(request): return render(request,'createCertificates/profile.html') pipeline.py from django.shortcuts import redirect from .models import profiledata #from socia.pipeline.partial import partial from django_social_app import views from social_core.pipeline.partial import partial @partial def requestprofiledata(strategy, details, user=None, is_new=False, *args, **kwargs): print(details) print(type(user)) #print(user.first_name,"..............") #print(user.registeredemail) test = 0 #if user and user.email and test != 0: if test == 1: return #elif is_new and not details.get('email'): else: registeredemail = strategy.request_data().get("registeredemail") #user['registeredemail'] = strategy.request_data().get("registeredemail") mobile = strategy.request_data().get("mobile") instname = strategy.request_data().get("instname") idproof = strategy.request_data().get("idproof") ''' … -
Django filter a prefetched queryset returning an empty list
In my app I have some Users and Groups, that are related by a many to many relation through GroupMember. class User(models.Model): ... class Group(models.Model): ... users = models.ManyToManyField(User, through='groups.GroupMember', related_name='groups') class GroupMember(models.Model): ... user = models.ForeignKey(User, related_name='group_members', on_delete=models.CASCADE) group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE) Now I am trying to build an endpoint that retrieves a list of user instances that are in any one of the groups that your user is in. So if user A and B are in group1, user A and C are in group2, and C and D are in group3, retrieving the users as A would return B and C (since those are in groups with A). That filter part can be done in multiple ways, but the part where I am stuck is how to show which groups were the cause of the relation. I tried to use prefetch_related with a custom filter, to fetch only the groups that have user A in them, like this: User.objects.exclude(id=user.id).annotate( # Annotate the amount of groups related between the users related_group_count=Count('groups', filter=Q(groups__users=user)) ).filter( # Only users that have at least 1 relation with this user related_group_count__gt=0 ).prefetch_related( # Prefetch the specific groups to show Prefetch('groups', User.groups.all(), to_attr='related_groups'), … -
onchange function doesn't work with decimal field
I'm not very familiar with JS, i m working on django project, when a 'price_buy' field is set to DecimalField on models, this function doesn't work, but if FloatField, it works fine. Also if another field is None, i get this error msg (Uncaught ReferenceError: None is not defined at HTMLSelectElement.select.onchange ((index):552)). How i can resolve this problem ? <script type="text/javascript"> document.querySelectorAll("select").forEach((select) => { select.onchange = function(){ var price_buy = 0; const value = this.value; {% autoescape off %} const products = {{ products }} {% endautoescape %} for (var index=0; index < products.length; index++ ) { if (products[index].id == value) { price_buy = products[index].price_buy; } } const name = this.name.replace("product", "price_buy") console.log(price_buy, name); document.querySelector(`input[name=${name}]`).value = price_buy; } }); </script> -
Reverse for 'lajme-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['lajme/(?P<slug>[^/]+)/$']
I need help on this i have no clue why isnt working. I tried different way and still there is more option left that im aware of -----Here is my HTML code: {% for lajme in lajmet %} <article class="media content-section"> <div class="container"> <div class="container"> <img src="media/{{lajme.fotografit}}"> <h4 style="text-align: center; font-family: Comic Sans; font-weight: 700;"><a class="article-title simson" href="{% url 'lajme-detail' lajme.slug %}">{{ lajme.titulli }}</a></h4> <!--<p class="article-content">{{ lajme.detajet|safe|truncatewords:"700"|linebreaks }}</p>--> </div> </div> </article> {% endfor %} --- Here is my model: class Lajmet(models.Model): kategorit = models.ForeignKey(Kategori, on_delete=models.CASCADE) titulli = models.CharField(default='', max_length=350) fotografit = models.ImageField(upload_to='imgs/') detajet = RichTextUploadingField() data_e_postimit = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titulli def get_absolute_url(self): kwargs = {'slug': self.slug} return reverse('lajme-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.titulli self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) ----Here is my View: class LajmetListView(ListView): model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' ordering = ['-data_e_postimit'] paginate_by = 4 # ---------------------------------------------------- class LajmetDetailView(DetailView): model = Lajmet query_pk_and_slug = True -- Here is my path url: path('', LajmetListView.as_view(), name='lajme-home'), path('lajme/<str:slug>/', LajmetDetailView.as_view(), name='lajme-detail'), -
Making dynamic form (adding additional form rows) using Django formset AND select2
I have a form and formset: I want to be able to dynamically add more sets of these forms, including new select2s, from within the formset itself, like adding an 'add row button' from within Django. class FruitForm(forms.ModelForm): region_category = forms.ChoiceField(choices=[('','----')] + [(region, region) for region in Lists.FruitTypes.region_categories], required=False) def __init__(self, *args, **kwargs): super(FruitForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['region_category'].disabled = True self.fields['fruit_type'].disabled = True self.fields['fruit_picked'].disabled = True self.fields['date_picked'].disabled = True if instance.fruit_type: self.fields['region_category'].initial = instance.fruit_type.region_category self.fields['fruit_eaten'].required = False self.fields['date_eaten'].required = False class Meta: model = Fruit fields = ['fruit_id','fruit_type', 'fruit_picked', 'date_picked', 'fruit_eaten', 'date_eaten' ] widgets = { 'fruit_type': autocomplete.ModelSelect2(url='fruit-type-autocomplete', forward=['region_category']), 'date_picked': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'text'}), 'date_eaten': forms.DateInput(format='%Y-%m-%d', attrs={'type': 'text'}) } FruitFormset = modelformset_factory(Fruit, form=FruitForm, extra=1, can_delete=True) Is this possible, and how would I go about it? -
How to save a foreign key field in the Django Rest Framework
I have a issuetracker project where a manager can assign a user to a project. The manager selects a project and a user from dropdowns, clicks submit, and an api call is called in the frontend to send that post data to my django backend APIView assignuser. Assignuser then takes both those values and filters for the correct project and the user, and saves that user to the project user. After checking the projects, I am unable to save a new User to a project as User comes up as null. Is there a specified way in saving foreign keys in the DRF? assignuser class assignuser(APIView): serializer_class = ProjectSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user_name = serializer.get('user') project_name = serializer.get('project_name') user = Users.objects.get(user=user_name) project = Project.objects.get(name=project_name) project.user = user project.save() return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED) else: return HttpResponse("Incorrect Credentials") Project Serializer class ProjectSerializer(serializers.ModelSerializer): user = SignUpSerializer() class Meta: model = Project fields = ('name', 'description', 'user') -
How Import parent package in django website
I have a tree like that : cyberactu ├── models.py ├── __init__.py ├── Scraping │ ├── __init__.py │ ├── scrap.py I'm in scrap.py and i want import a models from models.py. I know I must add the cyberactu folder to my PYTHON PATH. I do like that : import sys sys.path.append(path) After that, if I try to import my models : from models import MyClass That raise a error : django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. After view research this error mean i must link my Django settings to my file. So I do that : export DJANGO_SETTINGS_MODULE=website.settings website is the name of my django project. And that raise a other error: ModuleNotFoundError: No module named 'website' I have a empty init.py file in my cyberactu folder. Thank you for helping me -
Change permission on the basis of button chosen in Django
I am working on DRF and using viewsets for creating APIs. Here I am having one problem: Suppose, I have two buttons in a form i.e. Employee and Manager. If the user clicked on Employee, then it has access to only GET request and if he clicked on Manager, then it has POST, PUT, PATCH permissions. models.py class Employee(models.Model): emp_id = models.AutoField(primary_key=True) emp_name = models.CharField(max_length=30) email = models.EmailField(max_length=254, unique=True) position = models.CharField(max_length=30) team = models.CharField(max_length=30) phone = models.CharField(max_length=20, unique=True) viewsets.py class EmpViewSet(viewsets.ModelViewSet): serializer_class = EmployeeSerializer queryset = Employee.objects.all() permission_classes = [OfficeEngineerPermission] serializers.py class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' custom_permiss.py SAFE_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'HEADER', 'OPTIONS'] class OfficeEngineerPermission(BasePermission): def has_permission(self, request, view): if (request.method in SAFE_METHODS and request.user == 'OfficeEngineer'): return True return Response({'message':'This is not allowed'}) I read all things but getting stuck. Please suggest! -
Django: How to insert variable into path() kwargs
I'm trying to pass a boolean flag to my view: def lesson_detail_view(request, number, **kwargs): pass The documentation has an example of passing in kwargs, but only as hard coded. path('blog/<int:year>/', views.year_archive, {'foo': 'bar'}) My problem is getting the variable into the url pattern. I've tried to insert a variable the same way the path variables work with angle brackets, but it's not working. path('lesson-<number>/', views.lesson_detail_view, kwargs={'show_popup': '<show_popup>'}, name='lesson_detail'), Am I barking up the wrong tree? I feel like this should be pretty straight forward, but I'm not finding anything. -
render() got an unexpected keyword argument 'renderer' or crispy form
add article views.py error add article html -
Some of my HTMLs are not loading CSS file
I have a main.css file where all my styles are and some of my html files are loading them, but not all of them. All my html files extends base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <link href="static/css/main.css" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/2a770f4891.js" crossorigin="anonymous"></script> <title>{% block title %}E-Learning{% endblock %}</title> </head> <body> <input type="checkbox" id="check"> <nav class="nav"> <label for="check"> <i class="fas fa-bars" id="sidebar_btn"></i> </label> {% if user.is_authenticated %} {% if user.first_name != '' or user.last_name != '' %} <b class="top-menu" style="font-size:20px; margin-right:5px;"> Hello, {{user.first_name}} {{user.last_name}}</b> {% else %} <b class="top-menu" style="font-size:20px; margin-right:5px;">Hello, {{ user.username }}</b> {% endif %} {% else %} {% endif %} {% if user.is_authenticated %} <a href="{% url 'logout' %}" class="top-menu">Log out</a> {% else %} <a href="{% url 'login' %}" class="top-menu"> Log In </a> <a href="{% url 'register' %}" class="top-menu">Register </a> {% endif %} </nav> <div class="sidebar"> <a href="{% url 'subject_new' %}" > <span> Add </span></a> </div> <main class="content"> {% block content %} {% endblock content %} </main> </body> </html> and for example my register.html extends base.html (with all css files) just fine {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} … -
ImageField URL is incorrect when reuploading new file or same to the same input form
If I create new listing and upload an image, there is no issue. But When I try to reupload new or same image, it does not get uploaded and its url is pointing to not found file (media/FILENAME) If I just create and, the image gets uploaded and stored at the right directory (media/images). As soon as I try to upload the same or new image,the image does not get uploaded and its url is incorrect or pointing to the nonexistent address (media/FILENAME) My model class Listing(models.Model): title = models.CharField(max_length=64) image = models.ImageField(blank=True, null=True, upload_to="images/") created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Listing {self.id}: {self.title}" def create(request): if request.method == "POST": form = NewListingForm(request.POST, request.FILES) listings = Listing.objects.all() if form.is_valid(): title = form.cleaned_data["title"] image = form.cleaned_data["image"] if image is None: image = "" try: listing = Listing.objects.get(title=title) except Listing.DoesNotExist: listing = None if listing is None and form.cleaned_data["edit"] is False: new_listing = Listing.objects.create(title=title, image=image) new_listing.save() return HttpResponseRedirect(reverse("auctions:listing", args=(new_listing.id,))) elif form.cleaned_data["edit"] is True: existing_listing = Listing.objects.filter(title=title) existing_id = Listing.objects.get(title=title).id existing_listing.update(title=title, image=image) return HttpResponseRedirect(reverse("auctions:listing", args=(existing_id,))) else: return render(request, "auctions/create.html", { "form": form, "error": "Duplicate Item.", "existing_title": title, }) else: return render(request, "auctions/create.html", { "form": NewListingForm() }) else: return render(request, "auctions/create.html", { "form": NewListingForm() … -
Django-wkhtmltopdf - dynamic templates
I'm wondering if it is possible to dynamically assign the template_name based on data provided to my class-based view using a form? for example I have the following form page: views.py def form_generate_pdf(request, project_id): """Form to collect data to insert into PDF""" project = Project.objects.get(id=project_id) if request.method == 'POST': form = PDFForm(request.POST) if form.is_valid(): request.session['field1'] = form.cleaned_data.get('field1') return redirect('myapp:generate_pdf') else: form = PDFForm() context = { 'project': project, 'form': form } And the page that generates the PDF: views.py class Generate_PDF(PDFTemplateView): """Generate a PDF using the values from form_generate_pdf""" filename = "test.pdf" # I want the field below to be dynamic depending on the value of field1 from the view form_generate_pdf template_name = "myapp/pdf.html" cmd_options = { 'page-size': 'Letter', 'viewport-size' : '1920x1080', 'footer-left' : '[page]/[topage]', 'no-outline' : True, } def get_context_data(self, **kwargs): context = super(Generate_PDF, self).get_context_data(**kwargs) field1 = self.request.session['field1'] context['field1'] = field1 } I would say I'm intermediate with django but I'm still fairly new to python and django in general (~5 months of playing now), I don't seem to have enough understanding to figure out how to insert some logic into the Generate_PDF class to programatically select the template type. Something like: if field1 = 'this': template_name = 'myapp/pdf_1.html' … -
How to validate data entered in the sign up form created in Django?
I have created a registration form using the class models.User (refer) in Django as follows: from Django.shortcuts import render, redirect from django.contrib.auth.models import User def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password == confirm_password: # some code user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('login') else: return redirect('register') return render(request, 'register.html') My problems: Now I want to make Full Name as optional but all other fields as required, also I want to apply length constraint on my fields, how can I do that? As this is an inbuilt model (class models.User), I am not sure how to set blank=True or use max_length for any field. Also I want to remove the spaces (if any) at the end and beginning of the entered data, before saving it using user.save() (e.g. if someone entered the name as " abc efg " I want to save it as "abc efg"). Basically, I want to use .is_valid() feature of the Django forms. I even tried doing that as: from django.shortcuts import render, redirect from django.contrib.auth.models import User def register(request): if request.method == 'POST': form = User(request.POST or None) if form.is_valid(): #my code … -
How to check for user authentication in Django's class-based view with get_context_data
When using function based views in Django, I normally would check for user authentication with: if not self.request.user.is_authenticated: return HttpResponseRedirect('/path/to/redirect') Now I am trying to use Class based views instead but I don't know how to implement the authentication if I am using the get_context_data() method instead of just get(). class MyGenericView(generic.ListView): model = models.MyModel template_name = 'path/to/template.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['foo'] = 'bar' return context