Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap elements cause a reduction in width, which is not a proper behavior
As title says some bootstrap elements changes my whole website width, reducing it by 15px. I think that responsive elements cause this weird behavior. Code: <div class="px-4 py-5 my-5 text-center"> <img class="d-block mx-auto mb-4" src="{%static 'images/tinytools_logo.png'%}" alt="" width="100" height="100"> <h1 class="display-5 fw-bold text-body-emphasis">Tiny Tools - AI powered platform</h1> <div class="col-lg-6 mx-auto"> <p class="lead mb-4">Have you ever dreamt of a website that can instantly answer your questions or help you solve a test? Our advanced platform, powered by the mighty GPT-4, is here to assist you.</p> <div class="d-grid gap-2 d-sm-flex justify-content-sm-center"> </div> </div> </div> <div class="container col-xxl-8 px-4"> <div class="row flex-lg-row-reverse align-items-center g-5 "> <div class="col-10 col-sm-8 col-lg-6"> <img src="{% static 'images/ask_gpt_logo.jpeg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6"> <h1 class="display-5 fw-bold text-body-emphasis lh-1 mb-3">Ask GPT - AI chatbot</h1> <p class="lead">AI chatbot powered by GPT-4 analyzes your question and provides precise answers based on the latest knowledge.</p> <div class="d-grid gap-2 d-md-flex justify-content-md-start"> <button type="button" class="btn btn-warning btn-lg px-4 me-md-2">Tool</button> </div> </div> </div> </div> <div class="container col-xxl-8 px-4 py-5"> <div class="row flex-lg-row-reverse align-items-center g-5"> <div class="col-10 col-sm-8 col-lg-6 order-lg-2"> <img src="{% static 'images/lensgpt_logo.jpg'%}" class="d-block mx-lg-auto img-fluid rounded-circle" alt="Bootstrap Themes" width="500" height="500" loading="lazy"> </div> <div class="col-lg-6 order-lg-1"> <h1 … -
I need to upload to profile pic
using base64 encoded and saved in database b'iVBORw0KGgoAAAANSUhEUgAABZ0AAALkCAYAAABkw5u0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAP+lSURBVHhe7N0JYBTl2Qfwf07CnXCHS4IIBEFJxCpRPIKohGIlFA9SbSteSMADRKv0a1W8ECoKAa2iVgselGClgIoEDwRRJChIuCSIHOFMgIRcm+z3PrMzyexkd7NJNskm/H84bvad2ZnZmXfemX323WcCvv/+ezvIr9jtjl0ijzabDUVFRejQoQPat2+PsLAwBAUFaeOJiOqLtE35+fnYv38/8vLyEBISorVNAQEBWtsljzIQEdUn45qK7VHDZuxHM1dlZubxlU1bHbUxTyLyrDbacvM8K5u/q/E8vxARucegs58xLmDlUYI6BQUF6N27N9q0aaOVExH5mz179uD48eMIDQ0tCzwLXoQTEZGveAryVhYA9scAsT+uE1F9qc... I need to upload profile pic I need to display image in circle in circle i need to get image from data base when user is login -
Live dashboard: django, dash or else?
I'm new to this kind of development, so I write hoping to have a feedback. I need to build a dashboard displaying several parameters (# ~100) taken from an OPC UA server. I also need to implement some logic based on the values to show if the parameters are within safety limits or not. I already used plotly + dash in the past, thus I decided to start using dash to build my dashboard together with a python script responsible to subscribe to the opcua datapoints I need to follow and constantly update a file with them. This file with all the values is then feeding the dash app which is set to update throughIntervals every sec. This gives me a live updating dashboard. Now I was wondering if there is a better way to design this. The dashboard has a general main page where some of the most important parameters are displayed. However there are also different tabs per subsystem/topic where the user can switch to and see all the available parameters of that subsystem at once. Here the problem I encountered is that in dash I can not share information within the Tabs. Thus if a datapoint is … -
I want to see or download the file in django admin uploaded by user from frontend site
I created the form like contact form to upload file and other details. urls.py from django.contrib import admin from django.urls import path from eSangrah import views urlpatterns = [ path("xerox", views.xerox, name='xerox'), views.py from django.shortcuts import render, redirect from .models import Xerox from datetime import datetime def xerox(request): if request.method=='POST': name=request.POST['name'] phone=request.POST['phone'] desc=request.POST.get('desc') file=request.POST['file'] xeroxs = Xerox.objects.create(name=name, phone=phone, desc=desc, file=file, date=datetime.now()) xeroxs.save() return redirect("/xerox") return render(request, 'xerox.html') models.py from django.db import models class Xerox(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=13) desc = models.TextField() file = models.FileField() date = models.DateTimeField() def __str__(self): return self.name admin.py from django.contrib import admin from .models import Xerox admin.site.register(Xerox) enter image description here If I click on the uploaded file . I get below error... enter image description here -
How to create a draggable icon on a web page with JavaScript or a third-party library
I would like to create a website where I can create a round icon by clicking an add button. I can then drag and drop the icon onto an image. When I release the mouse, the icon's position on the image should be saved. Later, on another page, the icon should be displayed on the same position. For the backend I use Django. I have not been able to find a way to implement this and would like to ask for your ideas. -
How to prevent double encryption in Django with Vercel
I am hosting a django website on Vercel and, both, vercel and Django are encrypting the url. So, the " " character in the url gets encrypted to "%20" and then django again encrypts it to "%2520", but when decrypting, it decrypts only once. In my code, I am appending a name which allows " " to be used and that name gets appended to url which later gets used by a function in views.py as pk(not primary key but just a way to get data from the database). The problem is clearly seen in the image, url has replaced " " with %20 but django se getting "%2520". So, the problem was just with the " " character, so I removed space character from the name, which solves the problem, but I don't want that to be the solution. -
Cannot query "zs": Must be "Product" instance
I want the seller to be able to choose one of the offers for sale and then close the sale by clicking on the close button. This code doesn't do anything if I put a separate for loop in the html file, but if it's the way I sent it, it displays the button to close the sale, but after clicking the button, it gives this error. and, I feel that this graphic is not very user-friendly. What is your suggestion for a better design and to reduce the number of buttons to close the auction? Error: Exception Type: ValueError at /seller_page/ Exception Value: Cannot query "zs": Must be "Product" instance. views.py: def seller_page(request): seller_offers = PriceOffer.objects.filter(product=request.user) if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) def close_offer(request): if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return redirect('seller_page') product_detail.html : <ul> {% for offer in offers %} <li><a> {{ offer.author }}:{{ offer.offer_price }}</a></li> <form method="post" action="{% url 'close_offer' %}"> {% csrf_token %} <input type="hidden" name="offer_id" value="{{ offer.id }}"> <button type="submit">Close Offer</button> </form> {% endfor %} </ul> <form method="POST" action="{%url 'product_detail' product.id %}"> … -
django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"
I'm trying to perform migrations on my production server. I installed all packages and dependencies. However, I receive the message: django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"."url_for_interview" FROM "authentic... I tried deleting all files from the migrations folder of the application and project, but it didn't help. I then tried to create a migration only for the authenticator app by 'python manage.py makemigrations authentication' it didn't work properly. What can I do to make the system allow me to create a makemigrations on the server? My modes: from django.db import models from django.contrib.auth.models import AbstractUser from imagekit.models import ProcessedImageField, ImageSpecField from imagekit.processors import ResizeToFill from decimal import Decimal from django.utils.text import slugify from dashboard.choices import PROVINCES_CHOICES class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = [ ('Konto firmowe', 'Konto firmowe'), ('Konto indywidualne', 'Konto indywidualne'), ] name = models.CharField(max_length=200, blank=True, null=True) [..more fields here..] def __str__(self): return self.email class Meta: ordering = ['email', ] class RecommendationsSystem(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='owner', verbose_name='Osoba pierwsza') [..more fields here..] class SocialMediaUrl(models.Model): PERCENT_RANGE = [ (0.05, '5 procent'), # (0.10, '10 procent'), # (0.15, '15 procent'), # (0.20, '20 procent'), # (0.25, '25 procent'), # (0.30, '30 procent'), # (0.35, '35 procent'), # (0.40, '40 procent'), # (0.45, … -
How to update availability set by user?
I have a model with two users Student and Consultant. Consultant is able to set up his availability like this: from django.db import models from userregistration.models import UserProfile class Setup_Availability(models.Model): consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_availability') start_date = models.DateField() # The date when availability starts monday_start_time = models.TimeField(null=True, blank=True) monday_end_time = models.TimeField(null=True, blank=True) tuesday_start_time = models.TimeField(null=True, blank=True) tuesday_end_time = models.TimeField(null=True, blank=True) wednesday_start_time = models.TimeField(null=True, blank=True) wednesday_end_time = models.TimeField(null=True, blank=True) thursday_start_time = models.TimeField(null=True, blank=True) thursday_end_time = models.TimeField(null=True, blank=True) friday_start_time = models.TimeField(null=True, blank=True) friday_end_time = models.TimeField(null=True, blank=True) saturday_start_time = models.TimeField(null=True, blank=True) saturday_end_time = models.TimeField(null=True, blank=True) sunday_start_time = models.TimeField(null=True, blank=True) sunday_end_time = models.TimeField(null=True, blank=True) def __str__(self): return f"Availability for {self.consultant.user.username} starting on {self.start_date}" And Student will be able to book appointment through: class Appointment(models.Model): student = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='student_appointments') consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_appointments') appointment_datetime = models.DateTimeField() appointment_start_time = models.TimeField() appointment_end_time = models.TimeField() is_available = models.BooleanField(default=True) def __str__(self): return f"{self.student.user.username} - {self.consultant.user.username} - {self.appointment_datetime}" def book_appointment(request): day_of_week_name = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] if request.method == 'POST': form = AppointmentBookingForm(request.POST) if form.is_valid(): consultant = form.cleaned_data['consultant'] date = form.cleaned_data['date'] appointment_start_time = form.cleaned_data['appointment_start_time'] appointment_end_time = form.cleaned_data['appointment_end_time'] # Check if the selected time slot is available availability = Setup_Availability.objects.get(consultant=consultant) day_of_week = date.weekday() available_start_time = getattr(availability, … -
How to get last modified date with each image present in different folders in AWS S3 bucket
I have created a bucket on aws s3 storage and saving folders dynamically by the user in that bucket. The code is working perfectly and getting each folder images. But I am not able to get last modified date of each image present in different folders. I want to get last modified date of each image present in different folders. #views.py code: def home(request): data = {} storage = S3Boto3Storage() s3 = boto3.client('s3') image_info_list = {} for obj in s3.list_objects(Bucket=storage.bucket_name)['Contents']: # Getting the folder name from the object key. folder_name = obj['Key'].split('/', 1)[0] if folder_name not in image_info_list: image_info_list[folder_name] = [] # Adding the image url to the folder's image list. image_info_list[folder_name].append(storage.url(obj['Key'])) # Check if a Camera instance with the same name already exists camera, created = Camera.objects.get_or_create(name=folder_name) data = { 'image_info_list': image_info_list, 'cameras': cameras, } return render(request, 'index.html', data) -
How to use Django test without Django models?
I have a Django app for REST api, but not using Django REST Framework. I don't use models for any tables, only using Raw SQL query. Could've used flask since not using any Django features, but higher ups decided to use Django. I want to use Django test but digging in the source code I can see both dumpdata and loaddata which test uses to create Test DB uses app's model. But since I don't have any models how do I test my Django app? It is OK to use the actual development DB for testing. I see django overrides the DEFAULT_DB_ALIAS connection param with the newly created test db params, should I just override the param with the actual default db connection param instead? So can I use django test without models and migrations? can I use default database for testing and prevent django from creating a test db? -
Angular 16 catch errors response from Django
i learning Angular and i have a standard login service in Angular 16.2.0 and backend with Django. I post login details all working fine but when i catch errors i get only get only generic errors, Django is sending personalized messages for errors and i try to catch those to be able to show them in frontend. This is my login service function: login(username: string, password: string): Observable<any> { return this.http.post(apiRoot + 'dj-rest-auth/login/', { username, password, }, ).pipe(catchError((error: HttpErrorResponse) => { let errorMsg = ''; if (error instanceof ErrorEvent) { errorMsg = `Error: ${error}`; } else { errorMsg = `Error Code: ${error}, Message: ${error.message}`; console.log(error.message) } return throwError(() => new Error(errorMsg)); })); } Now in case of an error this is all i got: Http failure response for https://link.stars-nexus.com/dj-rest-auth/login/: 400 OK . In network i have: Network Headers Django is sending personalized error messages in response: Response Image That messages i try to catch them to be able to show them letter in front end. Django is taking care of all validations and provide proper personalized per error feedback. There is any way to catch them? Thank Kind regards. To be able to catch those messages from error response to … -
Registration showing password does not match
I am a beginner that start from python crash course. In the chapter 19, registration, when I tried to register user, it always have this line "Your username and password didn't match. Please try again." Views.register def register(request): if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(data=request.POST) if form.is_valid(): # account created new_user = form.save() # Check the username and password is correct # password is hashed, cannot retrieve normally authenticated_user = authenticate(username=new_user.username, password=request.POST['password1']) # login to the user account login(request,authenticated_user) return HttpResponseRedirect(reverse('learning_logs:index')) context = {'form':form} return render(request,'users/register.html',context) register.html {% extends "learning_logs/base.html" %} {% block content %} <!-- the action is the views url that handle the form ---> <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="register"> Register </button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}"> </form> {% endblock content %} login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% endif %} <!-- the action is the views url that handle the form ---> <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="login"> Login </button> <input type="hidden" name="next" value="{% url 'learning_logs:index' … -
Is it possible to create custom class for the Django default table 'auth_group_permissions'?
Is it possible to create custom class for the Django default table 'auth_group_permissions'? I want to create a simple history table for the 'auth_group_permissions' table. Is it possible to create a custom table by inheriting the base class auth_group_permissions. -
I need an interactive page in Django [closed]
The user uploads a checklist: The user uploads a file with a checklist and a note to the site. Checking for comments: The system analyzes the downloaded file. If there are any comments, go to the next step. If not, it ends. Model for downloading letters and instructions: The site provides the user with a form for downloading a letter and prescription. The user downloads the appropriate files and proceeds to the next step. Processing of letters and instructions: The system processes the downloaded letter and order and proceeds to the next step. Model for loading a repeat checklist: The site provides the user with the opportunity to download a new checklist and note. Checking the repeated checklist: The system analyzes the new file. If there are any comments, go to step 3 (downloading the letter and instructions). If there are no comments, go to step 7. Model for downloading the report: The site provides the user with a form to download the report. The user downloads the report and proceeds to the next step. Completing the process: The system processes the downloaded report. All these steps should be on one page. I tried using fetch js, but something went … -
server django and react [closed]
i have a server problem when I try to valide all data from input I use REACT for the frontend and DJANGO for the backend here is my problem on the console: Erreur lors de l'envoi de la requête: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Guest.js:93 handleSubmit Guest.js:93 here is my code which contains the handleSubmit function: handleSubmit = e => { e.preventDefault(); const { nom, prenom, contact, dateRDV } = this.state; const client = { nom, prenom, contact, dateRDV }; // Créez un objet contenant les données du formulaire // const Data = { // nom: nom, // prenom: prenom, // contact: contact, // rdv: dateRDV // }; this.setState((prevState) => ({ clients: [...prevState.clients, client], nom: '', prenom: '', contact: '', dateRDV : '' })); // Envoyez les données du formulaire au serveur Django fetch('http://127.0.0.1:8000/store/ClientGuest/', { method: 'POST', headers: { 'Content-Type': 'application/json', // Utilisez JSON pour le contenu }, body: JSON.stringify(client), }) .then(response => response.json()) .then(data => { console.log('Réponse du serveur:', data); // Faites quelque chose avec la réponse du serveur si nécessaire this.props.history.push({ pathname: '/ListeClients', state: { data: client } }); }) .catch(error => { console.error('Erreur lors de l\'envoi de la requête:', … -
Django: How to do something in init state of ModelAdmin
Currently I have something like this: from django.db import models from django.contrib import admin import requests API_SERVER= 'https://someapiserver.com' class Member(models.Model): nodeid = models.CharField(max_length=20, blank=True, null=True, editable=False) authorized = models.BooleanField(default=False) name = models.CharField(max_length=15, blank=False, null=False) assigned_ip = models.CharField(max_length=15, blank=True, null=True, verbose_name='USE IP') def __str__(self) -> str: return self.name class MemberAdmin(admin.ModelAdmin): list_display = ('nodeid', 'name','authorized', 'assigned_ip', 'from_ip') def from_ip(self, obj): try : r = requests.get(f'{API_SERVER}/peer/{obj.nodeid}') srcData = r.json() srcIP = srcData['from_ip'] return srcIP except Exception as e : return 'Unknown' I realize that with above methode, I need to make a http call for each custom field ('from_ip'). Acttualy, the API_SERVER can give me list of all peer in single call by just use r = requests.get(f'{API_SERVER}/peer') My question is : How to define a 'custom variable' inside this modelAdmin in init state, so that I can change my custom field definition like def from_ip(self, obj): try : srcData = [p for p in self.peers if p['id'] == obj.nodeid][0] srcIP = srcData['from_ip'] return srcIP except Exception as e : return 'Unknown' Sincerely -bino- -
I am getting Exception: 'QuerySet' object has no attribute 'client' where client is defined as a foreign key on a one to many relation
Here are the log entries around the prolem. 2023-09-25 10:29:25,768 - facebookapi.fetchMetadata - CRITICAL - about to save to master 2023-09-25 10:29:25,771 - facebookapi.fetchMetadata - CRITICAL - Master exists now update... 2023-09-25 10:29:25,773 - facebookapi.fetchMetadata - CRITICAL - _master.save() Exception: 'QuerySet' object has no attribute 'client' Here are the two models Client and Master class Client(models.Model): id = models.BigAutoField(primary_key=True), name = models.CharField(max_length=200, blank=False, null=True) #more fields abbreviated class Master(models.Model): id = models.BigAutoField(primary_key = True) client = models.ForeignKey(Client, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user_metadata = models.JSONField(max_length=5000, null=True, blank=True) user_id = models.CharField(max_length=500, blank=False, null = True) user_name = models.CharField(max_length=500, blank=False, null = True) #more fields abbreviated and the code that is generating the error. logger.critical("about to save to master+++++++++++++++++++++OOOOOOOOOOOO+++++++++++++") try: _master = Master.objects.filter(client=client_fk) if _master is None: logger.critical("Master does not exist now create...") new_master = Master.objects.create() new_master.client = client_fk new_master.user_id = user_id new_master.user_name = result["name"] new_master.user_apprequests = _connections1["apprequests"] new_master.user_business_users = _connections1["business_users"] new_master.user_businesses = _connections1["businesses"] new_master.user_accounts = _connections1["accounts"] new_master.user_adaccounts = _connections1["adaccounts"] new_master.user_assigned_ad_accounts = _connections1["assigned_ad_accounts"] new_master.user_assigned_pages = _connections1["assigned_pages"] new_master.user_permissions = _connections1["permissions"] new_master.user_personal_ad_accounts = _connections1["personal_ad_accounts"] new_master.user_metadata = result["metadata"] new_master.account_status = "created" new_master.save() else: logger.critical("Master exists now update...") logger.critical("Master.client: %s", _master.client) #_master.client = client_fk _master.user_id = user_id _master.user_name = result["name"] _master.user_apprequests = _connections1["apprequests"] _master.user_business_users … -
How to Update a django model wihtout using Django forms
I have a model called Record which i am trying to Update it by validating the html form without using Django Forms. I dont know what is wrong with my views.py Views.py def update_record(request, pk): current_record = Record.objects.get(id=pk) if request.user.is_authenticated: if request.method =='POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] phone_number = request.POST['phone_number'] state = request.POST['state'] current_record = Record.objects.update(first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, state=state) current_record.save() print('Record updated sucessfully') messages.info(request,'Record updated sucessfully') return redirect('home') return render (request, 'update_record.html', {current_record:current_record}) else: messages.info(request, 'you dont have access to this, you must login') return redirect ('home') -
How to optimize nested serializer custom update method
I'm writing a serializer that points to a nested serializer and as the documentation explains it is necesary to write custom create and update methods so that nested serializers could be writable. The way I'm doing this is next: def update(self, instance, validated_data): instance.attr1 = validated_data.get('attr1', instance) instance.attr2 = validated_data.get('attr2', instance) instance.attr3 = validated_data.get('attr3', instance) instance.save() return instance but the instance has 26 attributes. The question is. Is there a way of improving this code? -
Why is paddle.com overlay checkout not working from localhost?
I am trying to get a simple paddle.com overlay checkout working from a local hosted Django site - I'm using the sandbox for now. Currently I am just getting a "something went wrong" dialog when I try and open the checkout. I think I am following all the steps: I am including the following js in the webpage that is trying to show the checkout: <script src="https://cdn.paddle.com/paddle/paddle.js"></script> <script type="text/javascript"> Paddle.Environment.set('sandbox'); Paddle.Setup({ vendor: xxxx, }); </script> And then in the html later on in this page I have a button that I am pressing: <a href="#!" class="paddle_button" data-product="pri_xxxxxxxxxxxxx">Buy Now!</a> I have also set up the address in the sandbox checkout settings to be the url of the same page: https://localhost:8000/account/subscription When I press the Buy Now button I get the “something went wrong” dialog box coming up. I notice in Firefox developer console that it is trying to do an http get on: https://sandbox-create-checkout.paddle.com/v2/checkout/product/pri_xxxxxxxx/?product=pri_xxxxxxxxx&parentURL=https://localhost:8000/account/subscription&parent_url=https://localhost:8000/account/subscription&referring_domain=localhost:8000 / localhost:8000&display_mode=overlay&apple_pay_enabled=false&paddlejs-version=2.0.72&vendor=xxxxx&checkout_initiated=1695581565275&popup=true&paddle_js=true&is_popup=true And when I try and do a get on this link manually I get the following JSON back: {"errors":[{"status":404,"code":"error-creating-checkout","details":"Error creating the checkout"}]} I can also see a Cross-Origin Request Blocked error code in the console too – so I don’t know if that has something … -
How can I translate a Django website entirely?
I have a Django project. How can I translate the entire website? It's worth noting that additional data can be added to the database later, so I want to translate all the existing data in the database, including information added later. -
Django project - quiz Error 405 while clicking on + on the website
I am writing an newbie application - newbie quiz for learning programming languages. I am getting this message: #views.py from django.shortcuts import render from django.views import View from .models import Question # Create your views here. class QuestionView(View): def get(self, request): if request.method == "POST": print('Received data:', request.POST['itemName']) Question.objects.create(name = request.POST['itemName']) all_items = Question.objects.all() #Access to items from database Nur 1 .get(id=1); .filter(name='Hello') return render(request, "questionmanager.html", {'all_items': all_items}) #models.py from django.db import models from datetime import date # Create your models here. class Question(models.Model): created_at=models.DateField(default=date.today) name=models.CharField(max_length=200) done=models.BooleanField(default=False) #HTML - here questions/ items can be added <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet" /> <style> body { font-family: "Lato", sans-serif; background-color: rgba(179, 241, 245, 0.1); margin: 0; } header { background-color: rgba(142, 250, 184, 0.05); display: flex; padding-left: 20px; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1); } button { height: 60px; width: 60px; border-radius: 50%; background-color: rgba(163, 122, 11); border: unset; font-size: 35px; color: rgba(31, 28, 20); position: absolute; right: 16px; bottom: 16px; } .list-item { background-color: #9effff; height: 60px; box-shadow: 2px 2px 2px rgba(0, 0, 0, … -
Django Rest Framework Default Settings Not Working
I'm facing an issue with Django Rest Framework (DRF) where the default settings I've configured in my settings.py file are not working as expected. Specifically, I've set up default pagination and authentication classes, but they don't seem to be applied to my views. I am using : python3.11 Django==4.2.5 djangorestframework==3.14.0 django_filter==23.3 Here are the relevant parts of my project configuration: settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ] } project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] myapp/urls.py urlpatterns = [ path('myview/', views.MyListView.as_view()), # MyListView is a DRF view ] -
I can't populate the datatable in postgresql from Django
I'm struggling to populate the a table in a postgresql Database, it worked fine when for Users Database. My PropertyListing Model is not populating as a table in postgresql when i run Python manage.py migrate PropertyListings --database=PropertyListing Operations to perform: Apply all migrations: PropertyListings Applying PropertyListings.0001_initial... OK it populates a tabled called django_migrations as attached in the screenshotenter image description here here is my model.py file from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.validators import FileExtensionValidator PROPERTY_CHOICES = [ ("DVILLA", _("Detached Villa")), ("SDVILLA", _("Semi-Detached Villa")), ("Apartment", _("Apartment")), ("House", _("House")), ("Land", _("Land")), ("Commercial", _("Commercial")), ("Agriculture", _("Agriculture")), ] LISTING_CHOICES = [ ("RENT", _("Rental")), ("SELL", _("Sell")), ("VACRENTAL", _("Vacation Rental")), ] class ImageFieldWithExtension(models.ImageField): def __init__(self, *args, **kwargs): kwargs.setdefault('upload_to', 'MarocHomes/') kwargs.setdefault('validators', [FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])]) super().__init__(*args, **kwargs) class PropertyListing(models.Model): listing_type = models.CharField(max_length=200,blank=False, null=True, choices=LISTING_CHOICES, verbose_name=_("Listing Type")) realtor = models.EmailField(max_length=255, blank=False, null=True) propertytype = models.CharField(max_length=200, blank=False, null=True, choices=PROPERTY_CHOICES, verbose_name=_("Property Type")) slug = models.SlugField(unique=True, default="") title = models.CharField(max_length=50, verbose_name=_("Title")) building_name = models.CharField(max_length=100, blank=True, null=False, verbose_name=_("Building Name/Building No.")) street_name = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("Street Name")) city = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("City")) postal_code = models.CharField(max_length=50, blank=False, null=False, verbose_name=_("Postal Code")) description = models.TextField(blank=True, verbose_name=_("Description")) price = models.DecimalField(max_digits=30, decimal_places=2, verbose_name=_("Price")) ceiling_height = models.FloatField(blank=True, null=True, verbose_name=_("Ceiling height")) bedrooms = …