Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Inheritance with Generic Relation
I have the following model structure: **models.py** class Person(models.Model): . . contact = GenericRelation(Contact) class Patient(Person): some other fields When creating a patient, what I do in the serializer is the following: **serializers.py** class PatientSerializer(serializers.ModelSerializer): contact = ContactSerializer(many=True) class Meta: model = Patient fields = PersonSerializer.Meta.fields + ... def create(self, validated_data): if('contact' in validated_data): contact_data = validated_data.pop('contact') instance = Patient.objects.create(**validated_data) person = Person.objects.get(id=instance.person_ptr_id) if(contact_data): for contact in contact_data: Contact.objects.create(..., content_object=person) This way, in the Contact table, it'll have direct reference to the Person base model. The aim of this is that I have to base another classes on Person to inherit these contacts. The problem that I'm having with this structure is that for the Patient View, "contact" is always empty: it returns the below from list and retrieve views. May it just be a matter of adjusting the queryset? "contact": [] Any advices to make this code better/structure are well welcomed. Thanks in advance! -
Error rendering a Simple.tag on template - Django
I've create a simple.tag on extratags.py which checks if the user is an attendant of the post event. extra_tags.py @register.simple_tag def get_attendent_user(post_id, user_id): return Attending.objects.filter(post__id=post_id, attendant__id=user_id).exists() If I render this {% get_attendent_user post.id user.id %} on the template is working but, the idea is to play with an IF condition there. So if I render this on the template: {% if get_attendent_user post.id user.id is False %} <p>ok</p> {% else %} <p>Not requested</p> {% endif %} is giving me the error: Unused 'post.id' at end of if expression. How can I correctly render this on the template? Thanks!! -
Django URL patterns contain trailing whitespace
Django authentication views are being included as admin/ accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password_change'] accounts/ password_change/done/ [name='password_change_done'] accounts/ password_reset/ [name='password_reset'] accounts/ password_reset/done/ [name='password_reset_done'] accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/ reset/done/ [name='password_reset_complete'] rather then accounts/login/ [name='login'] accounts/logout/ [name='logout'] accounts/password_change/ [name='password_change'] accounts/password_change/done/ [name='password_change_done'] accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete'] My URL dispatcher automatically includes 1 whitespace to any part of the URL that gets added, even after parsing the one trailing accounts. Want to know if there is a way to stop this from happening entirely without having to parse my URLs on my own. My urls.py is as follows: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path(s'accounts/', include('django.contrib.auth.urls'))) ] -
How can i send a webook to my django app and only execute it on logged in user
Hi i am new to coding and only been learning python and django for about a week. so sorry if this does not make sense. i am trying to send a webhook(this is just a test then ill add json) so that when i send to http://127.0.0.1:8000/webhook i am using postmen desktop so i receive the webhooks. it will execute my session code but the problem i have that in my app i have already set up users db and when i sent the webhook it return none since no one seems to be logged in. i know i will have to add a code something like a token to specify each user but only want to test with one user first. i get the error None or when i remove user authenticated then it says i can't send to anonymous user. is there a way i can send it to lets say a specific user or ID or let's say a token i save with the user. @csrf_exempt def webhook(request): #get current users keys if request.user.is_authenticated: user = request.user database = Bybitapidatas.objects.all().filter(user=user) for apikey in database: apikey = apikey.apikey for apisecret in database: apisecret = apisecret.apisecret session = HTTP(endpoint='https://api-testnet.bybit.com/', … -
UserProfile not creating in custom model using User model as OneToOneField(User)
I am creating the super user through admin panel or command line, but it is not showing in the custom model in the database. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(null=True) profile_image = models.ImageField(null=True, blank=True) def __str__(self): return str(self.user) class Following(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) following = models.CharField(max_length=30) class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) follower = models.CharField(max_length=30) Using OneToOnefield should create the user in the Profile model automatically but it is not happening. I am not sure what is wrong because in the previous project it was workiing fine. Also I have registered the models in admin.py. -
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) …