Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist at /home/
I'm following a video tutorial but Im getting an error. The only differance is that author uses Subline Text, while i use VSCode what is causing the error? enter image description here here's my views code: from django.http import HttpResponse from django.shortcuts import render def about(request): return HttpResponse("Inforamation about") def home(request): return render(request, 'home.html') here's my urls code: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/', views.about), path('home/', views.home), ] and my settings code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
update model field when events occurs in django
I have a patient model and one dateTimeField field, i need to update this data when an event occurs patient.py class Patient(Tenantable): lastVisitDateTime = models.DateTimeField(null=True) and event.py class Event(Tenantable): patient = models.ForeignKey( Patient, related_name="events", on_delete=models.CASCADE ) what i should do? -
Getting bytes written to SQL database for integer column, want integer to be written
I am writing data from a dash app to a SQL database setup by Django and then reading back the table in a callback. I have a column that the value should either be 1 or 2 but the value is as below in the SQL database: SQL Database view of column that should contain 1 or 2 When this is read back to a pandas dataframe it appears as b'\00x\01x... or something along those lines, which then gets read wrong when it needs to be used. The django code for the column is: selected = models.IntegerField(default=1, null=True) I am writing and reading the data using SQLAlchemy. Number appeared perfectly in pandas dataframe before involving SQL. Read and write code: select = pd.read_sql_table('temp_sel', con=engine) select.to_sql('temp_sel', con=engine, if_exists='append', index=False) Any help would be appreciated. -
Django form validation based on custom function that calls api to validate form input value
I've been trying to look around for resources on how to do this, but no luck so far. Any direction would be appreciated! I'm attempting to run a custom function on a Django form as validation. So, how it would work is: User submits form Within the validation, there is a function that calls an external API with the input value If the API returns a valid response, the form submission completes successfully If the API returns an error, the form validation is failed and a notification is returned to frontend with error. Any direction on how this could be accomplished would be appreciated! -
Can't get the Profile instance that have logged user as field
So i have here a 'create_project' view where l’m trying to assigne to the 'owner' field of project instance created a 'profile of the current user logged . so it's show a error says: DoesNotExist at /projects/create-project/ Profile matching query does not exist. create_project view : def create_project(request): # create operation form = projectForm() if (request.method == "POST"): form = projectForm(request.POST,request.FILES) if form.is_valid(): # check if it valid project = form.save(commit=False) project.owner = Profile.objects.get(user=request.user) project.save() return redirect("home") context = {'form':form} return render(request, 'projects/project_form.html',context) Project Model Class: class project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) Profile Model Class: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) -
Flask SQLAlchemy Columns
I want to make a blog where a user can make posts. And I want the title of the post to be unique. But when I try to make a post and the post already exists returns an error. But when I write a try it still returns an error. Why does this happen? @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): try: allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) post2 = Post.query.all() db.session.add(post1) db.session.commit() # error, there already is a user using this bank address or other # constraint failed if sear != 2: flash('We couldnt make your post') except: flash('Error') return render_template('posts.html') class Users(UserMixin,db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(200),unique=True,nullable=False) password = db.Column(db.String(200),unique=False,nullable=False) role = db.Column(db.String(200),unique=False,nullable=False) missions = db.Column(db.String(200),unique=False,nullable=True) waiter = db.Column(db.String(200),unique=False,nullable=False) posts = db.relationship('Post',backref='user') class Post(db.Model): … -
Decorator @property on ASP net core like in django
The thing is that like in Django which you can add model properties without changing the model class using the @property decorator. I'm trying to achieve same with aspnetcore I mean I want to add some functions to the model class which will return some string/int in order to access to them from the razor view(ex: model.extraProperty) Someone could help me to address this? -
Exempt Django Cross Domain Password Reset from CSRF token
I have a separate front end and backend site and am trying to enable users on the front end to reset their password. I have created an endpoint for them to do so which works when accessed via the backend site. But when I try to access the endpoint via Insomnia I get a 403 CSRF verification failed. Request aborted. error. I have added my front end ddomain to the CORS_ORIGIN_WHITELIST class PasswordResetView(auth_views.PasswordResetView): template_name = 'users/reset_password.html' @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) Is there some other method that I must also make csrf_exempt? -
How to use exchanged token with OAuth2 - social-auth-app-django
I'm trying to implement OAuth2 authentifications using social-auth-app-django. My backend can exchange an authorization token that I get from a frontend using providers SDK, I will give Apple as an example: My iOS app gets an authorization token from the user using "Sign in with Apple". I then sends this token to the backend so I can exchange it using this view: @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token_view(request, backend): serializer = SocialSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print("Backend:", backend) print("Token:", serializer.validated_data['access_token']) # set up non-field errors key # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views try: nfe = "non_field_errors" except AttributeError: nfe = 'non_field_errors' try: # this line, plus the psa decorator above, are all that's necessary to # get and populate a user object for any properly enabled/configured backend # which python-social-auth can handle. user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: # An HTTPError bubbled up from the request to the social auth provider. # This happens, at least in Google's case, every time you send a malformed # or incorrect access key. return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) print() return Response({'token': token.key}) else: # user is not active; at some point they deleted their … -
PostgreSQL or Firebase Firestore DB for Django E-Commerce Web App (and Android & iOS App)
I am building an e-commerce website with customers and sellers with Django (as well as iOS and Android apps with React Native). I want to use the Firebase Firestore Database but I can't get it to work with Django (there are also almost no tutorials online..). For PostgreSQL there are a lot of tutorials online and I've already once used it in another Django project. Which is better for a Django e-commerce website (and React Native mobile apps)? -
Django Limit the Number of objects in a model
i am working on a django-cms project and (i have to make a image model which can only make 3 objects not more than that if someone tries there should be a message: Max Objects Have been Created) so, how can i limit the number of objects in a model ? Thank you, I will Really appreciate you feedback. -
Create an account from django-admin
In my CRM, the owner of the company gives the first password and email for new employees. Employee can change them later (I don't need to show them in admin, which is not allowed by django by default). But how to show the fields for giving the first password in admin? For examplle fields - "Password for new user" and "Again password for new user" models.py class CustomUser(AbstractUser): [...] def __str__(self): return self.email admin.py from django.contrib import admin from .models import CustomUser admin.site.register(CustomUser) I need this effect: -
Pyscript in Django application
I am wondering if we could use pyscript on HTML pages inside a Django project. I'd tried to use it but unfortunately, it doesn't work. Any suggestions? -
How do I preserve search result in Django pagination
I am new to Django and I have develop form with Country and State field from the Profile Model. And I want a situation where if I search for country and a particular state, a list of persons belonging to that country and state should be display and paginated. And if the records are in multiple pages then I should be able to click on individual pages that follow to view the searched results on those pages without loosing the search results. Here is my views code with pagination. def search_applicants(request): form = ApplicantsSearchForm(request.GET or None) if form.is_valid(): list_submited = Profile.objects.filter( nation__icontains=form.cleaned_data['nation'], state__icontains=form.cleaned_data['state'] ) else: list_submited = submited_apps.objects.all() paginator = Paginator(list_submited, 5) page = request.GET.get('page') paged_listApps = paginator.get_page(page) context = { 'list_applicants':paged_listApps, 'form':form, } return render(request, 'user/list_applicants.html',context) You may wish to understand that I have got the pagination of all records from the Profile Model but any time I perform a search and try to click on the pagination tabs the search result is get scattered and returns to all the list items in the database. Someone should kindly help. Thank in anticipation to your answer. -
Django Migration from Github actions
Hello I have a database in Google Cloud Platform and I am trying to figure out how to run a django migration from github actions once I have deployed my app to GCP's App engine. I have tried using cloud_sql_proxy, but cannot get it to connect to my database. I would whitelist github actions ip address but I am not really sure what the ip addresses is either. Here is the config I currently have: # .github/workflows/deploy # https://cloud.google.com/python/django/appengine # https://github.com/actions-hub/gcloud: name: deploy-app-to-gcp on: push: branches: [ main] paths: - '**' jobs: migrate: name: Migrate Database runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: get env file run: echo "${{secrets.ENV_FILE}}" | base64 --decode > ./env_variables.yaml - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Get Cloud SQL Proxy run: | wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy chmod +x cloud_sql_proxy - name: migrate Database env: DATABASE_CONNECTION_ADDRESS: 127.0.0.1 run: | pip install ruamel.yaml set -a; eval $(python -c 'from pathlib import Path;from ruamel.yaml import YAML; print( "".join( [f"{k}={v!r}\n" for k, v in YAML().load(Path("env_variables.yaml"))["env_variables"].items() if not k.__eq__("DATABASE_CONNECTION_ADDRESS")] ) )'); set +a ./cloud_sql_proxy -instances=com-cjoshmartin:us-central1:cms-db=tcp:5432 & python … -
In Python how can I overwrite the class attribute of an inherited class, where that attribute is itself an instance of a model
As in the title, I have a base class ListView, with a Serializer attribute that needs overwriting. For each of my django models I create a child ListView class and a Serializer. So for example for the django model Event we have a corresponding view class EventListView(ListView), and we have a corresponding Serializer class EventSerializer(Serializer). The Serializer child class is specified within the ListViewClass, as in my code below. Is it possible to have the serializer overwritten automatically based on the value supplied to model, and how may I mark model and Serializer as attributes that are to be overwritten adn therefore do not need values specified in the base class? Many thanks class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = 'all' class ListView(APIView): model = # Event is set as the default. Serializer = queryset = model.objects.all() def get(self,request): # !!! Get filter conditions from request queryset = ListView.queryset.filter() # !!! Filter conditions serializer = ListView.Serializer(queryset,many=True) return Response(serializer.data) def post(self,request): data = JSONParser.parse(request) serializer = ListView.Serializer(data = data) if serializer.is_valid(): return Response(serializer.data, status = 201) else: return Response(serializer.errors, status = 400) class EventListView(ListView): model = Event -
Django 3.2: AttributeError: 'NoneType' object has no attribute 'attname'
I am working with Django 3.2, and have come across a problem that seems to have answers here and here also, and I have tried the solutions offered in the accepted answers, but have not been able to resolve the issue I am having (error message in subject title). Here is what my models look like: #### models.py class ActionableModel: def __init__(self, parent_object): self.parent = parent_object # FIX: This might be an expensive operation ... need to investigate if isinstance(parent_object, django.contrib.auth.get_user_model()): self.owner = parent_object self.actionable_object = parent_object else: self.owner = self.parent.get_owner() self.actionable_object = self.parent.get_actionable_object() self.owner_id = self.owner.id self.ct = ContentType.objects.get_for_model(self.actionable_object) self.object_id = self.actionable_object.id # ... class Prey(models.Model): # ... fields pass class Predator(models.Model, ActionableModel): catches = GenericRelation(Prey) catch_count = models.PositiveIntegerField(default=0, db_index=True) last_catch = models.DateTimeField(editable=False, blank=True, null=True, default=None) def __init__(self, *args, **kwargs): ActionableModel.__init__(self, *args, **kwargs) # ... class Meta: abstract = True # Classes used for testing - naming similar to [mommy](https://model-mommy.readthedocs.io/en/latest/basic_usage.html) class Daddy(): def __init__(self, *args, **kwargs): ActionableModel.__init__(self, *args, **kwargs) class Foo(Daddy, Predator): # ... pass In the shell, I type the following: from myapp.models import Foo admin = django.contrib.auth.get_user_model().objects.all().first() foo = Foo.objects.create(parent_object=admin) Here is the stack trace of the error that results in the subject title: Foo.objects.create(parent_object=admin) Traceback (most … -
How to remove extra puncuation marks during saving forms data in django?
when ever i add data to the form i got extra puncuation marks in the value as shown in the image. for example - name = xyz while saving i get name = ('xyz',) This image is for refrence -
How to use a CNN code in python inside a website?
I have website with backend in Python (Django) and JavaScript hosted on heroku. I want to use an external code that is working on Google Colab, this code uses CNN to do image classification. My idea is that user upload an image through the website then the code that is written in python in Google Colab does the classification and returns the result to the website. Does anyone know what would be the best way to do this? -
Flask SQLAlchemy Unique Column Problems
I want to make a blog where a user can make posts. And I want the title of the post to be unique. But when I try to make a post and the post already exists returns an error. But when I write a try it still returns an error. Why does this happen? @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): try: allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) post2 = Post.query.all() db.session.add(post1) db.session.commit() # error, there already is a user using this bank address or other # constraint failed if sear != 2: flash('We couldnt make your post') except: flash('Error') return render_template('posts.html') class Users(UserMixin,db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(200),unique=True,nullable=False) password = db.Column(db.String(200),unique=False,nullable=False) role = db.Column(db.String(200),unique=False,nullable=False) missions = db.Column(db.String(200),unique=False,nullable=True) waiter = db.Column(db.String(200),unique=False,nullable=False) posts = db.relationship('Post',backref='user') class Post(db.Model): … -
Webhook vs Polling Django
I have a doubt about which technology to use, I am developing a project that will have three parts as in the image below, the first and the front in react js, the second would be the back in python django, and the third that will be deliver written in pure python (runs on pc) that will do calculations and physical simulations that can take up to days to run, all environments will be running on aws. For this communication I thought of taking these functions written in pure Python and transforming them into django, and using them as a service, but the question would be whether I use polling or webhooks to do this process, since the physicists gave me the calculations, but there is no a lot of documentation about them, just the minimum to run, I wanted to change the code as little as possible, so I thought about polling, react keeps asking if it's finished, and if it has an error it says it gave an error, I believe the webhook to see if it gave an error and return would need to change the code more, what do you advise? -
Object is not subscriptable python error django
I have this function where i am using models 'Start' and 'End' that contain fields latitude and longitude.. and I am trying to match them with a field called elements that I am using subscript to extract the start_id and end_id and match them with 'Start' and 'End' The function in question that is giving me a subscript error is: def dispatch(request): events = Event.objects.filter(description="Dispatch").values("element") starts = Start.objects.all() ends = End.objects.all() # subscript error fixed d_starts = { s.start_id: s for s in start } # subscript error fixed d_ends = { c.end_id: c for c in end } d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]], 'end': d_ends[e['element'][69:75]] } for e in events ] for d in d_start_end_ids: # Error is here data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])} JsonResponse(data) I am getting an error saying: line 33, in dispatch_data data = '[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude']) TypeError: 'Start' object is not subscriptable] My Start model is: class Start(models.Model): start_id = models.CharField(primary_key=True, max_length=100) name = models.CharField(max_length=150) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) please help -
Update array of ManyToMany field in Django REST framework
I have a Model Plot which looks like this: from django.db import models class Plot(models.Model): class SUNSHINE(models.TextChoices): NONE = None FULL_SUN = 'Plein soleil', SHADOW = "Dans l'ombre", SUNNY = 'Ensoleillée', MODERATE = 'Modérée' name = models.CharField(max_length=50) garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) width = models.CharField(max_length=50, blank=True, null=True) height = models.CharField(max_length=50, blank=True, null=True) exposition = models.CharField(max_length=50, choices=SUNSHINE.choices, default=SUNSHINE.NONE, blank=True, null=True) qr_code = models.CharField(max_length=50, blank=True, null=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) def __str__(self): return self.name With a plant object which is a foreign key of the model of the same name. And I have this partial_update function in my view: class PlotViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Plot.objects.all() def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) serializer = WritePlotSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) But when, in my front, I want to update the plants in my plot, I can select several of them and when I click on add it works it updated, but it deleted the old plants present or I would like that when I update, it keeps the plants that were already present in the array then it adds the one we just added. How can I do to get this result? Here is my serializer of Plot … -
How to create sitemap with dynamic sub sitemap structure in django?
I'm trying create a dynamic generate sitemap in django and i hit the wall. Action I'm trying to code: in url.py i have url: re_path(r'sitemap-jobs.xml$'...) the above web address triggers function: MonthlyJobsSitemap in sitemap dict whose create sub sitemap divided by months like: http:/host/sitemap-pl-jobs-2022-01.xml The result is address in robots.txt sitemap: /sitemap-pl-jobs.xml. After entering there are files splitted on monthly files: /sitemap-pl-jobs.xml-2022-01. And after entering the monthly sitemap i wanna see addresses to jobs published on web site. I don't have problem with create one sitemap with all jobs but i have to split it into monthly sitemaps. Someone have any idea how to code that in django? -
How to delete multiple records from different classes in django?
It seems that whenever I delete records I get server error (500), I'm knew in web development so I don't know what's causing the problem please help... these are my classes in models.py where I would like to delete records from: class Bscs1_1(models.Model): idNumber = models.CharField(max_length=15) CC100 = models.FloatField() CC101 = models.FloatField() resultCS11 = models.IntegerField() courseCS1 = models.TextField() class Cs(models.Model): cs_count = models.TextField() class Retention_cs1(models.Model): retention_count = models.TextField() And this is how I add records from views.py: def resultCS1_1(request): CC100 = request.POST['CC100'] CC101 = request.POST['CC101'] prediction = model1.predict([[CC100,CC101]]) studentID = request.POST['studentID'] student1 = Bscs1_1() student1.idNumber = studentID student1.resultCS11 = prediction student1.CC100=CC100 student1.CC101=CC101 student1.save() courseCS1 = Cs(cs_count='BSCS1') courseCS1.save() retention = Retention_cs1() if prediction == 0: retention.retention_count = 'NEGATIVE' else: retention.retention_count = 'POSITIVE' retention.save() return render(request, "rCS1_1.html" , {'student1': student1} ) This is how I delete records from all those classes all in one click of a button: def deleteCS12(request, student_id): stud = Bscs1_1.objects.get(pk=student_id) stud.delete() csCount = Cs.objects.get(pk=student_id) csCount.delete() retention = Retention_cs1.objects.get(pk=student_id) retention.delete() return redirect('tableCS12')