Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign constraint failed on django model instance
I try to create a model instance upon an action. I can't get the process to a succes. I receive an error message, and I'm stuck. Here is the view @login_required(login_url='/login/') def return_book(request,pk): books = Books.objects.filter(school = request.user.school).get(id = pk) if books: Return.objects.create(borrowed_item_id=books.id,returner_id=request.user.school.id) return redirect("view_books") The models class Books(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) reg_no = models.CharField(max_length=50) book_name = models.CharField(max_length=200) class Issue(models.Model): borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) class Return(models.Model): return_date = models.DateField(default=datetime.date.today) borrowed_item = models.ForeignKey(Issue,on_delete=models.DO_NOTHING) returner = models.ForeignKey(CustomUser,on_delete=models.DO_NOTHING) And the traceback Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\views.py", line 216, in return_book Return.objects.create(borrowed_item_id=pk,returner_id=request.user.school.id) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, … -
django Select_related(): from another model has a ForginKey To the model that will execute Select_related
I have two model, one for Question and two for answer tow have a forginkey to one and one have a forginkey to users for this purpose I use a To be grouped together at the same endpoint I add the second to the first in serializer With this solution, Django accessed the database with the number of answers in the second form and I cannot use Select_related here the question is, how can I reduce database hits to the second model Models.py class Consultation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() create_at = models.DateTimeField(auto_now_add=True) files = models.FileField(upload_to="media/files", null=True, blank=True, validators=[FileExtensionValidator(['pdf', 'jpg', 'png'])]) def __str__(self): return self.user.username class Meta: ordering = ['-create_at'] class ConsultaionAnswer(models.Model): consultation = models.ForeignKey( Consultation, on_delete=models.CASCADE, related_name='reply') answer = models.TextField(null=True, blank=True) def __str__(self): return self.consultation.content[:20] + "..." serializers.py class ConsultaionAnswerSerilaizers(serializers.ModelSerializer): class Meta: model = ConsultaionAnswer fields = ('answer',) class ConsultationSerilaizers(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) username = serializers.StringRelatedField( source='user.username', read_only=True, ) reply = ConsultaionAnswerSerilaizers(read_only=True, many=True) class Meta: model = Consultation fields = ( "id", "user", "content", 'create_at', 'files', 'username', "reply" ) views.py class ConsultationView(APIView): serializer_class = ConsultationSerilaizers def get(self, request, format=None): consultat = Consultation.objects.select_related().filter(user=request.user) serializer = self.serializer_class( consultat, many=True, context={'request': request}) return Response(serializer.data) django debug tool … -
how to add paypal and keep save data to user after buy
i want ask simple question : how to use / add paypal instead of razorpay in my app here is my simple app it's for checkout ( for buy digital products ) but it's use razorpay and i want to use paypal , does anyone can help me and edit my app to add paypal app link : https://gofile.io/d/x7Enng -
are there an equivalent of django mixin in node js?
So, I'm new to Node and I have a background with Django so there is a Mixins you can add to impose certain authorization on your models such as only login users can see this or only the owner of model can edited. Are there any equivalent for that in node or I should right them on my own? -
static filters rendering as strings in template
I am returning a valid HTML string that I'm rendering in a template, but specific {% ....%} is rendering as a literal, even after applying the safe filter. return "<button type='submit' value='Save'>Save<svg>{% load static %}<use xlink:href='{% static 'svg/icons.svg' %}#save'></use></svg></button>" I am rendering like this {{ html_string|safe }} {% load static %} and {% static 'svg/icons.svg' %} are rendering as literal strings, not processed by Django template engine. How can I render {% load static %} and {% static 'svg/icons.svg' %} properly if I'm building the string outside of the template? -
Django DTL for Frontend
I want to ask a question, that Django provides us with Django Template Language (DTL), when we write HTML and CSS code in the DTL does it considered as Frontend? As we are rendering HTML and CSS code in DTL just like we do in all other Frontend stack framework. Django Template Language (DTL) is just like Embedded JavaScript. Embedded JavaScript is considered as language for Frontend than why Django Template Language is not? I heard from someone he was saying that Django is only for server side code it has nothing to do with Frontend. Kindly help me out. -
E: Unable to locate package psql
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up # I had to wait for 2 minutes and do CTRL+C in order to give the database to start docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 … -
Secure authentification with django graphql jwt reactjs
I did a website using frontend reactjs and back django, using graphQL to communicate with DB. I need to post data on a database (with a form accessible just when the user is logged in). For now I am able to connect it and get a token with jwt. but I did not succeed to post data on the database with graphQL with the token, and having a "unauthorized" page when token is not valid (unlogged). Can please you guide me to a good tutorial which can help me how to do that? I am searching and I am non founding anything useful... Thanks a lot in advance for your help ! -
Django unkown field
My django server is returning line 276, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (name) specified for Planet my forms.py file is from django import forms from .models import Planet class PlanetForm(forms.ModelForm): """a form to enter a new planet""" class Meta: """docstring for Meta""" model = Planet fields = ['text'] labels = {'text': ''} the function in views.py that would run the function in forms.py is as such def new_planet(request): """add a new planet""" if request.method != 'POST': # no data submitted; create a blank form form = PlanetForm() else: #post data submitted; process data form = PlanetForm(data=request.POST) if form.is_valid(): form.save() return redirect('HelloWorlds:planets') # display a blank or invalid form context = {'form': form} return render(request, 'HelloWorlds/new_planet.html', context) This is the way i know how to create forms on django. i have tried changing the forms.py as per the official documentations but that returned views.py, save() not defined on form from PlanetForm. Sorry if my technical terms are completely wrong -
Failure calculating Percentage of A django model
I intend to calculate 8 percent compound interest of the amount invested every ten days- something like a 10 days countdown and when the ten days countdown is over then another 10 days countdown should begin. The 10 days count will begin immediately the amount is deposited and the percent will be added to the balance only after ten days. The percentage countdown calculation should begin on request by the user or immediately after deposit. This questions is a question I have not been able to find solution to. I hope there is a solution now class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) added = models.DateTime() request_time = models.Daterime() def percentages_in_ten_days(self): return self.amount *0.08 I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self, day=10): pef_of_amount = Investment.objects.filter([x for for x in get_percentage_ten_days]).annotate(day=Sum('x')) return get_percentage def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance -
DRF writable serializer for GenericRelation in django
I'm trying to have a writable serializer that creates/updates a model and its GenericRelation target in a single API class TaggedItem(models.Model): tag_name = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') class Note(models.Model): text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) In the above, I would like to support a create/update end-point on Note. The data would be: { "text": "something", "tags": [ { "object_id": "1" "tag_name": "something" }, { ... ... } ] } The documentation only has the following brief note: Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. One option of course is to override create, update in NoteSerializer, extract the TaggedItem data and call the TaggedItemSerializer manually. However, since Note is a GenericRelation target from multiple models, I want to avoid doing this on every source model Is there a better way ? As best as I can tell, all the information needed to create these objects is present since the target of the relationship is known...so I'm hoping this pattern is a first-class-citizen with DRF. Haven't found anything yet. -
Running Django Test on CircleCI - django.db.utils.OperationalError: FATAL: role "circleci" does not exist
hope you are fine: as i'm trying to use django with circleCI, i have the following as my settings.py database configuration: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME':'default_db', 'USERNAME':'postgres', 'PASSWORD':'default_pass', 'HOST':'localhost', 'PORT':'5432', } } and on circleCI config.yml (same user, db and password): environment: POSTGRES_USER: postgres POSTGRES_DB: default_db POSTGRES_PASSWORD: default_pass and i get django.db.utils.OperationalError: FATAL: role "circleci" does not exist, from a previous question it seems when running postgres inside docker, there might be some problems regarding the port as postgres also running locally, but i don't know if this is the same case here, any help would be appreciated. circleCI executor: docker. circleCI db image: circleci/postgres:latest-postgis -
Django Custom Queryset managers: Implicit chained filter()?
In Django, when it comes to M2M relationships, we know that these two queries: MyModel.objects.filter(othermodel__attr1="someval1", othermodel__attr2="someval2") MyModel.objects.filter(othermodel__attr1="someval1").filter(othermodel__attr2="someval2") Will not necessarily return the same results (docs). I've recently started utilizing custom QuerySet managers and it suddenly dawned on me that I may get this undesired behavior (for me at least) if I'm doing something like this: # defined as customobjects = MyModelQuerySet.as_manager() in `MyModel` class MyModelQuerySet(models.QuerySet): def method1(self): return self.filter(othermodel__attr1="someval1") def method2(self): return self.filter(othermodel__attr2="someval2") and using MyModelQuerySet like this: results = MyModel.customobjects.method1().method2() Then I may be getting the behavior of chained filters. For me this makes using a custom QuerySet manager completely useless as I need an AND behavior most of the time. But I'm not sure this is indeed the behaviour. If it is, are there are any workarounds while using managers? (I want the ability to flexibly use different filters and mix and match them with managers, but I don't want the chained filters behavior) -
Django, React encountered static file 404 error. Is there any solution?
In Dango, index.html of React is successfully displayed, but it is not rendered and only white blank pages are displayed. Below are my settings. /etc/nginx/sites-available/mystar.conf: django setting: dir tree: site error: React is shown by setting the build folder from the template of Janggo. How can I solve the above error? -
Trouble with writing view in django
So I have the following models in my Django app: Models.py class Cia(models.Model): confidentiality = models.BooleanField(default=False) integrity = models.BooleanField(default=False) availability = models.BooleanField(default=False) def __str__(self): return '%s, %s, %s' (self.confidentiality, self.integrity, self.availability) class security_incident(models.Model): asset = models.CharField(max_length=200) actor = models.CharField(max_length=200) action = models.CharField(max_length=200) cia = models.ManyToManyField(Cia) def __str__(self): return self.asset class attack(models.Model): name = models.CharField(max_length=100) defense_mechanism = models.CharField(max_length=100) action = models.ManyToManyField(security_incident) def __str__(self): return self.name class adtree(models.Model): goal = models.CharField(max_length=200) security_incident = models.ManyToManyField(security_incident) cia = models.ManyToManyField(Cia) def __str__(self): return self.goal the adtree model should be rendered into a tree structure like this: Database (root node/asset) --Confidentiality ---Security Incident ----Attack --Integrity ---Security Incident ----Attack --Availability ---Security Incident ----Attack So this is the usecase: A user inputs the root node (asset) of a tree in this form, and selects the checkboxes the user wants to see: <form method="GET" action="."> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="goal" placeholder="Enter goal of ADT (asset)" /> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="confidentiality" name="confidentiality"> <label class="form-check-label" for="confidentiality"> Confidentiality </label> </div> </div> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="integrity" name="integrity"> <label class="form-check-label" for="integrity"> Integrity </label> </div> … -
Django in python
What I do ?Docmas.profile.user: (fields.E300) Field defines a relation with model 'app.Model', which is either not installed, or is abstract. Docmas.profile.user: (fields.E307) The field Docmas.profile.user was declared with a lazy reference to 'app.model', but app 'app' isn't installed. : from django.db import models from django.contrib.auth.models import User class profile(models.Model): user = models.OneToOneField("app.Model", verbose_name=("user"), on_delete=models.CASCADE) name= models.CharField(("NAME:"),max_length=30) who_i = models.TextField(("Who are You?"),max_length=120) price= models.IntegerField(("what is your price?")) class Meta: verbose_name = ('profile') verbose_name_plural = ('profile') def __str__(self): return self.name -
Django Query - Return All objects that have been referenced at least once in a model
I have two models. Employees and Schedule class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=20) class Scheduled(models.Model): title = models.CharField(max_length=50) description = models.TextField() assigned_employee = models.ForeignKey(Employee, on_delete=models.CASCADE) I want to return all employees that have been referenced at least once in Scheduled table. Note: I have done it with 2 queries, but is there a way to do this in just one query? -
NoReverseMatch Django url parameter passing
I am trying to pass a string parameter to a url and I keep getting this error. Reverse for '' not found. '' is not a valid view function or pattern name. on this url urlpatterns = [ path('dashboard/<str:filter>/', views.dashboard, name='dashboard'), ] root urls urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('users.urls')), path('', include('app.urls')), # dashboard comes from here ] this is how I pass the parameter href="{% url 'dashboard' 'create_time' %}" -
django tutorial02 "playing with the api"
okay so i have been following the django tutorial perfectly up untill the "Playing with the API" point. Now here's my problem. I got to the point where i had to add def __str__(self): to my code. I did exactly what the tutorial said and when it got to the point that i had to restart the shell i pressed ctrl+z to exit the shell then i started the shell again. The only problem is that when it got to making sure that the __str__() addition worked. It didnt. ive been stuck on this for the past week and i really want to move forward. ive looked at everybodys opinion that ive seen and none of the solutions worked. from my point of view i dont know what i did wrong. someone help please. im using python 3.9.2 by the way. the only place im not sure of was the restarting of the shell. -
Python django, check if sql column contains a value
Is there a way to check if a table column already contain a value without using a for loop? Does django have a "not in" syntax? -
How to merge two model in a signal from django?
I want to merge two model in a signal from which I am using for update my blog post. here is my code: models.py class Post(models.Model): title = models.CharField(max_length=300,unique=True,error_messages={'unique':"This title already exists. Please use different title"}) author = models.ForeignKey(User, on_delete=models.CASCADE) class HeaderImage(models.Model): header_image = models.ImageField() #I want to merge this model with Post model and want to add image field in my current forms. froms.py class BlogPost(forms.ModelForm): class Meta: model = Post fields = ['title','author','body'] views.py class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost How to get image filed from second model and add it to existing from which using first model? -
Where to query model if not in model.py?
I have a model.py that looks as such: from django.db import models import requests import pandas as pd from datetime import timezone from datetime import datetime from datetime import date from datetime import timedelta import time class cryptoData(models.Model): coin = models.CharField(max_length=10) asset_id = models.SmallIntegerField() time = models.DateTimeField() close = models.FloatField() volume = models.BigIntegerField() market_cap = models.FloatField() reddit_posts = models.IntegerField() reddit_comments = models.IntegerField() tweets = models.IntegerField() tweet_favorites = models.IntegerField() social_volume = models.IntegerField() def apiFunc(): #pull data from API and put into df return(df) df = apiFunc() cryptoData.objects.bulk_create( cryptoData(**vals) for vals in df.to_dict('records') ) However, as I understand from reviewing other threads, it is not in best practice to query the database in the same file as model.py. Where then should I house the code that loads data into my created model? -
How do I manage django reusable app urls for different environments?
I am creating a Django reusable app with django rest framework DRF. I defined at first this urls.py file. (omit imports for shortness) urlpatterns = [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'admin/', admin.site.urls), path('core/v1/', include(ApiRouter.get().urls)), # I define here url paths for models ] The problem is that when I build this app, and I installed it on another project. There are going to show up all the api-auth and admin urls from the reusable app in the other project. I came with this idea: Create two url files (for local dev and for build), and use an env variable to use one or another. And I implemented like this: Define an env variable in for example env.ini dev_mode=False Then in project settings file: DEV_MODE = get_var_from_env_file(‘dev_mode’) if DEV_MODE: ROOT_URLCONF = 'myproject.urls_dev' else: ROOT_URLCONF = 'myproject.urls' And so in urls.py I will have only url relative to models and in urls_dev all. urls.py urlpatterns = [ path('v1/', include(ApiRouter.get().urls)), ] urls_dev.py urlpatterns = [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'admin/', admin.site.urls), path('core/v1/', include(ApiRouter.get().urls)), # I define here url paths for models ] Is there a standard way to manage this? Or is there a better approach? -
How to implement a double sided referral program with Stripe Checkout?
we're selling access to our product which has a monthly/yearly subscription. We're using Stripe Checkout to manage our subscriptions. How do I implement double sided rewards for our users (e.g. if a friend signs up with someone's promo code, they both get $25 off the price of their subscription). -
Dropdown menu should only show user created data from the field with Django
A disclaimer that I'm new to programming so please take it easy on me. :) I have authentication set up and users that log into my Django website. I have two forms that the user can fill out. Patient and Script. The Script form and view of ScriptCreateView has a patient field that should only show patients that that user has entered. Currently the dropdown shows all patients all users has entered. I have googled my head off and can't seem to figure it out. Any assistance would be appreciated. Models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Patient(models.Model): patient_name = models.CharField(get_user_model(), max_length=40, unique=True) num_cycles = models.PositiveIntegerField(verbose_name='How Many Cycles Will This Patent Have') cycle_length_days = models.PositiveIntegerField(verbose_name='How Many Days Will Each Cycle Be') treatments_per_cycle = models.PositiveIntegerField(verbose_name='How Many Treatments Will Be In Each Cycle') cycle_start_day = models.DateField(null=False,verbose_name='What Is The Date Of The First Cycle') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.patient_name def get_absolute_url(self): return reverse('patient_detail', args=[str(self.id)]) class Script(models.Model): patient = models.ForeignKey(Patient, on_delete=models.SET_NULL, null=True, verbose_name='Patient Name') author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) drug_name = models.CharField(max_length=40, unique=True, verbose_name='Name Of Drug') drug_instructions = models.CharField(max_length=250, verbose_name='Detailed Instructions') drug_start_day = models.DateField(null=False, verbose_name='First Day To Take This Drug') …