Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why it is giving 403 forbidden error once I submit the form?
I was following a newsletter app project. I got 403 error.It is storing data but once i click the subscribe button it shows this error.But unless I remove response=sg.send(message) and obisously not sending the mail.But without this line, app will be incomplete. project/letter/views.py def random_digits(): return "%0.12d" % random.randint(0, 999999999999) @csrf_exempt def new(request): if request.method =='POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails= sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), sub.email, sub.conf_num)) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return render(request, 'index.html', {'email': sub.email, 'action': 'added', 'form': SubscriberForm()}) else: return render(request, 'index.html', {'form': SubscriberForm()}) project/letter/models.py class Subscriber(models.Model): email = models.EmailField(unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" project/urls.py from django.contrib import admin from django.urls import path from letter import views urlpatterns = [ path('admin/', admin.site.urls), path('new/', views.new, name='new') ] templates/index.html <div class="container"> <div class="col-12"> <h1>Email Newsletter</h1> </div> <div class="col-12"> {% if email %} <p>{{ email }} has been {{ action }}.</p> {% endif %} </div> {% if form %} <div class="col-12 … -
Django, ajax request and JsonResponse
I'm trying to get the data obtanied filling a form utilizing a ajax call. First of all I have created my models.py: class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) numero_lavorazione=models.ForeignKey(Lavorazione, on_delete=models.CASCADE, null=True) The forms.py: class CostiMaterialeForm(forms.ModelForm): class Meta: model = Costi_materiale fields = "__all__" And finally my views.py: class CostiRicavi(ListView): model = Costi_materiale template_name = 'commesse/costiericavi.html' context_object_name = 'costs' def get_context_data(self, **kwargs): context = super(CostiRicavi, self).get_context_data(**kwargs) context.update({ 'form_1': CostiMaterialeForm(), }) return context class Costi_materiale(View): def get(self, request): codice_commessa1 = request.GET.get('codice_commessa', None) numero_lavorazione1 = request.GET.get('numero_lavorazione', None) obj = Costi_materiale.objects.create( codice_commessa = codice_commessa1, numero_lavorazione = numero_lavorazione1, ) info = { 'id':obj.id, 'codice_commessa':obj.codice_commessa, 'numero_lavorazione':obj.numero_lavorazione, } data = {'info': info} return JsonResponse(data) After I have created my template, in which I have put a form (using crispy) and a jquery code, like the following: <form id="addCostoMateriale"> {% csrf_token %} <div class="form-row"> <div class="form-group col-2 0 mb-0" > {{form_1.codice_commessa|as_crispy_field}} </div> ......... $("form#addCostoMateriale").submit(function() { var codice_commessaInput = $('input[name="codice_commessa"]').val().trim(); var numero_lavorazioneInput = $('input[name="numero_lavorazione"]').val().trim(); if (codice_commessaInput && numero_lavorazioneInput) { // Create Ajax Call $.ajax({ url: '{% url "costi_materiale" %}', data: { 'codice_commessa': codice_commessaInput, 'numero_lavorazione': numero_lavorazioneInput, }, dataType: 'json', success: function (data) { if (data.info) { appendToUsrTable(data.info); } } }); } else { alert("All fields must have a valid value."); } … -
Django page freezes after form submission
recently I am facing an issue that on a page where I have 3 forms on a blog post (they all have separate views to handle them) after I want to submit a comment the page freezes and I need to close the page. This happened on both Chrome and Safari. I do not know where the issue is as I see no error on the console, I can see the POST being successful on the terminal and I do not see any errors overall. My javascript that handles the Ajax: $(document).ready(function(){ $('textarea').keyup(function (e) { var rows = $(this).val().split("\n"); $(this).prop('rows', rows.length); }); var s = 0; $("#post-comment-button-viewer").click(function(){ if(s == 0){ $('textarea').val('') $("#post-comment-form-div").fadeIn(); s = -1; } else { $("#post-comment-form-div").fadeOut(); s = 0; } }) $('.inside-post-detail #likeBtn').on("click", function (e) { e.preventDefault(); if($(".inside-post-detail #likeBtn i").hasClass("fa-thumbs-up")){ $(".inside-post-detail #likeBtn i").removeClass("fa-thumbs-up").addClass("fa-thumbs-down"); } else { $(".inside-post-detail #likeBtn i").removeClass("fa-thumbs-down").addClass("fa-thumbs-up"); } }) $('.post-comment-form').on("submit", function (e) { e.preventDefault(); e.stopImmediatePropagation(); $.ajax({ type:'POST', url: $(this).attr('action'), headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: $(this).serialize(), dataType: 'json', success: function(data) { $("#post-linked-comments div").html(data.comments); $('textarea').val(''); $('.reply-btn').on("click", function () { $("#modal-comment-reply textarea").attr("placeholder","Add your reply") $("#modal-comment-reply textarea").addClass("comment-reply-adjust") var c_id = $(this).data('id'); $("#c-get-id").val(c_id); $('textarea').val(''); $("#modal-comment-reply").modal("show"); }); $('.view-replies').on('click', function () { var h = $(this).data('hidden'); var curr = $(this).text() var … -
no reverse match error when trying to call a view function in django
I want to call a view function, Person2, when pressing the persons button but it seems that there is a miss match in the url. I am trying to call my function from a template wtih the id of person. The template displays the result of a search query that comes from the main page, but I want to be able to call a view function when pressing the person button for further information. my template, searchResult.py: {% extends "artdb/index.html" %} {% block sr1 %} <ul> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:person2' person.id %}"> Persons: {{person.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Activities: {{activity.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Members: {{member.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Comments: {{comment.count}} </a> <br></br> {% if person.all %} {% for p in person.all %} <h6>First name: {{p.first_name}}</h6> <h6>Last name: {{p.last_name}}</h6> <h6>Phone: {{p.phone_number}}</h6> <h6>Adress: {{p.street_address}}</h6> <h6>Zip Code: {{p.zipcode}}</h6> <h6>City: {{p.city}}</h6> <h6>Country: {{p.country}}</h6> <h6>Payment: {{p.payment}}</h6> {% for c in p.comment.all %} <h6>Comment: {{c}}</h6> {% endfor %} <hr> {% endfor %} {% for d in activity.all %} <h6>Activity name: {{d.activity_name}}</h6> <h6>project name: {{d.project.project_name}}</h6> … -
Unable to create log files in Django using CentOS server
My django project is hosting in centos Server, which is working fine. I've added a new functionality and to check if its working properly, I've added logging to the one file as follows. In my views.py import logging logging.basicConfig(filename='/tmp/logging/testlog.log', level=logging.DEBUG) def myfunction(request): logging.debug('my function started') user = User.objects.all() return render(request, 'myfunction.html', { 'user':user, }) my understanding is that this should create a testlog.log file in /tmp/logging but that is not happening. I specifically chose /tmp/logging folder as it does not require any permissions for creating or writing files, yet my log file is not being created in the server -
ERROR : 'AnonymousUser' object has no attribute '_meta' , when new user is added by extending User Model
I'm trying to add a new user(Using Signup Form) by Extending User Model Using a One-To-One Link. In the signup form I am using 2 forms, userSignup and userSignup_profile. userSignup contains details of user for the fields which are already in 'auth_user' userSignup_profile contains other information like Address, pincode, etc. Please Refer the link which explains what I'm trying to do: https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) pincode = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Forms.py class userSignup(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name','username', 'password', 'email') class userSignup_profile(forms.ModelForm): class Meta: model = Profile fields = ('phone', 'address', 'pincode') user_signup.html <body> <form action="user_signup" method="POST"> {% csrf_token %} {{form.as_p}} {{ profile_form.as_p}} <input id="next" type="hidden" name="next" value=" {{ request.GET.next }} "/> <button class="primary" type="submit" value="login">SIGNUP </button> </form> </body> views.py def user_signup(request): if request.method == "POST": user_form = userSignup(request.POST, instance=request.user) profile_form = userSignup_profile(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('/') else: return redirect('user_signup') else: form = userSignup() profile_form = userSignup_profile() return render(request,"user_signup.html",{'form':form, 'profile_form':profile_form}) Error : Request Method: POST Request URL: http://127.0.0.1:8000/user_signup Django Version: 3.0.5 Python Version: 3.7.2 Installed Applications: … -
Convert QuerySet to python list in Django
I have this script: lec_name = request.POST['selected_name'] data = Schedules.objects.filter(name=lec_name) data_list = data.values_list('schedule', flat=True) print(data_list) This gives below OUTPUT: <QuerySet ["[['1', 'Subject 01', 'Hall 01', 'Tuesday'], ['2', 'Subject 02', 'Hall 03', 'Monday']]"]> Then I tried below script to convert data_list to a list: converted_list = list(data_list) This gives below OUTPUT: ["[['1', 'Subject 01', 'Hall 01', 'Tuesday'], ['2', 'Subject 02', 'Hall 03', 'Monday']]"] This works fine. But I'm not getting the expected output properly. EXPECTED OUTPUT: [['1', 'Subject 01', 'Hall 01', 'Tuesday'], ['2', 'Subject 02', 'Hall 03', 'Monday']] How can I solve this? I found a lot of answers about this, but none helped. I'm using Python 3.7.4, Django 3.0.1 -
how to disable submit button until file selected for upload
I am working on one web application in which i am taking pdf file and then extract it, For file input I have used a django form for uploading pdf. I'd like to disable the submit button, until user selects an pdf to upload.I tried jQuery also but failed to get id of FileField. forms.py from django import forms class browse(forms.Form): file = forms.FileField() extractdata.html {% extends "invoicedata/base.html" %} {% block content %} <main role="main" class="container" style="margin-right: 11%;"> <div class="col-md-12"> <h2>Extract From Pdf</h2> <hr> <div class="container"> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-header"> Featured </div> <img class="card-img" src="https://vectorified.com/images/parser-icon-30.png" alt="bgimage"> <div class="card-img-overlay "> <div class="card" style="width:40%; margin-top:50px;" > <div class="card-body" > <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-primary" onclick='start(0)' type="Submit" name="submit" value="Extract & Save"> </form> <br> <h5>EXtracted Data will apear here</h5> <hr> {% for key, value in result.items %} <h6>{{key}} : {{value}}</h6> {% endfor %} </div> </div> </div> </div> </div> </div> </div> </div> </main> {% endblock content %} -
Django - Show a different form depending on a dropdown list
I'm creating an online quiz and I want to be able to add two different types of questions. I created two models and forms according to my two different types of questions. I added my app in INSTALLED_APPS, added a path in urls.py and registered my models in admin.py. I'd like to show the correct form according to what you chose in the dropdown list. This his what I made so far : My two models in models.py : from django.db import models from django.contrib.auth.models import User class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=200, unique=True) answer = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=200, unique=True) choice_1 = models.CharField(max_length=200, unique=True, default='') choice_2 = models.CharField(max_length=200, unique=True, default='') choice_3 = models.CharField(max_length=200, unique=True, default='') choice_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' Then my two forms in forms.py : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM, Point class Form_Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de la question') question = forms.CharField() answer = forms.IntegerField() class Meta: model = Question_Num fields = ['num_question', 'question', 'answer'] class … -
How to insert HTML string into a Microsoft Word document?
I have an HTML string captured through user input in a Web application through TextArea. I would like to populate this HTML string into a Microsoft Word template file. I can populate normal string into the template file. However, with HTML string, I am not sure, how to do it. In terms of technology, I am developing a web application in Django. -
deploying angular 9 with django drf with docker - requests gets rejected
Disclaimer: sorry for my bad english and I am new to angular, django and production. I am trying to push the first draft of what I've made into a local production server I own running CentOS 7. Up until now i was working in dev mode with proxy.config.json to bind between the Django and Angular so far so good. { "/api": { "target": "example.me", "secure": false, "logLevel": "debug", "changeOrigin": true } } when I wanted to push to production however i failed to bind the container frontend with backend. these are the setup i made Containerizing angular and putting the compiled files in an NGINX container -- port 3108 Containerizing Django and running gunicorn -- port 80 Postgres image DockerFiles and Docker-compose Django Dockerfile FROM python:3.8 # USER app ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ Angular Dockerfile FROM node:12.16.2 AS build LABEL version="0.0.1" WORKDIR /app COPY ["package.json","npm-shrinkwrap.json*","./"] RUN npm install -g @angular/cli RUN npm install --silent COPY . . RUN ng build --prod FROM nginx:latest RUN rm -rf /usr/share/nginx/html/* COPY ./nginx/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/dist/frontend /usr/share/nginx/html EXPOSE "3108" Docker-compose version: '3' services: db: image: postgres environment: - … -
How can a Django web app in a centos Docker container send emails via a Windows 10 host?
I have a Django web app running in a Unix (Centos 8) Docker container, and this app is supposed to send emails. Currently I am running the app, including other Docker containers, on my Windows 10 laptop for development and manual testing. But eventually it will run in an AWS EC2 instance. I suspect that in AWS I can just use Amazon's SES ("Simple Email Service"). But I would like to be able to email in Development mode too. I set up an SMTP relay Docker container, with port 25 mapped to host port 25, and running an emailer called Postfix (a successor to Sendmail), and tried to configure it. But, although the SMTP relay mode configuration of Postfix is supposed to be pretty simple I wasn't able to get the perishing thing to work. I'm not sure if this is because my Postfix config is defective somehow or because Windows 10 is not playing ball. Any ideas? P.S. I case it helps, the following are the Postfix environment variable values I defined. If anyone faced with the same problem finds this page, please don't rely on these values, as some or all may well be nonsense! ENV RELAY_MYDOMAIN=jrsurveys.com ENV … -
how to access a model inside the app template
Trying to access if affiliate exists in the template HTML, but it doesn't instantiate the object in HTML I try to access the affiliates with {% if affiliates %} or {% if objects %}, but code goes to else part instead, this has to check if an affiliate already exists in the model. {% block affiliate_content %} {% if affiliates %} <h3>{% trans "Your code" %}</h3> <table class="table table-bordered"> <thead> <tr> <td>{% trans "Title" %}</td> <td>{% trans "Code" %}</td> <td>{% trans "Example" %}</td> </tr> </thead> <tr> <td>{% trans "Affiliate code" %}</td> <td>{{ affiliate.aid }}</td> <td></td> </tr> <tr> <td>{% trans "Affiliate link" %}</td> <td>{{ affiliate_link }}</td> <td></td> </tr> <tr> <td>{% trans "Affiliate link for website" %}</td> <td>{{ '<a href="'|force_escape }}{{ affiliate_link }}{{'">'|force_escape }}{% trans "Partner link" %}{{'</a>'|force_escape }}</td> <td><a href="{{ affiliate_link }}">{% trans 'Partner link' %}</a></td> </tr> </table> {% else %} {% trans "Currently you don't have affiliate program. Please, enable it first." %} {% endif %} {% endblock %} Views.py class AffiliateBaseView(generic.CreateView): model = Affiliates form_class=AffiliateForm template_name = "affiliates/affiliate.html" def get_form_kwargs(self, *args, **kwargs): kwargs = super(AffiliateBaseView, self).get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs def get_initial(self, *args, **kwargs): initial = super(AffiliateBaseView, self).get_initial(**kwargs) return initial def form_valid(self, form): form.instance.user = self.request.user return … -
How can I override the save function for serializers? (Django Rest Framework)
I'm using Django REST Framework and using the .save() method I'm getting an error saying that I have to override the .create() method. I'm using multiple nested objects. I have no idea how to override that function, thanks in advance!! This is my models.py file from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Pizzas(models.Model): # DB model to keep info about pizza name = models.CharField(max_length=200) description = models.TextField() # Ingredients n stuff photo = models.ImageField(upload_to='main/img', default='main/img/pizza.jpg') price = models.IntegerField(default=15) class Meta: verbose_name_plural = "Pizzas" def __str__(self): return self.name class Orders(models.Model): # Orders table user = models.ForeignKey(User, on_delete=models.CASCADE) # who has ordered the pizza/pizzas price = models.IntegerField(default=0) # Price of the orde (make a function or something to calculate this) address = models.CharField(max_length=300) # User gives it content = models.ManyToManyField(Pizzas) # Self explainatory date = models.DateTimeField("Date Ordered", default=timezone.now()) class Meta: verbose_name_plural = "Orders" def __str__(self): return f"{self.user} - {self.price}" My serializers.py file from rest_framework import serializers from main.models import Orders, Pizzas from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id'] class PizzasSerializer(serializers.ModelSerializer): class Meta: model = Pizzas fields = ['name'] class OrdersSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) content = PizzasSerializer(many=True, read_only=True) class … -
Django Profile Project
I have a typical scenario that i want to create a Registration form where anyone can insert First Name, Last Name, Email Id, Username, Password(which can be stored in User table provided by Django) , Bio and Profile Picture(which can't be stored in User table provided by Django) and after registration when user tries to login with Username and Password then he can view his detail and also update them. i have completed the registration part with the help of OneToOne relationship with User table but having a lot of Trouble in viewing and updating them help me with Django Code. Models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) work = models.CharField(max_length=120,null=True) bio = models.TextField(null=True) profile_picture = models.ImageField(upload_to="Profile Pictures",null=True) def __str__(self): return self.user.username login.html <form action="" method="POST"> {% csrf_token %} <div class="modal-body"> <div class="md-form form-sm mb-5"> <i class="fas fa-user prefix fb-text "></i> <input type="text" name="username" class="form-control form-control-sm validate" required> <label data-error="wrong" data-success="right" for="username">Your Username</label> </div> <div class="md-form form-sm mb-5"> <i class="fas fa-envelope prefix fb-text"></i> <input type="email" name="email" class="form-control form-control-sm validate" required> <label data-error="wrong" data-success="right" for="email">Your email</label> </div> <div class="md-form form-sm mb-5"> <i class="fas fa-envelope prefix fb-text"></i> <input type="text" name="work" class="form-control form-control-sm validate" required> <label … -
Django | Field 'id' expected a number but got OrderedDict()
I have a create endpoint in restframework that works fine. views is as follows class ItemAddAPIView(CreateAPIView): serializer_class = ItemSerializer parser_classes = [MultiPartParser] def create(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) item_obj = Item.objects.create(title=serializer.data['title'], discount=serializer.data['discount'], rate_per_kg=serializer.data['rate_per_kg']) return Response(serializer.data, status=HTTP_201_CREATED) except Exception as e: print("error :: ",e) serializer is given below: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields='__all__' This works fine. But when I add a SerializerMethodField() to the Serializer it gives the error : Field 'id' expected a number but got OrderedDict([('title', 'erwre'), ('rate_per_kg', 53.0), ('discount', 5.0)]). class ItemSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField(method_name='get_image_list') class Meta: model = Item fields='__all__' def get_image_list(self,obj): image_list=[] item_images = ItemImage.objects.filter(item=obj) request = self.context.get('request') for each in item_images: image_list.append(request.build_absolute_uri(each.image.url)) return image_list -
Django Web Form - Update YAML File Variables
Is it possible to update YAML file variables from a Django web form? I ask because I need to update a YAML file based on user input without giving them access to the YAML file itself. I was thinking that a Django web form would be suitable for this task in my brief reading of it, but I'm not sure if this is possible or not and if it's worth researching any further. -
When will Django officially support one nosql database?
When will Django officially support one at least nosql database? -
Asked to install Pillow when requirement is already satisfied
I'm trying to run a Django Project I had running before formatting my PC (Windows 10). Now I tried to do: pip install -r requirements.txt And everything install ok, no errors. But when trying to run my Django app with: python manage.py runserver I get: ERRORS: shop.Category.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Pack.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Profile.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.Sample.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". shop.UnitaryProduct.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". System check identified 6 issues (0 silenced). Then when I try to do: pip --no-cache-dir install Pillow It appears to have installed it but still cannot run my … -
Django CustomUser Signup attribute error: 'str' object has no attribute 'META'
I have the following error when I try to signup to my application: AttributeError at /signup/: 'str' object has no attribute 'META' Whatever I did, I couldn't resolve the error. This is the SignUp view (I redirect to a "redirect" view after successful signup, this is here only for being placeholder, printing the logged in users email in a template) views.py def redirect(request): return render(request, 'accounts/redirect.html') def signup(request): if request.method == 'POST': form = SignUpForm(data=request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('accounts:redirect') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) I have a CustomUser object as my Authentication User model in my Django application. I use CustomUserCreationForm, and SignUpForm which inherits this CustomUserCreation Form (You can see below the CustomUser model, CustomManager as well as the CustomForms.) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email adress', unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_exhibitor = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Meta: verbose_name = 'user' managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User … -
django filter on multiple GET parameters
I have a search field and two extra search parameters (category and platform) on the side of the results on my search page. my queryset looks like this on the list view: def get_queryset(self): query = self.request.GET.get('q') category = self.request.GET.get('category') platform = self.request.GET.get('platform') text_query = ( Q(name__icontains=query) | Q(category__name__icontains=query) | Q(tags__name__icontains=query) ) object_list = Results.objects.all() if query: object_list = object_list.filter( text_query ) if category: object_list = object_list.filter(Q(category__name=category)) if platform: if platform == "windows": object_list = object_list.select_related('versions').latest().filter(windows=True) elif platform == "linux": object_list = object_list.select_related('versions').latest().filter(linux=True) elif platform == "mac": object_list = object_list.select_related('versions').latest().filter(mac=True) return object_list I know the last part can be one line with exec, but this does not work because you cant filter the result of a filter (object_list). What is the best way to filter based on multiple GET parameters? -
user.is_authorised returns false in particular django template
username is showing up in all templates except one template. What is missing there? user.is_authorised returns false in one particular template. -
Galler images very big in size using html
Is there a way to make these images smaller? and fit into a box? I followed according to a tutorial and images are bigger.This is zoomed out to 25% view. I'm looking for a way to resize the images to fit into the gallery like view, in the tutorial, the person ended up with a perfect gallery type output unlike me xd .This is for a django project and thanks in advance :) This is normal zoomed out view html code: {% extends 'portofolio/base.html' %} {% load static %} {% block content %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.8.2/css/lightbox.min.css"> <link rel="stylesheet" href="{% static "portofolio/css/photogallery.css" %}"> <body> <h1 style="margin-top: 70px;">Image Gallery</h1> <div id="jLightroom" class="jlr"> <a href="{% static "portofolio/images/1.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/1.jpg" %}"> </a> <a href="{% static "portofolio/images/2.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/2.jpg" %}"> </a> <a href="{% static "portofolio/images/3.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/3.jpg" %}"> </a> <a href="{% static "portofolio/images/4.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/4.jpg" %}"> </a> <a href="{% static "portofolio/images/5.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/5.jpg" %}"> </a> <a href="{% static "portofolio/images/6.jpg" %}" data-lightbox="lb1" class="jlr_item"> <img src="{% static "portofolio/images/6.jpg" %}"> </a> <a href="{% static "portofolio/images/7.jpg" %}" data-lightbox="lb1" class="jlr_item"> … -
Implementing pageviews in Django
I am working on a small a small website and I want to display the total views of every object in the detail view. But sincerely, I don't know how to actualise this. Let me post my models.py and views.py Models.py class Music(models.Model): artist = models.CharField(max_length=300) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(default='', blank=True, unique=True) thumbnail = models.ImageField(blank=False) audio_file = models.FileField(default='') uploaded_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-uploaded_date'] def save(self): self.uploaded_date = timezone.now() self.slug = slugify(self.title) super(Music, self).save() def __str__(self): return self.title + ' by ' + self.artist def get_absolute_url(self): return reverse('music:detail', kwargs={'slug': self.slug}) Views.py return Music.objects.order_by('-uploaded_date') def detail(request, slug): latest_posts = Music.objects.order_by('-uploaded_date')[:5] song = get_object_or_404(Music, slug=slug) comments = Comment.objects.filter(post=song) if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.post = song comment.save() return HttpResponseRedirect(song.get_absolute_url()) else: comment_form = CommentForm() context = { 'latest_posts': latest_posts, 'song': song, 'comments': comments, 'comment_form': comment_form, } return render(request, 'music/detail.html', context) -
Does 'list_editable' work with files in the django admin?
I'm trying to get a way to rename my uploaded files in the django admin using list_editable. I tried it but it doesn't seem to be working, since it only shows a 'Save' button below, but nowhere where I can edit my files names. Is this even possible or does it now work with FileFields? I looked on forums but nothing seemed to be similar to what I was trying to do. Thanks in advance!