Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Subscription Form using Django Allauth
I recently created a Django template using allauth for an Abstract User. I followed William Vincent’s best practices in his book and the settings according to the documentation but I’m currently stuck. I’d like to support multiple signup forms to create a user. The 2 signup forms I’d like to support are: Account creation, which uses the typical convention of: #my_project/setings.py AUTH_USER_MODEL = ‘users.CustomUser’ LOGIN_REDIRECT_URL = ‘home’ LOGOUT_REDIRECT_URL = ‘home’ ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_AUTHENTICATION_METHOD = ‘email’ ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = ‘username’ ACCOUNT_USER_MODEL_EMAIL_FIELD = “email” A User Subscription Form (with simply email and no password), which uses what I came up with: #users/forms.py class CustomUserSubscribeForm(forms.ModelForm): class Meta: model = CustomUser fields = (‘email’, ) email = forms.EmailField( label=_(''), widget=forms.TextInput( attrs={ 'placeholder': _('john@email.com') } ) ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_method = 'POST' self.helper.form_class = 'form-inline justify-content-center' self.helper.layout = Layout( Div( FieldWithButtons('email', Submit('Submit', 'submit', css_class='btn btn-outline primary')), Submit('submit', u'Submit', css_class='btn btn-success'), css_class='form-inline' ) ) #users/views.py class SubscribePageView(CreateView): form_class = CustomUserSubscribeForm success_url = reverse_lazy(‘subscribe’) template_name = ‘subscribe.html’ #users/urls.py from .views import SubscribePageView urlpatterns = [ path(‘subscribe’, SubscribePageView.as_view(), name=‘subscribe’), ] These views/html pages render and the … -
In Django, how can I get a count of records based on a subquery of a subquery?
A baseball player plays in a game if he makes one or more appearances in that game. So, to get a count of the number of games a player played in, you need to count the games that have an inning that have an appearance by that player. Here are my models: class Player(models.Model): ... class Game(models.Model): ... class Inning(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) class Appearance(models.Model): inning = models.ForeignKey(Inning, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) The SQL query to achieve what I want is: SELECT COUNT(*) FROM games_game WHERE id IN (SELECT game_id FROM innings_inning WHERE id IN (SELECT inning_id FROM appearances_appearance WHERE player_id = 1)) How could I do this in Django without using Raw SQL? Note that this is for a PlayerDetailView, so I just need it for a single Player object. -
Second app static files not being served in Django
I have two apps in my Django projecto: frontend and backend. The static files from the backend app are being served correctly. The folder hierarchy is backend - static - backend. I am now starting with the frontend app. The hierarchy is frontend - static - frontend. Yet, for this app, files are not being served. When trying to go to the file url I get a 'frontend\assets\vendor\nucleo\css\nucleo.css' could not be found. In my urls.py I have: urlpatterns = [ path('', views.index, name="frontend") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And in my settings.py I have: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' -
KeyError at /product/create/ django rest framework
I am trying to create a product but one related field does not accept null value it causes error Traceback (most recent call last): File "/home/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 213, in save self.instance = self.create(validated_data) File "/home/apps/product/serializers.py", line 194, in create videos = validated_data.pop('product_videos') KeyError: 'videos' class ProductCreateSerializer(serializers.ModelSerializer): product_videos = ProductVideoSerializer(many=True, required=False) class Meta: model = models.Product fields = '__all__' def create(self, validated_data): product_videos = validated_data.pop('videos') phone = self.context.get('view').kwargs.get('phone') user = models.User.objects.get(phone=phone, is_superuser__exact=True) instance = models.Product.objects.create(user=user, **validated_data) for video_uri in product_videos.values(): models.ProductVideoOverview.objects.create(product=instance, **video_uri) return instance It is not accepting the null value I do … -
Possible causes for error: Field cannot be both deferred and traversed using select_related at the same time?
I am trying to use graphene-django-optimizer to remove some of the unnecessary queries. It worked quite well until one certain field where I get this error message Field User.company cannot be both deferred and traversed using select_related at the same time. The only difference with this field is that it is models.OneToOne instead of models.ForeignKey. Why Django make this field deferred? Is it possible to disable field being deferred? -
S3 bucket configuration for open edx (Hawthorn)
I am trying to set s3 for scorm for this I have set: “AWS_ACCESS_KEY_ID” : “access-key”, “AWS_S3_CUSTOM_DOMAIN” : “bucket-name.s3.amazonaws.com 3”, “AWS_SECRET_ACCESS_KEY” : “secret-key”, “AWS_STORAGE_BUCKET_NAME” : “bucket-name”, }, Is there anything. which I have forgot? -
Django doesn't return ajax response with dataType : "JSON"
I have Ajax like this var data = {"data":1} $.ajax({ type: "POST", url: "api/export_csv", data:JSON.stringify(data), // dataType: "JSON", // if I comment out here it works. success: function(response) { console.log("success"); } Then in django view.py @api_view(['POST', 'GET']) def export_csv_view(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=somefilename.csv' writer = csv.writer(response) writer.writerow(['First row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response Very strangely If I comment out the dataType: "JSON" it works, but if I put this line it doesn't work with no error(javascript console). -
Django Template search
In one of my project the template is being searched at <project_root>/<app>/templates/ while in another it is being searched in <project_root>/<app>/templates/<app>/ What exactly does this depend on Both project's settings.py have the following exact same configuration in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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', ], }, }, ] -
How do I ensure that certain model instances are always present in django database?
My django-application requires a few model instances to always be present in the database to function properly. I currently create the model instances that I require in the Appconfig.ready(self) method for the corresponding app. This way the instances are always present on boot of the django-application. This works but not as well as I'd like, I have to be careful when deleting objects so that I do not delete the required objects. I would like the required model instances to be undeletable or preferably, be created whenever they are not present in the database. -
Send individual emails to multiple recipients without using BCC with the SparkPost API
Our Django app uses SparkPost as an email provider. A new feature we are implementing should allow users to create their own organizational emails and send them to whoever they wish. Now, these emails should be received as individual ones, not with multiple recipients ("to") so that users can't see each other's address. I have run a few tests with the SparkPost transmissions API. This is how you send an email: sp = SparkPost(API_KEY) response = sp.transmissions.send(recipients=emails, html=body, from_email=sender, subject=self.subject) Where emails is a list of string literals. In all test cases except one I did get individual emails with a single recipient just as I was after. But in one case the email had multiple "to" emails, and you could see each other's email address. I changed absolutely nothing in the code, this just happened. Is there any way I could do that other than sending an individual transmission for each recipient? I'm worried about performance if it comes to that: sp = SparkPost(API_KEY) for email in emails: sp.transmissions.send(recipients=email, html=body, from_email=sender, subject=self.subject) -
Keyerror 'job.cost.sheet' in odoo 12
i try to devellop a custom module in odoo . when i upgrade it i have this error in the log ''' Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 12.0\server\odoo\api.py", line 1049, in get value = self._data[key][field][record._ids[0]] KeyError: 434 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 12.0\server\odoo\fields.py", line 989, in get value = record.env.cache.get(record, self) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\api.py", line 1051, in get raise CacheMiss(record, field) odoo.exceptions.CacheMiss: ('ir.actions.act_window(434,).search_view', None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 656, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 314, in _handle_exception raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\tools\pycompat.py", line 87, in reraise raise value File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 698, in dispatch result = self._call_function(**self.params) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 346, in _call_function return checked_call(self.db, *args, **kwargs) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\service\model.py", line 97, in wrapper return f(dbname, *args, **kwargs) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 339, in checked_call result = self.endpoint(*a, **kw) File "C:\Program Files (x86)\Odoo 12.0\server\odoo\http.py", line 941, in call return self.method(*args, **kw) File "C:\Program Files (x86)\Odoo … -
How to declare abstract class and methods for model implementation?
I wonder if there is a way in Django to create an abstract class where I can declare a method that should be implemented in a model. Normally, in Python, we declare abstract class like this: import abc class MyABC(metaclass=abc.ABCMeta): @abc.abstractmethod def do_something(self, value): raise NotImplementedError And then implement it like this: class MyClass(MyABC): def do_something(self, value): pass What I did with django is: import abc from django.db import models class MyClass(metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self): raise NotImplementedError class MyClass2(models.Model, MyClass): def __str__(self): pass But this gives me error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I don't understand what I did wrong here. MyClass2 should inherit from MyClass and from models.Model. What I did wrong? Why this is wrong? What is the better way of declaring methods that should be implemented in models? -
Clear the variable x after use in sklearn.linear_model
I developed the django application which use a sklearn.linear_model model to predict the output based on input using form when i submit i get the expected output and then when i revisit the page i get this error how i can clear the x. ValueError at /output/ X has 18 features per sample; expecting 6 Request Method: POST Request URL: http://127.0.0.1:8000/output/ Django Version: 3.0.4 Exception Type: ValueError Exception Value: X has 18 features per sample; expecting 6 Exception Location: C:\Users\Saicharan Pogul\Desktop\Sihva\Project\final\lib\site-packages\sklearn\linear_model\_base.py in decision_function, line 273 Python Executable: C:\Users\Saicharan Pogul\Desktop\Sihva\Project\final\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Saicharan Pogul\\Desktop\\Sihva\\Project\\final\\avasyu', 'C:\\Users\\Saicharan ' 'Pogul\\Desktop\\Sihva\\Project\\final\\Scripts\\python37.zip', 'c:\\users\\saicharan pogul\\anaconda3\\DLLs', 'c:\\users\\saicharan pogul\\anaconda3\\lib', 'c:\\users\\saicharan pogul\\anaconda3', 'C:\\Users\\Saicharan Pogul\\Desktop\\Sihva\\Project\\final', 'C:\\Users\\Saicharan ' 'Pogul\\Desktop\\Sihva\\Project\\final\\lib\\site-packages'] Server time: Fri, 13 Mar 2020 08:38:03 +0000 I tried this to clear all the variable then to i get the error def approvereject(request): files = os.path.join(settings.MODELS, 'classifierfinal.pkl') with open(files, 'rb') as file: classifier = pickle.load(file) # classifier = joblib.load(file) converted_data = input_con(data) print(data) output = classifier.predict([converted_data]) print(output) dis_out = output_con(output) print(dis_out) dis_output = dis_out del converted_data del output del dis_out return render(request, 'output.html', {'output': dis_output}) def clear_data(request): data.clear() return render(request, "landing.html") -
Django crispy forms tabholder can't change css
In my form i would like to change the style of the tabs, if i add a css_class to TabHolder it won't render it, it just keeps the default class. Here is the init of the modelform. def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_method = 'POST' self.helper.layout = Layout( TabHolder( Tab(_('Company'), 'name', css_class='nav-item active'), Tab('Address', 'country', css_class='nav-item'), Tab('Info', 'email', 'phone', 'website', css_class='nav-item'), css_class='nav nav-tabs nav-tabs-highlight nav-justified mb-0' ), ButtonHolder( Submit('submit', "Submit form", css_class='btn btn-primary') ), ) As you can see in TabHolder there is css_class='nav nav-tabs nav-tabs-highlight nav-justified mb-0' but it keeps showing just css_class='nav nav-tabs' -
Html is not recognizing block, endblock arguments. Danjo query
*I am having trouble in my index.html file. {% extends 'base.html' %} works. But everything b/w {% block content %}{% endblock content %} doesn't execute. Here are my files. views.py:-* **from django.shortcuts import render def index(request): return render(request, 'main/index.html')** base.html:- **<!doctype html> {%load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <title>To Do App</title> </head> <body> <div> <nav class=" navbar fixed-top navbar-dark bg-dark"> <a class="navbar-brand" href="/">To Do App</a> </nav> <div class="container"> ***{% block content %} {% endblock content %}*** </div> </div> </body> </html>** index.html:- **{% extends 'base.html'%} {% block content %} <div class="row"> <div class="col"> <h2>Add Item</h2> </div> </div> {% endblock content %}** All it shows is a navbar of dark color saying To Do App I also tried adding advanced things like form but it didn't work so then i added this heading saying Add Item. And guess what it doesn't work -
How to change the Django-allauth default url patterns?
while using the django-allauth as the registeration system, the following codes work well: urls.py urlpatterns = [ path('accounts/', include('allauth.urls')), path('admin/', admin.site.urls), ... ] so, under this settings: when the user wants to signin, then go to 'example.com/accounts/login' when the user wants to signup, then go to 'example.com/accounts/singup' ... but now I want to change the urls to something like: when the user wants to signin, then go to 'example.com/staff/login' when the user wants to signup, then go to 'example.com/staff/singup' ... I just want to change 'accounts' in the urls to 'staff'. I've just tried to revise the urls.py to: urlpatterns = [ path('staff/', include('allauth.urls')), path('admin/', admin.site.urls), ] most of the registration funcitons worked well, except the email comfirmtion. I reveived the confirmation email and clicked on the comfirmation button, but then the redirect url will always be 'example.com/accounts/login', which raise a 404 error. I want to know how to fix this problem, I will: fix it, if this can be done in a few steps use the default settings, if this is complicated or will bring some risks. Versions: Python: 3.8.1 Django: 3.0.4 Django-allauth:0.41.0 I am a freshman on coding (and English), thank you very very much. -
Query for GET request in django
My model: class ABC(models.Model): user_id = models.IntegerField(null=True) itemId = models.IntegerField(null=True) calorie_count = models.IntegerField() I'm trying to get data from database in following manner: Url: /api/?user_id=<user_id> Method: GET, Output: - Response Code: 200 - { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } and also I want to get the user id with the maximum calorie intake till date API. What will be the query for these 2 API ? -
Django filter by datetime month__gte is not working
I'm using Django 2.2 I have a created field of DateTime type. I'm using following command to filter the records which are greater than specific date q.filter(created__year__gte=2020, created__month__gte=3, created__day__gte=1) In my database there are records for March (3) month and more but not for February (2). When above command is executed, it gives me queryset list of data greater than March 1. But when I use the following command q.filter(created__year__gte=2020, created__month__gte=2, created__day__gte=28) Where month is February (2), it is not giving any data and the queryset is blank. -
ForeignKey and One To Many
i having trouble with a form and a view i have 3 tables: Product Order OrderItem. in the view: i have create Order, and save it to the DB and then i wanted to use the neworder ID and store it in the OrderItem Form. but for somereason when i save the From nothing happen in the DB. see my views,py, in short: i am trying to link Order to OrderItem. Model.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def date_createdview(self): return self.date_created.strftime('%B %d %Y') class Product(models.Model): CATEGORY = ( ('General', 'General'), ('SmartHome', 'SmartHome'), ('Software', 'Software'), ('Mobile', 'Mobile'), ) name = models.CharField(verbose_name='שם', max_length=200, null=True) price = models.FloatField(verbose_name='מחיר', null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY, verbose_name='קטגוריה') description = models.CharField(max_length=200, null=True, verbose_name='מלל חופשי') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('New', 'New'), ('Work in progress', 'Work in progress'), ('completed', 'completed'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def date_createdview(self): return self.date_created.strftime('%d/%m/%Y') class OrderItem(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) order = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=True) def __str__(self): return self.product.name Views.py def createOrder(request, pk): customer = … -
Can selected option tag can carry multiple values using django?
I have this selection in my html <select id="days" name="days" onchange="periods(this)" required> <option>-----</option> {% for perfume in s %} <option value="{{perfume.id}}" value="{{perfume.adddate}}" data-days="{{perfume.adddate}}">{{perfume.product}} - {{perfume.adddate}} Days </option> {% endfor %} </select> -
"Missing staticfiles manifest entry" but no apparent spelling mistakes and path correctly included in .json file
I am running into a classic ValueError: Missing staticfiles manifest entry for 'habitap/img/settings.png' when deploying my app on heroku but can't find where the error could be: 1) I can't see any apparent spelling mistakes between the template where I call the file and the path: How I call the file: <img src="{% static 'habitap/img/settings.png' %}"> and the path to the actual folder is: static/habitap/img/settings.png 2) the path seem to be correctly referenced in the file staticfiles.json: "habitap/img/settings.png": "habitap/img/settings.0900b5e534c2.png", The error could be coming from the use of ` instead of " maybe but all my other static files are being served correctly and I don't think I am doing anything different. I am conscious I am giving very little clue but i am a taker for any tips you may provide at this stage. Thank you ! -
Chart.js not displaying Django Rest API data
I have REST API with django rest framework like this : [ { "id": 2, "timestamp": "2020-03-04T11:46:10+07:00", "vibration": 3, "moisture": 70, "gps_latitude": "-7.760776", "gps_longitude": "110.376113", "gyro_x": 6.58, "gyro_y": 85.0, "gyro_z": -3.9, "accelero_x": 6.58, "accelero_y": 85.0, "accelero_z": -3.9, "displacement": 10, "node_id": 1 }, { "id": 3, "timestamp": "2020-03-05T11:46:10+07:00", "vibration": 4, "moisture": 40, "gps_latitude": "-5.760776", "gps_longitude": "115.376113", "gyro_x": 5.58, "gyro_y": 55.0, "gyro_z": -5.9, "accelero_x": 5.58, "accelero_y": 55.0, "accelero_z": -5.9, "displacement": 50, "node_id": 1 }, { "id": 4, "timestamp": "2020-03-12T11:46:10+07:00", "vibration": 8, "moisture": 90, "gps_latitude": "-5.769776", "gps_longitude": "125.376113", "gyro_x": 7.58, "gyro_y": 65.0, "gyro_z": -9.9, "accelero_x": 4.58, "accelero_y": 45.0, "accelero_z": -4.9, "displacement": 40, "node_id": 2 }] And this is the code for making rest API : models.py from app directory from django.db import models from django.contrib.auth.models import User class Data(models.Model): node_id = models.ForeignKey("Node", on_delete=models.CASCADE) timestamp = models.DateTimeField() vibration = models.IntegerField() moisture = models.IntegerField() gps_latitude = models.CharField(max_length=250) gps_longitude = models.CharField(max_length=250) gyro_x = models.FloatField() gyro_y = models.FloatField() gyro_z = models.FloatField() accelero_x = models.FloatField() accelero_y = models.FloatField() accelero_z = models.FloatField() displacement = models.IntegerField() def __str__(self): return self.node_id class Node(models.Model): node_id = models.IntegerField() This is serializers.py from app directory : serializers.py from .models import Data,Node from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField() … -
Populating drop-down list in Django
Given that I have 2 models: Department Course My django project directories are structured as such: \timetable_generator \detailscourse \templates \detailscourse \partials add_course.html admin.py models.py views.py \detailsdepartment \templates \detailsdepartment \partials add_department.html admin.py forms.py models.py views.py models.py-detailsdepartment looks like this: from django.db import models # Create your models here. class Department(models.Model): department_id = models.CharField(primary_key=True, max_length=20) department_name = models.CharField(max_length=100) def __str__(self): return self.department_name forms.py-detailsdepartment looks like this: from django import forms from .models import Department class DepartmentForm(forms.ModelForm): class Meta(): model = Department fields = '__all__' views.py-detailsdepartment looks like this: from django.shortcuts import render, redirect from django.contrib import messages from .models import Department from .forms import DepartmentForm # Create your views here. def adddepartment(request): form_class = DepartmentForm form = form_class(request.POST or None) if request.method == 'POST': if form.is_valid(): cleaned_info = form.cleaned_data form.save(commit=True) messages.success(request, 'The department is added successfully.') return redirect('/detailsdepartment/adddepartment') else: messages.error(request, 'Department ID already exists.') return redirect('/detailsdepartment/adddepartment') else: return render(request,'detailsdepartment/add_department.html', {'form':form}) admin.py-detailsdepartment looks like this: from django.contrib import admin from .models import Department # Register your models here. class DepartmentAdmin(admin.ModelAdmin): list_display = ['department_id', 'department_name'] admin.site.register(Department, DepartmentAdmin) And the web page of the Department section looks like this add_course.html-detailscourse looks like this: . . . <div class="row mb-5"> <div class="col-lg-12"> <form class="p-4 p-md-5 border … -
Django schedule new events for an object
I am working on a Django app. The purpose of the app is to be able to select a device and then select days of the week and time. After the user clicks save a new scheduled event should be created for that device which sends a request to the Url(already stored in database) of the device for the selected days and time. I don’t know how to achieve this. It would be great if some can help me. -
Can we embed param in URL in Django app from url.py?
I want to embed param in URL by default like I have end point abc.com/abc with call type GET I call from postman like this abc.com/abc?isActive=1 now I want Django to embed key=1 in URL Like This abc.com/abc?isActive=1&key=1 in url.py file I now it looks no sense in it but I need this for some purpose