Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid block Tag, 'endblock'
i don't know what type of error is this. The issue seems to be here: {% ifequal error "no" %} <script> alert("signup successfully"); window.location = ('{% url 'user_login' %}') </script> {% endifequal %} {# problem is here #} {% ifequal error "yes" %} <script> alert("Try Again..."); </script> {% endifequal %} Thank you1 -
How to override Django DeleteView without using Abstract Model and Manager
I am trying to soft delete entry from my DB by overriding delete method in DeleteView but it is not working. Attribute active should be set to False. I can't use Abstract model and Manager because my parent model must originally have active attribute. my view class PersonDeleteView(DeleteView): model = Person template_name = 'contacts/deleteperson.html' success_url = reverse_lazy('persons') def delete(self, *args, **kwargs): self.object = self.get_object() self.object.active = False return HttpResponseRedirect(self.get_success_url()) parent model class AddressEntry(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) gender = models.CharField( max_length= 20, choices=GENDER, default='Male') name = models.CharField(max_length=100) firstname = models.CharField(max_length=100) birthdate = models.DateField() active = models.BooleanField(default=True) def __str__(self): return self.name def soft_delete(self): self.active = False self.save() child model class Person(AddressEntry): parentname = models.CharField(max_length=100) job = models.CharField(max_length=100) -
Cannot access Django on Google Cloud service through external IP
I have started Django server on google cloud service (it's CentOS) successfully: [root@XXXXXXXXXX]# python3 manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). March 04, 2022 - 20:20:58 Django version 3.2.12, using settings 'XXX.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. And in settings.py of this Django project, I have set ALLOWED_HOSTS = ['*'] to allow all hosts. But when I try to access this Django project on browser through [external_ip_of_my_google_cloud_compute_engine_instance]:8000 like 35.xxx.xxx.xxx:8000, I keep failing to make it. I also tried to install uwsgi but the result doesn't change. Does anyone know what I can do to solve this problem? -
check_token in PUT method not working DRF
So I have a view that sends a confirmation email to the new user to activate with a uid and token. That part works fine. When the user clicks on the link it's suppose to send a PUT to my ActivateUserAPI where it grabs the 'uid' and 'token' from the url and sets email_confirmed = True, but it is not getting past djangos check_token function serializer: class ActivationSerializer(serializers.ModelSerializer) class Meta: model = User fields = ('id', 'email_confirmed',) view: class ActivateUserAPI(generics.UpdateAPIView): serializer_class = ActivationSerializer permission_classes = [ permissions.AllowAny ] def put(self, request, *args, **kwargs): token = self.kwargs['token'] try: uid = force_str(urlsafe_base64_decode(self.kwargs['uid'])) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): serializer = ActivationSerializer(user, data=request.data) if serializer.is_valid(): user.email_confirmed = True user.save() return Response(serializer.data) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') The weird thing is that if I access the api directly through the url it works fine, like in the link below View of DRF -
How to filter out objects that do not have a relationship with another form in Django?
I have two samples in an application built using Django: class User(models.Model): email = models.EmailField() class Product(models.Model): user = models.ForeignKey(User) I want to filter out all users who don't have any products in the store. How do I do this? -
Bootstrap modal doesn't display images that were uploaded in django
hello I have a problem to show several images that are in my database when calling the modal, they just don't show up. I have found little information about it and what I have found seems very difficult to follow. Can you help me explain how it would be to show the images that are in my database through my modal? The images are loading well in the database, the only problem is displaying each of the images, when I click the image only the empty modal is shown HTML {% for carro in carros %} <tr> <td>{{carro.fecha_registros}}</td> {% if carro.fotosCarro %} </td> <a data-bs-toggle="modal" data-bs-target="#exampleModal"> <img src="{{carro.fotosCarro.url}}" height="68"> </a> </td> {% endif %} <td>{{carro.placas}}</td> <td>{{carro.año}}</td> <td>{{carro.modelo}}</td> <td>{{carro.color}}</td> <td>{{carro.cliente.nombre}}</td> </tr> {% endfor %} JS <script> $('#exampleModal').on('shown.bs.modal', function () { $('#myInput').trigger('focus') }) </script> views.py def list_cars(request): if request.method == 'POST': fromdate=request.POST.get('fromdate') todate = request.POST.get('todate') searchresult = Carro.objects.filter(fecha_registros__range=(fromdate, todate)) return render(request,'carros/index.html',{'carros':searchresult}) else: displaydata = Carro.objects.all() return render(request, 'carros/index.html', {'carros': displaydata}) -
Deleting a value from database based on data coming sent from a form - Django
I am trying to implement newsletter/email subscription for my project. I created a model which only stores the email and the timestamp and uses SendGrid to send emails to the users who subscribed. I want to include an unsubscribe button inside the emails I send them. When the user clicks unsubscribe link in the mail it appends the id of the value in db to the url and redirects to cancelsub.html where I am accessing it. In cancelsub.html I have a form with a submit button which when a user clicks should delete the value from db. It is not working for some reason. Models.py-- class NewsletterUser(models.Model): email = models.EmailField(null=True) date_added = models.DateTimeField(default=datetime.now) def __str__(self): return self.email Views.py-- def NewsLetter(request): if request.method == 'POST': email_input = request.POST.get('email_value') new = NewsletterUser(email=email_input) new.save() sendEmail(email_input) return render(request,"pages/index.html") def DeleteNewsLetter(request): if request.method == 'POST': del_id = request.POST.get('id_value') NewsletterUser.objects.filter(id= del_id).delete() return render(request, "newsletter/CancelSubscription.html") cancelsub.html-- <form id="cancel-subscription-form" method="POST"> {% csrf_token %} <div class="email-and-btn"> <button class="btn btn-danger mb-2 art-digest-btn" id="cancel-btn" type="submit" value="">Yes, Cancel It</button> </div> </form> <script src="https://code.jquery.com/jquery-1.9.1.js"></script> <script> var current_url = window.location.href var id = current_url.split('?')[1] id_int = parseInt(id) $("#cancel-btn").val(id_int); $(document).on('submit','#cancel-subscription-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url "DeleteNewsLetter" %}', data: { id_value: parseInt($("#cancel-btn").val()), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ } … -
hard reload loads new css but f5 load the older version (even after the hard reload)
I have wagtail project, in this project I compile scss with webpack to the static folder in my project. When i have devtools open (and i checked the no cache checkbox) and then reload the page, the css is loaded. When i hard reload (clear cache etc) the new updated css is applied. If after this i press f5 again the previous older version is loaded. How and why is this happening? This is the first time i've encountered this problem. maybe it doesn't override the cache with the new css? I am running version: 98.0.4758.109 -
Django url template tag refers to url with trailing question mark
This is a question concerning a trailing question mark that gets appended to the end of the URL rendered by Django's url template tag. My goal is to have this trailing question mark removed, yet I do not know how. On my site's main page, I have a button - a form HTML tag, really - that directs me to another link of the website. The form looks like: <form action={% url 'my_index' %}> <input type="submit" value="some value" /> </form> When clicking on that button, I am directed to the URL corresponding to the my_index view. The problem, however, is that at the end of that URL, there is a "/?" that is appended - that is, the URL is in the form "http://127.0.0.1:8000/my_app/?". I want to remove this /? at the end and also want to understand why this trailing question mark got appended. My urls.py pointed to by the ROOT_URLCONF IS urlpatterns = [ path('', include('my_app.urls')), ] And my urls.py within my_app app looks like: urlpatterns = [ path('', views.index, name='my_index'), ] Any advice is appreciated. -
Django redirect to page only if it exists
I have a Python Django application I'm working on. There is a submission page that takes some input from the user and I spend time working on it with a thread. This processing can take variable time, as low as one minute to maybe 30 minutes. While the thread is running, I redirect to a waiting page, but I want to redirect from that waiting page to some output page when the processing thread completes. I can have the thread create all necessary changes i.e. creating the page template, appending some code to the views.py file, and adding the path to the urls.py file, but I'm not sure how to have that redirect trigger. I believe the overall question here is how can I redirect to a page in Django only if it exists? -
Django - Submit multiple embedded forms using ajax
I defined a Usercomp model for user details linked with standard User model with OneToOne relationship. Thus, I have 2 forms to update user details: is it possible to manage the POST request using ajax? At this stage, changing the model is not an acceptable option, even it would probably make thinks easier. In addition, I know how to manage this without javascript. So I make this post for a better understanding of the technical environment I'm discovering. The first question is actually: does it make sense? I went to js for the GET request, to populate the forms in a modal window to edit existing rows, so I wonder if it's a good idea to make the POST request like this? The second question is then: how to proceed? Here are some code snippets I tried so far: user_profile.html (modal form): <div class="row modal-content"> <div class="modal-body"> <div class="col-lg-12 align-items-center text-center"> <form id="upd-user" action="." method="post" url-endpoint="{% url 'polls:upd_user_detail' %}" comp-slug="{{ comp_slug }}" usr-id="{% if usr_id %} {{ usr_id }} {% else %} 0 {% endif %}"> {% csrf_token %} {{ user_form }} <!-- standard user data - simplified code --> {{ usercomp_form }} <!-- custom user data - simplified code … -
adding custom CSS to django admin forms
I'm trying to style a form in django admin. I created a file to extend the base admin page with myApp/templates/admin/base_site.html and I'm calling in a new css file with: {% extends 'admin/base.html' %} {% load static %} {% block branding %} {% block extrastyle %} <link rel='stylesheet' href='{% static 'css/admin.css' %}'> {% endblock %} {% endblock %} I added a static directory and file at myApp/static/admin/css/admin.css. Since the admin app has already took control of URIs like http://127.0.0.1:8000/static/admin/css/base.css my app can't find static/css/base.css because it expects my admin.css to be in venv/lib/python3.9/site-packages/django/contrib/admin/static/admin/css. I want to extend the base css (add to it), not necessarily completely override it. I'm guessing the answer is to edit settings.py to tell it to look at myApp/static but I'm not sure how. The relevant settings.py lines are: STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static/'), ] STATIC_URL = 'static/' Thanks. -
How can I run a form validation function only runs depending on the value of a field in another form?
I have two forms, form1 and form2, but only want to run the validation check functions in form1 if one of the fields in form2 has a certain value. How can one do this in Django? FORMS E.g. Form 1 class form1(forms.ModelForm) fields = {employment_type} Form 2 class form2(forms.ModelForm) fields = {student_loan} # But I only want to run this check if employment_type == 'Employee', in form 1??? def clean_student_loan(self): student_loan = self.cleaned_data('student_loan') if student_loan == 'something': do stuff -
Conversion from website to mobile application
I am developing a website for a startup and plan to have a mobile app version. The technologies used to build the website are: Frontend: HTML, CSS, JavaScript Backend: Python (Django) DataBase: SQLite I would like to know if the conversion from website to mobile app maintains the same level of performance and is it advantageous? -
django Expiration object
I am using an activation system to verify the user email and now in the active_code model , I wnat only the objects that are created 120 seconds ago . Help me please! def Activation_page(request): if request.method == "POST": form = forms.Active(request.POST) if form.is_valid(): data = form.cleaned_data past_seconds = timezone.now().date() - timedelta(seconds=120) if active_code.objects.filter(email = request.session['email'] , code = data['num'] , expiration__gte=past_seconds).exists() : try: b = User.objects.get(email = request.session['email']) b.is_active = True b.save() return redirect('home:loginveiw') except: messages.error(request , 'error') else: messages.error(request , 'error_2') else: form = forms.Active() return render(request , 'home/activation.html' , {'form' : form}) -
Issues with django Group formsets
Am trying to implement a group form where a choice in a model field will determine the options in the other field. kindly checks my code below models.py class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) mobile_number = models.CharField( max_length=11) # validators should be a list type = models.CharField(choices=Main.TYPES, max_length=10) operator = models.CharField(max_length=15) circle = models.CharField(max_length=20) plan = models.DecimalField(max_digits=6, decimal_places=2) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) plan_id = models.DecimalField(max_digits=6, decimal_places=2) network_id = models.DecimalField(max_digits=6, decimal_places=2) api_development_no = models.CharField(max_length=15) class Meta: ordering = ["-timestamp"] fields.py class GroupedModelChoiceField(ModelChoiceField): def __init__(self, *args, choices_groupby, **kwargs): if isinstance(choices_groupby, str): choices_groupby = attrgetter(choices_groupby) elif not callable(choices_groupby): raise TypeError('choices_groupby must either be a str or a callable accepting a single argument') self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby) super().__init__(*args, **kwargs) forms.py class RechargeDataForm (forms.ModelForm): class Meta: model = RechargeData fields = ['mobile_number', 'type', 'operator', 'circle', 'plan'] class GroupedRechargeDataForm(forms.ModelForm): operator = GroupedModelChoiceField(queryset=operator.objects.exclude(operator=None), choices_groupby='operator') class Meta: model = RechargeData fields = ['mobile_number', 'type', 'operator', 'circle', 'plan'] This form rendering is bringing a different outcome by fetching only operator field created in model but am trying to render the rest form based on choice on operator. for example. if the User choices Mtn As operator then the cycle, the plan, the type, the network_id, the plan_id will … -
Why do I get a Key Error when raising Validation Error in a form.py file?
No idea what is going on here, but when I include this validation check function in form.py file, I get a Key Error on the field: def clean_student_loan_payment_method(self): student_loan_payment_method = self.cleaned_data['student_loan_payment_method'] student_loan_boolean = self.cleaned_data['student_loan_boolean'] if student_loan_payment_method == None: student_loan_payment_method = '' if student_loan_boolean == True and student_loan_payment_method == '': raise forms.ValidationError(_("Please choose the method by which you repay your Educational Loan.")) return student_loan_payment_method If I hash out the line called 'raise forms.Validation(...', I get no Key Error. The form submits, and all is fine. Any ideas? Specifically this is the error Request Method: POST Request URL: http://localhost:8000/app/profile/edit/employment/ Django Version: 4.0.2 Exception Type: KeyError Exception Value: 'student_loan_payment_method' Exception Location: /Users/....Website Development/Github Pages/.../forms.py, line 432, in clean_student_loan_plans Python Executable: /Users/....Website Development/Github Pages/....python3 Python Version: 3.8.9 -
How do you handle non-standard 4xx and 5xx Django Errors?
We have the 404, 500, etc. templates created for our Django app to handle the built-in HTTP Errors that Django supports. But how do you handle the non-standard 4xx and 5xx HTTP Errors? For example, when I submit a really long URL param, I see a 414 Request-URI Too Long message instead of one of our templates. How do I set up Django to error handle HTTP Error codes like: 411, 414, 505, etc? -
How to run python function from Django
I would like to run a python script (or even better a function inside the script) inside my Django app. Basically I think AJAX would be the right choice for this, since the web page should not reload when the button is clicked. Can someone help me with the structure or give me tips? What I got so far is basically my template and a reference for my button: "page.html" <form method="post"> <button type="button" type="submit" class="btn btn-primary">Resync</button> </form> How can I put this into my "views.py" and run an python script from my project folder when click on the button (basically the python script will do some database updates in the background)? -
Testing Django Wagtail - assert that a child of the given Page type with an image can be created under the parent
I've defined a custom page model (a blog post) as a child of a parent model (a blog index page) and I want to test that the child can be created under its parent. The BlogPage and BlogIndexPage models are copied from the wagtail "basic blog" example in the documentation, and works as expected. I'm trying to follow the documentation but I get the following error: AssertionError: Creating a page failed for an unknown reason Through trial and error, I know that the error is caused by including an InlinePanel that references another model (BlogPageGalleryImage). If I remove this panel from my BlogPost model definition then the test will pass. I don't understand why including the panel causes an error, or how to solve this problem. Any help is much appreciated! The problematic line: ... InlinePanel("gallery_images", label="Gallery images"), ... The models: class BlogIndexPage(Page): template = "blog.html" intro = models.TextField(blank=True) subpage_types = ["cms.BlogPage", "cms.SimpleBlogPage", "cms.BlogTagIndexPage"] def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context = super().get_context(request) blogpages = self.get_children().live().order_by("-first_published_at") context["blogpages"] = blogpages return context content_panels = Page.content_panels + [FieldPanel("intro", classname="full")] class BlogPage(Page): template = "blog-post.html" parent_page_types = ["cms.BlogIndexPage"] date = models.DateField("Post date") intro = models.CharField(max_length=250) … -
'cryptography' package is required for sha256_password or caching_sha2_password auth methods
Request Method: POST Request URL: http://192.168.0.110/admin/login/?next=/admin/ Django Version: 4.0.1 Exception Type: RuntimeError Exception Value: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods Exception Location: /home/chickoos/explab/ExpLab/venv/lib/python3.8/site-packages/pymysql/_auth.py, line 143, in sha2_rsa_encrypt Python Executable: /home/chickoos/explab/ExpLab/venv/bin/python Python Version: 3.8.10 Python Path: ['/home/chickoos/explab/ExpLab', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/chickoos/explab/ExpLab/venv/lib/python3.8/site-packages'] Server time: -
unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date
In model, I have a property accepted_at = models.DateTimeField(blank=True, null=True) When I save it from datetime import datetime Entry.objects.last().accepted_at = datetime.now() I'm trying to know if is accepted before 30 minutes from datetime import datetime if (datetime.now() - Entry.objects.last().accepted_at).total_seconds() > 1800: return True But I'm getting the following error unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date Can someone help me? -
Redirect URL does not match on azure
I am building a django app which is hosted on azure web app service. I have used azure ad for authentication and to support that I have used MSAL library of python. In localhost, I have been able to login using azure and view site data but cannot visit the site when application is deployed to azure web app. I am getting the following error. I have used HTTP://localhos:8000/auth/redirect as redirect uri and using same for app deployed to azure web app: https://.azurewebsites.net/auth/redirect but it is not working and is showing the following error above. I am using the following code provided from https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication . I do not what is the issue. Please help. -
Cant render HTML file on Django
Django 4.0.3 and Python 3.10.2 I cant render a html file on my project. What am i missing? Main parts of code below. Settings.py at INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1', ] Settings.py at TEMPLATES: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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', ], }, # 'DIRS': [r'project1\app1\templates\app1'], 'DIRS': [os.path.join(BASE_DIR, 'templates')], }, ] Project-Urls: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')), # main will be the name of your app ] App1-Urls: from django.urls import path from . import views urlpatterns = [ path('', views.simple_function, name='simple_function'), ] Views: def simple_function(request): print("Print executes correctly, but the render doesn't") return render(request, r'project1\app1\templates\app1\home.html') Html file path: app1/templates/app1/home.html Github of this project Had to post this bunch of information to clarify. -
Override delete model in django
I have question model and also have Like and Dislike model, i want that if user have already liked this question and then click like button, delete Like object and question point increase by one. example: question has 10 like --> i send like, so question has 11 like --> i also send like, so delete object and question's like quantity (10) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("user")) question = models.ForeignKey(Question,on_delete=models.CASCADE,verbose_name=_("question")) def save(self, *args, **kwargs): if not self.pk: self.question.point += 1 self.question.save() return super(Like, self).save(*args, **kwargs) @receiver(post_delete, sender=Like) def delete_like(sender, instance, using, **kwargs): print(instance.question.point) #point is 3 instance.question.point -= 1 print(instance.question.point) #point is 2 when i print everything is fine but when i open database, result is not same edit: def get_context_data(self, *args, **kwargs): like_exist=bool(Like.objects.filter(user=self.request.user, question=self.get_object())) dislike_exist=bool(DisLike.objects.filter(user=self.request.user, question=self.get_object())) self.object=self.get_object() context = super(QuestionDetail, self).get_context_data(**kwargs) try: question = Question.objects.get(id=self.kwargs["pk"]) context['detail'] = question context['like_ex']=like_exist context['dislike_ex']=dislike_exist except Http404: return reverse("Profile:error") if "like" or "dislike" in self.request.GET: if "like" in self.request.GET: if Like.objects.filter(user=self.request.user, question=self.get_object()): Like.objects.filter(user=self.request.user, question=self.get_object()).delete() else: Like.objects.create(user=self.request.user, question=self.get_object()) if DisLike.objects.filter(user=self.request.user, question=self.get_object()): DisLike.objects.filter(user=self.request.user, question=self.get_object()).delete() if "dislike" in self.request.GET: if DisLike.objects.filter(user=self.request.user, question=self.get_object()).exists(): DisLike.objects.filter(user=self.request.user, question=self.get_object()).delete() else: DisLike.objects.create(user=self.request.user, question=self.get_object()) if Like.objects.filter(user=self.request.user, question=self.get_object()).exists(): Like.objects.filter(user=self.request.user, question=self.get_object()).delete() return context