Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize default message djangorestframework-simplejwt retrieved when the user is not active?
I'm using Django==4.0.3 ,djangorestframework==3.13.1 and djangorestframework-simplejwt==5.1.0 and djoser==2.1.0 I have used djoser to authenticate, and all works fine. When the user is not active yet, the response is same as when user enter wrong password {"detail":"No active account found with the given credentials"} I need to customize this response. I have checked this message inside a dictionary in the class TokenObtainSerializer default_error_messages = { 'no_active_account': _('No active account found with the given credentials') } have tried to override this class with no success. Any ideas? Thanks -
Why django not storing files in media folder?
My settings.py MEDIA_ROOT='/static/' MEDIA_URL='media' My urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns=[ #all routes ] if settings.DEBUG: urlpatterns+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This code works fine many time but this is not working, I don't know why? -
AWS Elastic BeanStalk - Django Deployment failed (Error: chown /var/app/staging/env/bin/python: no such file or directory)
I am trying to deploy my django application to AWS beanstalk and i get the following error 2022/03/05 08:06:43.401505 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_sourc e_bundle -d /var/app/staging/ 2022/03/05 08:06:45.020761 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging / successfully 2022/03/05 08:06:45.024804 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop run ning the command. Error: chown /var/app/staging/env/bin/python: no such file or directory 2022/03/05 08:06:45.024814 [INFO] Executing cleanup logic 2022/03/05 08:06:45.024928 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAI LURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For de tails, see 'eb-engine.log'.","timestamp":1646467605,"severity":"ERROR"}]}]} My configuration file is as follows option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "src.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "src.wsgi:application" Can someone please tell me what i could be doing wrong? Do note that i am not currently using any environment variables in an external files throught my django settings -
Error while inserting data in database using Ajax in Django after validating the ModelForm
I am creating a Django ModelForm It is partially working as if I do not validate the form i.e. if I remove if form.is_valid(): statement from the code then values got inserted in the database but if I use it, then it shows error in the console as print("Errors ", form_to_insert_data.errors) as: <ul class="errorlist"><li>name<ul class="errorlist"><li>write name</li></ul></li><li>ini_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>dev_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>mid_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_stg<ul class="errorlist"><li>This field is required.</li></ul></li><li>ini_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>dev_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>mid_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>end_kc<ul class="errorlist"><li>This field is required.</li></ul></li><li>root_len<ul class="errorlist"><li>This field is required.</li></ul></li></ul> However, I am inserting all the values properly in the form i.e. noting is left blank. and if I don't pass print("Errors ", form_to_insert_data.errors), then the error appears as Internal Server Error: /url_for_crop_data_to_insert Traceback (most recent call last): File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 188, in _get_response self.check_response(response, callback) File "C:\Python_Abhilash\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 309, in check_response raise ValueError( ValueError: The view waterbalance.views.save_inserted_cropdata didn't return an HttpResponse object. It returned None instead. The code is as below Model from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class CropDetail(models.Model): name = models.CharField(max_length=100) ini_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) dev_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) mid_stg = models.PositiveIntegerField(validators=[MinValueValidator(0.0), MaxValueValidator(100.0)]) … -
Django : What does "%" mean in self.success_messages % fiche.__dict__
Since I've been leaning Python, I have often seen and used : class FicheDeleteView(LoginRequiredMixin, DeleteView): model = Fiche success_url = reverse_lazy('fiche-list') success_messages = "La Fiche %(ref_id)s a bien été supprimée" def delete(self, request, *args, **kwargs): fiche = self.get_object() messages.success(self.request, self.success_messages % fiche.__dict__) return super(FicheDeleteView, self).delete(request, *args, **kwargs) Even if I see this mechanic's effects, I'm not really sure to understand. Does it mean : I send to the "reverse-lazy" all the FICHE dict and in my message.success I retrieve the fiche.ref_id with %(ref_id)s ? -
How to get all id from model in django
views.py e = FRUser.objects.get(id) print(e) models.py from django.db import models from django.contrib.auth.models import User from app_user_mngmt.models.image import Image from django.contrib.postgres.fields import ArrayField from .frtemplate import FRTemplate ## Table for saving FRUser details. class FRUser(models.Model): image = models.ForeignKey(to=Image, on_delete=models.CASCADE, null=True) frtemplate = models.ForeignKey(to=FRTemplate, on_delete=models.CASCADE, null=True) name = models.TextField(null=True) user_type = models.TextField(null=True) uid = models.TextField(null=True) company_name = models.TextField(blank=True, null=True) visit_purpose = models.TextField(blank=True, null=True) employee_number = models.TextField(blank=True, null=True) designation = models.TextField(blank=True, null=True) valid_from_date = models.DateField(null=True) valid_till_date = models.DateField(null=True) valid_from_time = models.TimeField(null=True) valid_till_time = models.TimeField(null=True) is_blacklisted = models.BooleanField(default=False, null=True) is_other_visit_purpose = models.BooleanField(default=False, null=True) How to get all uid from FRUser model in views How to do code for to get all uid from FRUser model database Thanks in advance -
django can't edit js file
I'm trying to edit config file config.js of ckeditor in http://127.0.0.1/static/ckeditor/ckeditor/config.js for django after I add this two line config.allowedContent = true; config.ignoreEmptyParagraph = false; if I refresh the url I get a file without the lines I added CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; }; if I do python manage.py collectstatic --noinput --clear the file return back as it was without the 2 lines I added -
How to specify field choices in django inlineformset
I wish to only display a subset of the choices for a model form field. E.g Depending on the url the user is at I might want only 'weight gain' and 'parkinsonism' displayed as options for the 'se_name' field. I can work out how to get the url as a parameters in the view (p = self.request.GET.get("p", None)) But I cant work out how to use this parameter to limit the choices available. This is the formset SideeffectFormSet = inlineformset_factory( Case, SideEffect, fields=("se_name",), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) Which is based on the model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("weight_gain", "Weight Gain"), ("parkinsonism", "Parkinsonism"), ("dystonia", "Dystonia"), ("none", "None"), ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, default="none") case = models.ForeignKey(Case, on_delete=models.CASCADE) And the form is rendered by this view: class CaseView(LoginRequiredMixin, TemplateView): model = Case template_name = "se_balance/se_balance.html" def get(self, *args, **kwargs): p = self.request.GET.get("p", None) sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none(),) return self.render_to_response( { "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) -
Altering a Django model values based on a few conditionals? What is the best practice way to do this?
I have the model SyncCollector that has the field status. status is one of statusIntervalEnum. I want to change the existing ones that are statusIntervalEnum.DYNAMIC to 'statusIntervalEnum.STATIC. Now I know that I can do a SyncCollector.objects.filter(status=statusIntervalEnum.DYNAMIC) and loop through all of them and save them and perhaps trigger it through a custom endpoint that I later take away, but what is the best way to do this for a production instance? Making a fake endpoint that I just call in prod to run this seems very hacky. -
having this particular problem... in installing react
p reactapp_clones Creating a new React app in C:\Users\Eduur\reactapp_clones. You are using npm 3.5.3 so the project will be bootstrapped with an old unsupported version of tools. Please update to npm 6 or higher for a better, fully supported experience. Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts... npm ERR! Windows_NT 10.0.19042 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\Eduur\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "install" "--no-audit" "--save" "--save-exact" "--loglevel" "error" "react" "react-dom" "react-scripts@0.9.x" npm ERR! node v16.14.0 npm ERR! npm v3.5.3 npm ERR! primordials is not defined npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! https://github.com/npm/npm/issues npm ERR! Please include the following file with any support request: npm ERR! C:\Users\Eduur\reactapp_clones\npm-debug.log Aborting installation. npm install --no-audit --save --save-exact --loglevel error react react-dom react-scripts@0.9.x has failed. Deleting generated file... package.json Done. C:\Users\Eduur> -
Filtering ArrayField by entire and exact array only?
I have a slug ArrayField on a model. How can I filter or get by the entire exact array only? I'm currently doing something like this: search = f'["a", "b", "c"]' list = search[2:-2].split("', '") dict = {} for n, item in enumerate(list): dict[f"slug__{n}"] = item obj = queryset.filter(**dict) However, this returns any object where the slug begins with "a", "b", and "c". E.g. ["a", "b", "c"] ["a", "b", "c", "d"] ["a", "b", "c", "d", "e"] ["a", "b", "c", "123"] How do I do a filter or get so that only the entire and exact slug match returns? I.e. obj only returns objects with a slug of ["a", "b", "c"] -
Need to restrict access to view only their inputted data or assigned data in the django admin
User model class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.OneToOneField(Default_User,on_delete=CASCADE) dob=models.DateField(max_length=8) email=models.EmailField(max_length=25,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneNumberField() emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return str(self.id) Job model class Job(models.Model): job_name=models.CharField(max_length=50) client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client',default=None) #project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project',default=None) project = ChainedForeignKey(Project,chained_field="client", chained_model_field="client",show_all=False, auto_choose=True, sort=True) user=models.ForeignKey(User,on_delete=CASCADE,related_name='user',default=None) hours=models.TimeField(null=True) start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) class Meta: db_table ='Job' def __str__(self): return '{} {}'.format(str(self.id), self.job_name) admin.py class StaffAdmin(admin.ModelAdmin): '''def get_queryset(self, request): qs = super().get_queryset(request) print(f"\nrequest.user : {request.user}\n") if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id)''' def get_queryset(self, request): qs = super().get_queryset(request) user = request.user if user.is_superuser: return qs return qs.filter(user_id=request.user.id) custom user model class Default_User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) email = models.EmailField(max_length=250, unique=True) first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] I have given a privilege for the staff users to view, edit and delete the Job API, but I need to restrict to view only their job assigned to that users and edit and delete the jobs which the user have added. But in the … -
Django restfamework put method not working
I am creating a rest api using DRF the get and post method work perfectly but the put method doesnt update the request this is my views.py from django.shortcuts import render from rest_framework import viewsets # Create your views here. from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from BarakaSalesSystemApp.models import Farmer from BarakaSalesSystemApp.serializers import FarmerSerializer def list(self, request): farmer = Farmer.objects.all() serializer = FarmerSerializer(farmer, many=True, context={"request": request}) response_dict = {"error": False, "message": "All Farmers List Data", "data": serializer.data} return Response(response_dict) def create(self, request): try: serializer = FarmerSerializer(data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Farmers Data Saved Successfully"} except: dict_response = {"error": True, "message": "Error During Saving Farmers Data"} return Response(dict_response) def update(self, request, pk=None): try: queryset = Farmer.objects.all() farmer = get_object_or_404(queryset, pk=pk) serializer = FarmerSerializer(farmer, data=request.data, context={"request": request}) serializer.is_valid(raise_exception=True) serializer.save() dict_response = {"error": False, "message": "Successfully Updated Farmer Data"} except: dict_response = {"error": True, "message": "Error During Updating Farmer Data"} return Response(dict_response) farmer_list = FarmerViewSet.as_view({"get": "list"}) farmer_create = FarmerViewSet.as_view({"post": "create"}) farmer_update = FarmerViewSet.as_view({"put": "update"}) and this is my serializer.py from rest_framework import serializers from BarakaSalesSystemApp.models import Farmer, Customer, Order, Bill, Employee, Delivery class FarmerSerializer(serializers.ModelSerializer): class Meta: model = Farmer fields = ["name", "address", "contact", "in_stock"] When … -
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.