Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unittest is not detecting my newly made test file in Django
I'm working on a Django project that had a prewritten "example test". When I run python manage.py test it only runs/detects the example test file. I'm looking to test a model so my test structure is a little different but I can't see why unittest is not detecting them. Note: The tests are rudimentary # test_example.py from rest_framework import status from rest_framework.test import APITestCase class AuthenticationTestCase(APITestCase): def setUp(self): self.user_data = { "username": "test1", "email": "test@foo.com", "password": "123456", } def test_not_authenticated_protected_endpoint(self): """Try to access a protected endpoint without a token""" response = self.client.get(f"/api/users/{self.user_data['username']}") self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_authenticated_protected_endpoint(self): """Try to access a protected endpoint with a valid token""" # Register a user register_response = self.client.post( "/auth/register", data=self.user_data, format="json" ) self.assertEqual(register_response.status_code, status.HTTP_201_CREATED) data = register_response.json() self.assertIn("token", data) # Access protected route with credentials users_response = self.client.get( f"/api/users/{self.user_data['username']}", format="json", **{"HTTP_X-ACCESS-TOKEN": data.get("token")}, ) self.assertEqual(users_response.status_code, status.HTTP_200_OK) data = users_response.json() self.assertEqual(data, []) Here is my test: # test_conversation_group.py from django.test import TestCase from messenger_backend.models import ConversationGroup from messenger_backend.models import Conversation from messenger_backend.models import User class ConversationGroupTest(TestCase): def setUp(cls): cls.thomas = User( username="thomas", email="thomas@email.com", password="123456", photoUrl="https://res.cloudinary.com/dmlvthmqr/image/upload/v1607914467/messenger/thomas_kwzerk.png", ) cls.thomas.save() def test_something_that_will_pass(self): self.assertFalse(False) def test_1(self): self.assertEqual(self.thomas.username, "thomas") Directory structure: ├─tests ├── __init__.py ├── test_example.py └── test_conversation_group.py Thanks! -
__call__() missing 1 required positional argument: 'value' in Form
I set the model with tuple class CallType(m.IntegerChoices): PUSH = 1,"Push" PULL = 2,"Pull" Now I try to use this in model in Form class MyModelForm(forms.ModelForm): my_call_type = forms.ChoiceField( required=False, choices=CallType) in template {% render_field form.my_call_type class="form-control" %} There comes error like this python3.9/site-packages/django/forms/fields.py", line 773, in __iter__ yield from self.choices_func() TypeError: __call__() missing 1 required positional argument: 'value' I am guessing it means ,requiring to add some method to CallType though, What should I do? -
Making complex model without database Django
On django 3 When I need data without real database(like mysql), I can use m.IntegerChoices This CallType never changes so IntegerChoices is suitable. from django.db import models as m class CallType(m.IntegerChoices): PULL = 1 PUSH = 2 class BaseCall(models.Model): class Meta: db_table = 't_BaseCall' call_type = m.PositiveSmallIntegerField( choices=CallType.choices, default=CallType.PULL) Now I want to expand CallType more complex. class CallType(m.IntegerChoices): PULL = {"number":1,"name":"pulling"} PUSH = {"number":2,"name":"pushing"} What practice should I use? I am afraid IntegerChoices is not suitable for this case. -
Issues with Django REST JWT tokens not refreshing?
I've been implementing JWT tokens with my django REST app and I got it mostly working with the help of simple-jwt found here. I can sign in and obtain my refresh and access tokens but I noticed that if I attempt to refresh my token via jwt_views.TokenRefreshView.as_view() I receive an error that reads: HTTP 401 Unauthorized { "detail": "Token is invalid or expired", "code": "token_not_valid" } I've been trying to find a solution across reddit and stackoverflow but to no avail. Why isn't my token refreshing? Here's the relevant parts of my code: Relevant Code settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( "rest_framework.authentication.SessionAuthentication", 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('Bearer', 'Token'), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', } models.py #custom user profile model class User(AbstractUser): link1 = models.CharField(max_length=100, blank=True) link2 = models.CharField(blank=True, max_length=100) link3 = models.CharField(blank=True, max_length=100) link4 = models.CharField(blank=True, max_length=100) about_me = models.CharField(blank=True, max_length=200) class Meta: db_table = 'auth_user' urls.py from rest_framework_simplejwt import views as jwt_views urlpatterns += [ path('admin/', admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] Expected vs actual output Expected to refresh token using api/token/refresh/ after receiving it via api/token/, but was met with an error saying it was invalid/expired. What I've tried Honestly I mostly tried just refreshing the … -
Error : django.db.utils.ProgrammingError: cannot cast type bytea to boolean
I am running a migrate command on heroku from my django project and I am getting this error. Thanks in advance. django.db.utils.ProgrammingError: cannot cast type bytea to boolean LINE 1: ...R COLUMN "available" TYPE boolean USING "available"::boolean This is the class it is referring to. I tried adding a default=1, blank=False to the boolean **options and no luck. class Cat(models.Model): name = models.CharField(max_length=32, null=True) available = models.BooleanField() -
Django Model Form is Failing Validation with Defaults Set in Model
Background: I am trying to implement a new user registration flow that adds in a verification step (using OTP) for their phone number and email address. Multiple forms are being submitted via JS and the edited in the views.py def registration(). Goal: Validate all of the forms and then save them Issue: My Customer forms will not validate. I am getting the following errors: {'status': [ValidationError(['This field is required.'])], 'customer_number': [ValidationError(['This field is required.'])], 'payment_term': [ValidationError(['This field is required.'])], 'discount': [ValidationError(['This field is required.'])]} What I have tried: I have tried to use both a Model form and a non-model form to no avail. When I use a non-model form I get a "Object has no save function" and when I use the Model form then I get the above stated error. I am not sure why I cannot submit this form with the fields being blank as they all have a default set. models.py class Customer(BaseModel): status = models.CharField("Status", max_length=2, choices=STATUS_OPTIONS, default="A") customer_name = models.TextField("Customer Name", max_length=100, unique=True) customer_number = models.TextField(max_length=19, unique=True, default=get_customer_number) phone_number = models.CharField(max_length=16, unique=True) payment_term = models.CharField("Payment Terms", max_length=4, choices=PAYMENT_TERM_OPTIONS, default="100P") discount = models.DecimalField("Discount", max_digits=2, decimal_places=2, default="0") views.py def register(request): if request.user.is_authenticated: return HttpResponseRedirect('/portal') if request.method … -
How can I solve syntax error in yaml file when pushing to github?
I'm using postgresql with django. I set a github action that verifies my code whenever I push or pull, and I get the following error: You have an error in your yaml syntax on line 19 Here is my yaml: # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest services: postgres: image: postgres:14 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: github_actions ports: - 5433:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python 3.9.7 uses: actions/setup-python@v2 with: python-version: "3.9.7" - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Test with Unittest env: SECRET_KEY: ${{secrets.SECRET_KEY}} EMAIL_FROM_USER: ${{secrets.EMAIL_FROM_USER}} EMAIL_HOST_PASSWORD: ${{secrets.EMAIL_HOST_PASSWORD}} DB_NAME: ${{secrets.DB_NAME}} DB_USER: ${{secrets.DB_USER}} DB_PASSWORD: ${{secrets.DB_PASSWORD}} DB_HOST: ${{secrets.DB_HOST}} DB_ENGINE: ${{secrets.DB_ENGINE}} DB_PORT: ${{secrets.DB_PORT}} run: | python3 manage.py test line 19 corresponds to image: postgres:14 but I can't see any syntax error here. I've looked at some examples and it looks exactly the same. -
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