Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST API refusing connection to browsers?
I tried accessing my Django project fro another device, and it always returns either ERR_CONNECTION_REFUSED on Chromium based browsers, or CORS on Firefox. I can access the API using Postman without issues. It also works if it is using localhost. Django serves HTML files no problem, just not the API calls. I've installed django-cors-headers and added it to installed applications, middleware, and allowed all. Requests don't show on console either (using manage.py runserver). Is there anything I'm missing? -
I'm creating a cost calculating site using django. How do I make the backend work?
class CalcView(TemplateView): template_name = 'calculator.html' onestoried = 600000 twostoried = 800000 highq= 240000 mediumq= 120000 select_story = input('How tall ?' '\n 1. One Storied' '\n 2. Two Storied : ') if select_story == '1': select_quality = input('What quality?' '\n 1. High' '\n 2. Medium : ') if select_quality == '1': print('The price will be:', onestoried + highq) elif select_quality == '2': print('The price will be:', onestoried + mediumq) else: print('Select a valid quality') elif select_story == '2': select_quality = input('What quality?' '\n 1. High' '\n 2. Medium : ') if select_quality == '1': print('The price will be:', twostoried + highq) elif select_quality == '2': print( 'The price will be:',twostoried + mediumq) else: print('Select a valid quality') else: print('Select a valid story') ** This is the code I wrote for the calculations. Very simple and works just fine in the terminal. But the question is how can I make this backend work in the webpage.?? What I'm trying is to create 4 buttons, dropdowns, checkboxes, anything suitable on the webpage named 'onestoried','twostoried','highq' and 'mediumq' and I want the calculations to be performed when the buttons are clicked i.e. if user clicks/selects high quality and one storied, I want the answer in … -
how do i get rid of attribute error as u can see in last line
PS C:\Users\Admin\Desktop\django path\mysite\portfolio> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions Running migrations: Traceback (most recent call last): File "C:\Users\Admin\Desktop\django path\mysite\portfolio\manage.py", line 22, in main() File "C:\Users\Admin\Desktop\django path\mysite\portfolio\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python39\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\python39\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\python39\lib\site-packages\django\db\migrations\executor.py", line 91, in migrate self.recorder.ensure_schema() File "C:\python39\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema with self.connection.schema_editor() as editor: File "C:\python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 24, in enter if not self.connection.disable_constraint_checking(): File "C:\python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 311, in disable_constraint_checking enabled = cursor.execute('PRAGMA foreign_keys').fetchone()[0] AttributeError: 'NoneType' object has no attribute 'fetchone' PS C:\Users\Admin\Desktop\django path\mysite\portfolio> -
modifay fileField to TextField by selected value
select video resource select URK resource (text) url resource i replace input[image] to input[text] with js but how does it manage while saving -
How to retrieve related instances without FK using one query in django
Imagine there are three models named Movie, Actor, and Participation. class Movie(models.Model): identifier = models.CharField() class Actor(models.Model): name = models.CharField() class Participation(models.Model): movie_identifier = models.CharField() actor = models.ForgeinKey(Actor, on_delete=models.CASCADE) Let's assume that I can't use ForgeinKey for the movie in the Participation model. how can I retrieve all the participation records of a movie with only one query? Here is the solution if I had a foreign key for the movie in the participation table: qs = Movie.objects.filter(identifier="an_identiier").prefetch_related("participations_set") How can I do this without having a Movie foreign key in the Participation model? Thanks! -
Django: Order_by combined two columns
I have following query; There are two columns (dateEmploymentRD and dateTerminationRD). qsPersonnel = qsPersonnel.filter(Q(dateEmploymentRD__isnull=False), Q(dateEmploymentRD__lte=personnelDateMax), Q(dateTerminationRD__gte=personnelDateMin) | Q(dateTerminationRD__isnull=True), Q(dateTerminationRD__lte=personnelDateMax) | Q(dateTerminationRD__isnull=True)).order_by('dateEmploymentRD','dateTerminationRD') I would like to sort that queryset with combined two coulmns (dateEmploymentRD and dateTerminationRD). But my query is ordering firstly 'dateEmployementRD' and than ordering by 'dateTerminationRD' as below. How can I order my query by combined two columns? -
How to order data in a specific/customised manner in django-models?
Here are my files models.py from django.db import models from django.urls import reverse class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Sterilisation', 'Sterilisation'), ('Cleaning Chemistry', 'Cleaning Chemistry'), ('Bacterial Barrier', 'Bacterial Barrier'), ('Waste Management', 'Waste Management'), ('Instrument Tracking', 'Instrument Tracking'), ('Validation', 'Validation') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name views.py def product(request): allProds = [] ster_prods = [] catprods = Product.objects.values('prod_category', 'id') cats = {item['prod_category'] for item in catprods} for cat in cats: prod = Product.objects.filter(prod_category=cat) prod = prod.order_by('-prod_name') # print('prod is', prod[0]) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds': allProds, 'ster_prods': ster_prods} return render(request, 'website/products.html', params) This code displays the following view: Category 1 Product 1 Product 2 Product 3 Category 2 Product 1 Product 2 Product 3 Category 3 Product 1 Product 2 Product 3 Where the categories are in random order .i.e. the order changes every-time the page is refreshed/product is added. Can you all help me to get the categories listed in a particular order that I want instead of a random … -
AttributeError at /profile/
'User' object has no attribute 'profile' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) The problem comes when i click on profile button to see the profile of the user -
Django: How to dump model defination to json?
Does Django has CLI to handle this? for example, convert: class Log(models.Model): ctime = models.DateTimeField(blank=True, null=True) message = models.CharField(max_length=1024) class Meta: managed = True db_table = 'log' to its json form, something like: { "db_table": "log", "managed": true, "fields": [ {"name": "ctime", "type": "datetime","null":true}, {"name": "message", "type": "char", "maxlength":1024}, ], } -
Djano - Google Maps API Uncaught in promise error when deployed
Im using the Google maps Javascript Api to display a map on my site. The lat and long are received from two HTML tags which gets the info from a model. The code works and displays a map for every instance of a model. However, it only works 100% of the time when it's on localhost, when I deploy the site to Heroku it only works sometimes. Sometimes the map will show and sometimes it won't. When it doesn't show it gives me an Uncaught (in promise) error. HTML <!-- The two tags I'm getting the lat and long from --> <input type="hidden" id="hidden_lat" name="lat" value="{{object.author.profile.detail_lat}}"> <input type="hidden" id="hidden_lng" name="lng" value="{{object.author.profile.detail_lng}}"> <!--Displays map --> <div id="main_top"> <div id="main"> <div id="right"> <div id="map"></div> </div> </div> </div> <script async src="https://maps.googleapis.com/maps/api/js?key=NICE_TRY=initMap"> </script> CSS <style> #main_top { margin-left: 100px; } #right { height: 70%; } #main { height: 400px; } #map { height: 100%; width: 900px; } </style> Javascript function initMap() { var lat = +document.getElementById('hidden_lat').value var lng = +document.getElementById('hidden_lng').value const map = new google.maps.Map(document.getElementById("map"), { zoom: 12, disableDefaultUI: true, gestureHandling: "none", zoomControl: false, center: { lat: lat, lng: lng }, }); const image = "https://upload.wikimedia.org/wikipedia/commons/8/8e/Pan_Blue_Circle.png"; const beachMarker = new google.maps.Marker({ position: { lat: … -
I want to build a nested serializer to display order with product and each product showing its individual value. I have my code below
models.py class Order(models.Model): user = models.ForeignKey(Account, related_name='orders', on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.first_name def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, null=True, blank=True) glasses = models.ForeignKey(Glasses, related_name='glass', on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def get_cost(self): return self.price * self.quantity class Power(models.Model): frame = models.ForeignKey(OrderItem, related_name='power', on_delete=models.CASCADE) type = models.CharField(max_length=20, choices=[('Powered', 'Powered'), ('bifocal', 'bifocal'), ('Frame_only', 'Frame_only')]) left_eye_power = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_cylinder = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_bifocal = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) left_eye_axis = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_power = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_cylinder = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_bifocal = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) right_eye_axis = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) serializer.py class PowerSerializer(serializers.ModelSerializer): class Meta: model = Power fields = '__all__' class OrderItemSerializer(serializers.ModelSerializer): #power = serializers.RelatedField(read_only=True) power = PowerSerializer(many=True) class Meta: model = OrderItem fields = ( "price", "glasses", "power", "quantity", ) class OrderSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = ( "id", "first_name", "last_name", "email", "address", … -
Django URLs: Getting Internal Server Error When render/httpresponse in live server but Working in local
I'm new in Django . I have worked Django web site, and it's working successfully in the local host . But got Internal Server Error after moving into live when I put training.example.com/about but working training.example.com . And page templates using common header and footer html codes, static files are working correctly. So please help review and advice on my bellow the file path and codes. File path : --- Meluxdj |-- MainApp | -- migrations | -- static | --MainAPP | --css | --js | --fonts | --images | -- templates | -- index.html | -- about.html | -- base.html | --admin.py | -- apps.py | -- urls.py | --views.py | --models.py |-- Mainproject | -- asgi.py | -- urls.py | -- settings.py | -- wsgi.py | -- manage.py | -- passenger_wsgi.py | -- db.sqlite3 MainApp/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def Index(request): mydata = {'val':'hai data from function'} return render(request,'MainAPP/index.html',mydata) def about(request): return render(request,'MainAPP/about.html',mydata) MainApp/urls.py from django.urls import path from . import views urlpatterns = [ path('',views.Index , name='index'), path('about/', views.about, name='about'), ] Mainproject/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('MainApp.urls')), … -
Django filter comparing DateTimeField with today's date does not work
Quite strangely, cannot figure this out after trying for sometime: Trying to fetch a model instance from the Model InputsApproval todays_input = InputsApproval.objects.filter(user=request.user, input_time__date=datetime.date.today()).first() but todays_input is returned as None when I know there is one record for the logged in user that has today's date (also visible from django admin) In fact, to debug this, I created a for loop to loop through all the records and it does return True for that one record but somehow the filter query returns None: all_records_for_current_user = InputsApproval.objects.filter(user=request.user) for record in all_records_for_current_user: print('today() returns', datetime.date.today()) print('date for this record is', record.input_time.date()) print ('Does it match?', datetime.date.today() == record.input_time.date()) -
Can someone explain to my why my django admin theme is dark?
I host my small project on pythonanywhere and after i host it i check if it is working and when i click the django admin, the theme of my django admin is dark and when i tried to run on my local host the theme is white so i tried to double check my static url and i think it is fine and btw this is my static url for my admin Static Url: /static/admin, Static Directory: /home/k3v1nSocialProject/.virtualenvs/myprojenv/lib/python3.8/site-packages/django/contrib/admin/static/admin. Can someone explain to me what is happening and why is my django admin theme is dark? -
Django admin read only fields with list_display and list_editable
I'm trying to make only blank fields editable with list_display and list_editable options, I guess there are no way to do it from the "box"... but there must be methods like get_list_editable_field or way to create it and override builtin... does anyone know a way to do it? https://i.stack.imgur.com/IspWG.jpg Now I have just standard options, so I want only 'energy_quantity' be editable when is blank/None class UserDataPeriodicAdmin(admin.ModelAdmin): list_display = ( 'prim_address', 'sec_address', 'energy_quantity', 'heat_power', 'time_date', 'apartment', ) list_editable = ('energy_quantity',) readonly_fields = ( 'prim_address', 'sec_address', 'energy_quantity', 'heat_power', 'flow_rate', 'flow_t', 'return_t', 'time_date', 'ver', 'status_code', 'apartment', 'weather', ) list_display_links = None list_filter = ( ('time_date', DateRangeFilter), ) -
What is the best way to validate fields when multiple fields follow same validation?
I have 5 fields which follow same validation in serializer. Suppose those fields are a, b, c, d, and e. Writing same validation in all 5 fields results in duplication of code. I want to avoid that. Now I have created a simple function validateFields that is called from validate_a, validate_b, validate_c, validate_d and validate_e. But django is showing this error : name 'validateFields' is not defined. How can I avoid this error? Also is there any better way than this to avoid duplication of data? -
How to bulid django login authorization to access the api endpint
i have a api end point for invoke a lambda function but i want to build django simple login authorization so that the person who is authorized can access my endpoint -
Why GET-request in react-native doesn't work?
Here is my request code backend() { GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; let xhr = new XMLHttpRequest(); xhr.open("GET", `https://randomday.ru/newValue/?value=${this.state.text}`, true); xhr.send(); xhr.onload = function() { if (xhr.status !== 200) { console.log(`${xhr.status}: ${xhr.statusText}`); } else { let json = JSON.parse(xhr.response); this.setState({ text: json.msg }); } }.bind(this); xhr.onerror = function(e) { console.log(e.target.status); }; } It starts on push the button <Pressable onPress={() => { this.backend() }} This works fine when i run the project with debugger in chrome, but normally the request returns "0 error". If anyrhing, i am accessing my server in django. My AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myreact"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Whats wrong? -
Django: load JavaScript function to HTML Template
I have tried my JavaScript function in the Console and it seems to be working, but whenever I try to write it in my js file and load it on the index page it doesn't work. index.js document.querySelector('#post-form').onsubmit = function() { const post = document.querySelector('#post-body').value; alert(`Hello, ${post}`); console.log(post); }; index.HTML {% extends "network/layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <div id="post-view"> <h3>New Post</h3> <form id="post-form"> {% csrf_token %} <textarea class="form-control" id="post-body" placeholder="Post"></textarea> <input class="btn btn-primary" type="submit" value="Post"> </form> </div> {% endif %} {% endblock %} {% block script %} <script src="{% static 'network/index.js' %}"></script> {% endblock %} -
Showing time according to User's Country
I am building a BlogApp and I am stuck on a Problem. What i am trying to asking :- As everybody know that Django provides Time Zone select feature in settings.py like TIME_ZONE = 'Asia/Sanghai' AND i have made a instance date = models.DateTimeField(auto_now_add=True) AND date_added = models.DateTimeField(null=True,default=timezone.now) in models.py So my time is of Asia AND whenever i deploy my webapp and A user from Europe try to access the webapp and try make a BlogPost, So what will be the time for Europe's User ? My selected time ( Asia/Sanghai ) ? OR `Europe's User Time ? If his/her time will be My selected time then how can i make it like : When someone visit the site then show time according to User's timezone ? I have no idea, What will be the timezone when someone try to access the site from different Country. Any help would be Appreciated. Thank You in Advance. -
Social media algorithms
I'm learning django my first project is social media app, how social media algorithms work (the suggestion algorithms to be specific)? Is it written by the backend (django) or there's something else? -
How do I select more than one of the same item in the serializer?
I'm trying to make this app where I can select the items I want to buy. I want to select two cakes, for example, but so far I can't select more than one. How do I do that? The field I need to change is 'food' since this one has options like 'cake', 'pastries', etc. I want the user to be able to select as many of each item as they want. I tried with many=True but something is not working out. This is the serializer so far: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Order(models.Model): food = models.ManyToManyField('Food', related_name='order', blank=True) def __str__(self): return self.food -
Images In CSS Integrity Issue
How do I link a local image in CSS as background-image? When I go to my localhost and console there is an error which says: " Failed to find a valid digest in the 'integrity' attribute for resource 'http://127.0.0.1:8000/static/css/base.css' with computed SHA-256 integrity 'VamhLHC0Rd5RsK5ayIQbhNx167AvkjG9xrdEDZaSFoc='. The resource has been blocked. ". I am using Django Framework. How do I fix this? This is my first question, so sorry if it is hard to understand. -
I trial make Notification for Comment
I trial make Notification for Comment by Many-to-many relationships how fix it raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use NotfFaId.set() instead. [17/Apr/2021 03:37:31] "POST /forum/addcomment/ HTTP/1.1" 500 73061 class CommentT(MPTTModel): Topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') NotfFaId = models.ManyToManyField( User, related_name='NotfFaVId', default=None, blank=True) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class MPTTMeta: order_insertion_by = ['publish'] def addcomment(request): if request.method == 'POST': if request.POST.get('action') == 'delete': id = request.POST.get('nodeid') c = CommentT.objects.get(id=id) c.delete() return JsonResponse({'remove': id}) else: comment_form = NewCommentTForm(request.POST) # print(comment_form) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('content') user = request.user.username user_comment.author = request.user user_comment.NotfFaId = request.user user_comment.save() Topic.objects.get(id = request.POST.get('Topic') ).NotfFaV.add(request.user) # CommentT.objects.get(id=user_comment.id).NotfFaId.add(request.user) return JsonResponse({'result': result, 'user': user,'id': user_comment.id }) -
Django GET request not reading parameters
I am using Django and the Django REST Framework to code a web API, I created a view for user authentication. It has a corresponding model called "Users" which takes fields "email", "password", etc. The view also has a corresponding serializer called UserSerializer. Here is the code for the view, which is supposed to check if the provided email and password exists in my Users table. class UsersView(APIView): def get(self, request, _email=None, _password=None): if _email and _password: try: queryset = Users.objects.get(email=_email , password=_password) except Users.DoesNotExist: return Response({'error': 'No user with the given credentials.'}, status=400) read_serializer = UsersSerializer(queryset) return Response(read_serializer.data) return Response({'error': 'Outside.'}, status=400) The issue I am having is when I send a get request with a body that contains fields for _email and _password, their values are not interpreted, they just stay null. For example, if I add the line return Response({_email}, status=400) (which simply prints the value of email) directly under the function definition (before the if statement), I get a response "null", even when I have passed in a valid value. Another way I tested this is by removing the function parameters altogether and instead defining variables _email and _password locally within my function and giving them …