Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
expanding dict model field in django
I need a way to be able to enter an unspecified number of arbitrary, integer values with an auto-incrementing key into a dictionary in a django model. It would need to look, or at least function, like this: { "1":6, "2":10, "3":0, ... "n":42 } I'm hoping there will be a simple solution like: class Foo(models.Model): title = models.CharField(max_length=100) dictOfInts = { models.AutoField(): models.IntegerField, models.AutoField(): models.IntegerField, models.AutoField(): models.IntegerField ... # it would start with just one and automatically add more k-v pairs as nessary } #other fields ect def __str__(self): return self.title Unfortunately, I know that doesn't work and wouldn't function how the comment suggests, but it would need to act like that for the end-user. I've looked through the docs and the only workaround I found there was using models.JSONField(), but that requires you to type out the dict yourself, which is not ideal. Another possible way that I found would be to separate the dict and the k-v pairs, linking them with a foreign key, but I couldn't quite figure out how to integrate it and it seemed very messy even if I could. If you need any more info, just let me know. Any help is much … -
Unable to push json file to Heroku for database data dump
I'm working on a school project, I have no experience with any of this and am having a hard time with this last step of setting up a website. For some background, the front end is coded in Next.js, backend is Python utilizing Django, and I have deployed the backend to Heroku (I have the app built and the database (postgreSQL) setup). I have done all of this following a tutorial that I found on Udemy which is only about a year old. I have run into some issues along the way but was able to figure them out after some trial and error, but this one is really giving me a hard time. So, in the tutorial he does a datadump and puts it into a file named "dump.json", then he runs the following command: heroku run python manage.py loaddata dump.json, which dumps the data into Heroku and the database populates and his Heroku app is up and running (it's connected to the Django rest framework, which is coded in the front end). Well, here is what I get when I run the command, I have to specify the path to manage.py otherwise it won't work, fyi... I have … -
django "no such table" when adding database entries via terminal
I am trying to create a relational database (one to many) in my models.py file. But when trying to add entries into my database i get an error saying: django.db.utils.OperationalError: no such table: app1_prices. I have ran makemigrations and migrate in the terminal as well, so that must not be the problem models.py from django.db import models class Figure(models.Model): id = models.CharField(max_length=12, primary_key=True) pieces = models.IntegerField() def __str__(self): return self.id class Prices(models.Model): id = models.ForeignKey(Figure, on_delete=models.CASCADE, primary_key=True) price_new = models.DecimalField(decimal_places=2, max_digits=8) price_used = models.DecimalField(decimal_places=2, max_digits=8) date = models.DateField(blank=True, null=True) def __str__(self): return self.id, self.date 0001_initial.py from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Figure', fields=[ ('id', models.CharField(max_length=12, primary_key=True, serialize=False)), ('pieces', models.IntegerField()), ], ), migrations.CreateModel( name='Prices', fields=[ ('id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to='app1.figure')), ('price_new', models.DecimalField(decimal_places=2, max_digits=8)), ('price_used', models.DecimalField(decimal_places=2, max_digits=8)), ('date', models.DateField(blank=True, null=True)), ], ), ] The code i have tried inside the terminal: >>> from app1.models import Figure, Prices >>> f1 = Figure("sw0001a", 5) >>> f1.save() >>> p1 = Prices(f1.id, 2.00, 1.20, "2022-05-03") >>> p1.save() django.db.utils.OperationalError: no such table: app1_prices -
Increasing the searching speed of Django set.all()
I am using Django to filter through a MongoDB full of data. Right now I have code that is working and have found where my slowdown is at... def does_this_property_apply(prop, app, dev, event): for platform_device in prop.platformdevice_set.all(): for event in platform_device.applicable_events.all(): if event.name == event: for app in platform_device.applicable_app.all(): if app.name == app: for device in platform_device.applicable_device.all(): if device.name == dev: print("This property applies") Basically I have 400+ properties that have a bunch of metadata. Inside of each property is a platform_device object (model) that contains information such as app, dev, and event. Think of it as this property only applies to certain applications, on certain devices, on certain user actions (events). Each property can have multiple of these. I am new to Django and trying to find out how I could quickly search all platform_device in the database and find if this property (prop) is applicable to my event, device, and application. class PlatformDevice(models.Model): _id = models.UUIDField(unique=True, primary_key=True,default=uuid.uuid4, editable=False) name = 'Property Specifics' property_field = models.ForeignKey('Property', on_delete=models.CASCADE) applicable_app = models.ArrayReferenceField(to=Platform, on_delete=models.CASCADE, blank=True) applicable_device = models.ArrayReferenceField(to=Device, on_delete=models.CASCADE, blank=True) applicable_events = models.ArrayReferenceField(to=Event, on_delete=models.CASCADE, blank=True) event_group = models.ArrayReferenceField(to=EventGroups, on_delete=models.CASCADE, blank=True) def __str__(self): return self.name -
comments display wrong when delete/edit button is removed due to authentication
My comment section is acting fine when am the user who typed the comments and have permission to see the edit delete button. Like in picture below: But when i enter on a user who dident post any of the comments and the delete and edit button dosent show its a mess picture below: Its wierd how do i fix it so the none owner of the comment that dosent see the edit/delete button sees the feild the same just excluded the delete/edit button? Would really appreciate some help product_detail.html The code starts at the bottom of the template under Reviews {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price … -
django-formset package use in class base view
when I use this package (django-formset 0.8.8) from "FormCollections" class after submit form redirect to success URL but the data doesn't saved in database this model is for quiz data for every device model.py from django.db import models from device.models import Device class QuestionTraining(models.Model): ANSWER_CHOICES = ( ('1', 'گزینه 1'), ('2', 'گزینه 2'), ('3', 'گزینه 3'), ('4', 'گزینه 4'), ) device = models.ForeignKey( Device, on_delete=models.CASCADE, verbose_name='دستگاه') question = models.CharField(max_length=500, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) answer = models.CharField(max_length=1, choices=ANSWER_CHOICES, null=True) def __str__(self): return self.question I use this form to show inline formset for each quiz forms.py from django import forms from .models import QuestionTraining class CreateQuestionTrainingDeviceForm(forms.ModelForm): class Meta: model = QuestionTraining fields = ['device'] class CreateQuestionTrainingForm(forms.ModelForm): class Meta: model = QuestionTraining fields = ['question', 'op1', 'op2', 'op3', 'op4', 'answer'] class PhoneNumberForm(forms.Form): phone_number = forms.fields.CharField() label = forms.fields.CharField() class QuestionCollection(FormCollection): min_siblings = 1 max_siblings = 5 extra_siblings = 1 question = CreateQuestionTrainingForm() class ContactCollection(FormCollection): divice = CreateQuestionTrainingDeviceForm() question = QuestionCollection() after submitting form, the data doesn't save in database, but redirect to success URL views.py class QuestionTrainingCreateView(FormCollectionView): template_name = 'question_training/create.html' collection_class = ContactCollection success_url = '/question_training/list' -
Django objects cannot be access from outside the shell
I'm going to assume this is a settings issue, but I just can't seem to figure it out. This is my views.py file from django.shortcuts import render from blogPost.models import blogpost def index(request): blog_list = blogpost.objects.all() context = {'blog_list': blog_list} print(context) return render(request, "index.html",context) When I run the server, I get this error Internal Server Error: /blogPost/ Traceback (most recent call last): File "C:\Users\Jonny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Jonny\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonny\Dropbox\Projects\django_app\meme_django_app\meme_django_app\blogPost\views.py", line 5, in index blog_list = blogpost.objects.all() AttributeError: 'function' object has no attribute 'objects' I know that blogpost does have objects because when I run the same command within the shell I get an output In [1]: from blogPost.models import blogpost In [2]: blogpost.objects.all() Out[2]: <QuerySet [<blogpost: blogpost object (1)>, <blogpost: blogpost object (2)>]> Why isn't my object accessible in my .py file, but it is in the shell? -
Get User model data in drf-social-oauth2 response after login
So I am using drf-social-oauth2 for authentication and React in the frontend, const handleGoogleLogin = (response) => { setLoading(true); axios .post(`${apiBaseURL}/auth/convert-token`, { token: response.accessToken, backend: "google-oauth2", grant_type: "convert_token", client_id: drfClientId, client_secret: drfClientSecret, }) .then((res) => { const { access_token, refresh_token } = res.data; const cookies = new Cookies(); cookies.remove("google_access_token"); cookies.remove("google_refresh_token"); cookies.set("google_access_token", access_token, {path: "/", maxAge: 24*60*60}); cookies.set("google_refresh_token", refresh_token, {path: "/", maxAge: 24*60*60}); setLoading(false); console.log(res); console.log(res.data); // window.location.href = `${appBaseURL}/`; }) .catch((err) => { setLoading(false); createErrorNotification(); }); }; Here the login is successful and everything works fine, however the response I get is just {access_token: 't3LqiUvz0x4HBWGDsSyLP7fsyKejJf', expires_in: 63583.018772, scope: 'read write', refresh_token: 'GEkGz8teGATlYY0pQ1zuntN8ODfFT4', token_type: 'Bearer'} What can I do to have all the user info like his model fields in the response? Couldn't find anything related to this anywhere -
Django admin models only showing quantity
I have been trying to find answers on some related questions, but not successful. I've created models and registered in the admin.py, all models are showing except Category models. I have tried expanding and collapsing it. It only flashes the 5 categories and then shows only quantity. I would really appreciate your assistance Image : Only quantity shows instead of the actual 5 categories Models.py class CategoryAdmin(admin.ModelAdmin): list_display = ['title', 'parent', 'status'] list_filter = ['status'] class Category(MPTTModel): STATUS = ( ('True', 'True'), ('False', 'False'), ) parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=30) keyword = models.CharField(max_length=255) description = models.CharField(max_length=255) image = models.ImageField(blank=True, upload_to='images/') status = models.CharField(max_length=10, choices=STATUS) slug = models.SlugField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) class MPTTMeta: order_insertion_by = ['title'] def __str__(self): return self.title Admin.py class CategoryAdmin2(DraggableMPTTAdmin): mptt_indent_field = "title" list_display = ('tree_actions', 'indented_title', 'related_products_count', 'related_products_cumulative_count') list_display_links = ('indented_title',) def get_queryset(self, request): qs = super().get_queryset(request) # Add cumulative product count qs = Category.objects.add_related_count( qs, Product, 'category', 'products_cumulative_count', cumulative=True) # Add non cumulative product count qs = Category.objects.add_related_count(qs, Product, 'category', 'products_count', cumulative=False) return qs def related_products_count(self, instance): return instance.products_count related_products_count.short_description = 'Related products (for this specific category)' def related_products_cumulative_count(self, instance): return instance.products_cumulative_count related_products_cumulative_count.short_description = 'Related products (in tree)' … -
When trying to use a rq worker get rq.exceptions.DeserializationError
When trying to run django-rq worker I keep getting this error 15:35:26 Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 249, in _deserialize_data self._func_name, self._instance, self._args, self._kwargs = self.serializer.loads(self.data) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/db/models/base.py", line 2141, in model_unpickle model = apps.get_model(*model_id) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 199, in get_model self.check_models_ready() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 1026, in perform_job self.prepare_job_execution(job) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 911, in prepare_job_execution self.procline(msg.format(job.func_name, job.origin, time.time())) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 284, in func_name self._deserialize_data() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 252, in _deserialize_data raise DeserializationError() from e rq.exceptions.DeserializationError Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 249, in _deserialize_data self._func_name, self._instance, self._args, self._kwargs = self.serializer.loads(self.data) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/db/models/base.py", line 2141, in model_unpickle model = apps.get_model(*model_id) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 199, in get_model self.check_models_ready() File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/django/apps/registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 1026, in perform_job self.prepare_job_execution(job) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/worker.py", line 911, in prepare_job_execution self.procline(msg.format(job.func_name, job.origin, time.time())) File "/home/john/PycharmProjects/api.to/venv/lib/python3.8/site-packages/rq/job.py", line 284, in func_name self._deserialize_data() File … -
Not saving a user to a group
I have this model in the admin panel. when I create this user from the admin panel, he simply is not added to the group. if I also try to add a user to the group through the shell, it works, but in the code is when creating (looked through the debugger) it returns None and does not add the user to the group. @admin.register(ProxyMechanicUser) class Mechanic(admin.ModelAdmin): list_display = ('username', 'phone_number', 'last_login', 'is_active') fields = ('username', 'password', 'is_staff', 'is_active', 'first_name', 'last_name', 'email', 'phone_number', 'groups','date_joined') readonly_fields = ('date_joined', 'last_login') def save_model(self, request: HttpRequest, obj, form, change): password = form.cleaned_data['password'] obj.password = make_password(password=password) obj.save() group = Group.objects.get(name=MECHANIC) obj.groups.add(group) # return None and dont setup user in groups # group.user_set.add(obj) its too dont work. return super(Mechanic, self).save_model(request, obj, form, change) -
Double post after refresh django
After i posted my comment and deside to refresh the page it adds the same comment over and over on every refresh how can i stop this? The code for the comment review is at the far bottom in the template.html. And the review code is under "def product_detail" in the views.py Hope someone can give me some tips so if i refresh it dosent do another post. template {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> <div class="row"> <div class="col-12 col-md-6 col-lg-4 offset-lg-2"> <div class="image-container my-5"> {% if product.image %} <a href="{{ product.image.url }}" target="_blank"> <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}"> </a> {% else %} <a href=""> <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> </a> {% endif %} </div> </div> <div class="col-12 col-md-6 col-lg-4"> <div class="product-details-container mb-5 mt-md-5"> <p class="mb-0">{{ product.name }}</p> <p class="lead mb-0 text-left font-weight-bold">${{ product.price }}</p> {% if product.category %} <p class="small mt-1 mb-0"> <a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}"> <i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }} </a> </p> {% endif %} {% if product.get_rating > … -
Django can't load images nor files to neither media nor admin
I'm trying to learn Django but I'm struggling to make a form using crispy forms to load some user info, file and image. I can load info just fine and display it in admin but I'm struggling to do the same for files for Images and Files, aka image and resume fields. The forms shows just fine but just won't take input for both images and files. Please tell me If I have to provide more detail, any help is appreciated thanks. Models.py class Application(models.Model): id = models.AutoField(primary_key=True) jobpost = models.ForeignKey(JobPost, on_delete=models.CASCADE, editable=False, related_name='post', blank=True, null=True) applicant = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, related_name='recruits') Firstname = models.CharField(max_length=200, default="") Lastname = models.CharField(max_length=200, default="") Cin = models.CharField(max_length=200, default="") Telephone = models.IntegerField(default=212) Email = models.EmailField(max_length=200, default="") displaypic = models.ImageField(upload_to='images/', null=True, blank=True, default='images/default.png') resume = models.FileField(upload_to='resume/', null=True, blank=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) date_applied = models.DateTimeField(auto_now=False, auto_now_add=True) archived = models.BooleanField(default=False, editable=False) def __str__(self): return self.applicant.username class Meta: ordering = ["-date_applied", "-updated"] views.py (please only see if 'applyjob' clause) @login_required def detailjob(request, job_id): title = 'Jobs' profile = Profile.objects.get(user=request.user) job = JobPost.objects.get(id=job_id) posts = JobPost.objects.exclude(id=job_id) if request.method=='POST': if 'applyjob' in request.POST: form = ApplicationForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.jobpost = job instance.applicant = request.user instance.save() return … -
Django package / solution: web app for data collection and management
We are in need of creating an app using python which will be mainly used for data collection or data entry relatively wrt accounting. Need the solution to display records in table grid allows user to add, edit, delete, search, print etc.. the records. Kindly suggest the best frame work for the same. I'm though trying to learn Django. Wondering if that'll suffice the needs. -
"Relation does not exist" after delete migration files
Can you please explain, why I get some issue after deleting migration files from database and in local? If the relation does not exist, how can I create this relation? I have active ForeignKey, but uncommented and commented the field and trying makemigrations, migrate, migrate --fake didn't work for me anyway. -
Django-axes Errors: 'Settings' object has no attribute . .
I've run into a lot of attribute errors when using django-axes. Whenever I fix one of them by setting the default attributes, more start showing up. I followed the documentation for installation. Here is my code... settings.py """ Django settings for ChatTest project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! if('SECRET_KEY' in os.environ): SECRET_KEY = os.environ["SECRET_KEY"] if('SECRET_KEY' not in os.environ): SECRET_KEY = 'o1(-!s0um*rj47xv8vk@)pdq3)2c1o-et!v!rnqq3p4m(9592k' #Secret key I use for local development DEBUG = True ALLOWED_HOSTS = ['.railway.app','localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'Chat.apps.ChatConfig', 'django_cleanup.apps.CleanupConfig', 'axes', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'axes.middleware.AxesMiddleware', ] X_FRAME_OPTIONS = 'DENY' ROOT_URLCONF = 'ChatTest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = … -
Showing data on frontend from sql databases using django
For fetching data from databases, I usually see people create a class in models.py and they migrate it, and then they fetch data from databases and show it on the front-end. my question is, i already have a database which has student_info table and has lots of data. I don't want to define student_info class in models.py and do migration. Instead, since i already have student_info data in sql database. so I want to fetch it directly. can i do so? one method i know of doing the same, is directly connecting sql server in views.py as; mydb=mysql.connector.connect(host="localhost",user="root",password="******",database=database_name) and fetching the data and passing it as variable in index.html. But the problem is, it fetches data only once, and if i refresh the page where local server is running, all the content will disappear, and server will report Broken pipe from ('127.0.0.1', 59579) and to see the data, again i need to restart the sever. Kindly looking for a better approach to show data on front-end from the existing databases -
how to get messages (data) in real time from database using ajax and django
i want to get messages in realtime using ajax and django for the backend, i have written the logic to send the messages and that is working, but i want to get a message immediately another user sends me a message without having to refresh the page, i tried using ajax interval but it seem i am not getting a hang of how to properly use the interval and forloop in ajax, what is it that i should do to achive the result i want? directs.html <div class="chat-wrapper"> {% for direct in directs %} {% if direct.sender == request.user %} <div class="chat-message-right pb-2"> <div> <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a> <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div> </div> <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3"> <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> --> {{direct.body}} </div> </div> {% else %} <div class="chat-message-left pb-2"> <div> <a href=""><img src="{{ direct.sender.profile.image.url }}" class="rounded-circle mr-1" alt="img" width="40" height="40" /></a> <div class="text-muted small text-nowrap mt-2" style="font-size: 10px; color: rgba(180, 180, 180, 0);"><p style="font-size: 10px; color: black;">{{direct.date|timesince}} ago</p></div> </div> <div class="flex-shrink-1 bg-light rounded py-2 px-3 ml-3"> <!-- <div class="font-weight-bold mb-1">Sharon Lessman</div> --> {{direct.body}} </div> … -
Making a json structure with nested serializers concept
I'm trying to make an api with Django Rest Framework , the api format looks like this, I'm new to nested serializer concept so I've tried to make relational models and nested serializer that is available in the documentation but it doesn't work for me , is there anyone who can help ? { "devices": { "device": [{ "type": "MP", "time": "18/05/2022, 15:15:10", "MP_name": "MP1", "SN": "EMSMP001", "plant_name": "Greenaftech", "gatway_name": "gw1", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, "apparent_power": 2.3, "FP": 0.99, "frequency": 49.98 }, { "type": "TP", "time": "18/05/2022, 15:15:10", "TP_name": "TP1", "SN": "EMSMP002", "plant_name":"Greenaftech", "gatway_name":"gw1", "adress": 12, "baud_rate":1, "UA":1, "UB":1, "UC":1, "UAB":1, "UBC":1, "UAC":1, "IA":1, "IB":20, "IC":43, "frequency":11, "Pa":88, "Pb":30, "Pc":23, "Pt":42, "Qa":21, "Qb":31, "Qc":49, "Qt":82, "Sa":63, "Sb":83, "Sc":10, "St":39, "FPa":54, "FPb":43, "FPc":34, "FPt":87, "THDV":56, "THDI":74, "max_demand":2, "count_E":8, "count_Er":55 }, { "type": "VFD", "time": "18/05/2022, 15:15:10", "vfd_name": "VFD1", "SN": "EMSMP002", "plant_name":"plant1", "gatway_name":"gw3", "adress": 7, "baud_rate":1, "c00":8, "c01":8, "c02":8, "c03":8, "c04":8, "c06":8, "c07":8, "c12":8, "c13":8, "c14":8, "c15":8, "c16":8, "c17":8, "c18":8, "c19":8, "c20":8, "c21":8, "c23":8, "c24":8, "c25":8, "c27":8 }, { "type": "MP", "time": "18/05/2022, 15:15:15", "MP_name": "MP2", "SN": "EMSMP001", "plant_name": "plant1", "gatway_name": "gw3", "adress": 1, "baud_rate": 9600, "voltage": 230, "current": 10, "active_power": 2.3, "reactive_power": 0.01, … -
Django urls + React Route
i have the next djnago urls.py: urlpatterns = [ path('register',views.registerPage, name="register"), path('login',views.loginPage, name="login"), path('logout',views.logoutUser, name="logout"), path('',views.index), path('createcompany',views.index), # path('',views.index, name='home'), path('test',views.index, name='test'), path('admin',views.administrare_view,name='admin'), ] and React route: <Router> <Drawer /> <Routes> <Route path="/" element={<Home />}/> <Route path="/createcompany" element={<RegisterPage />}/> <Route path="/login" element={<LoginPage />}/> <Route path="/test" element={<TestPage />}/> <Route path="/admin" element={<AdminPage />}/> </Routes> </Router> When i press the logout button it chnage the link to /logout but dosen't logout the user. If i type manually the link or i refresh the page the user is gonna to logout. The menu dynamically created from React const menuList=[ { id:1, text:"Profile", icon:<PersonIcon sx={{ color: 'gray' }} />, link:'/profile', }, { id:2, text:'Logout', icon:<LogoutIcon sx={{ color: 'gray' }} />, link:'/logout', }, ] <Tooltip title='Profile' placement='bottom' arrow enterDelay={500}> <IconButton onClick={userAvatar_Click} size="small" sx={{ ml: 2 }} aria-controls={open ? 'account-menu' : undefined} aria-haspopup="true" aria-expanded={open ? 'true' : undefined} > <Avatar sx={{ width: 32, height: 32 }}>M</Avatar> </IconButton> </Tooltip> <Menu anchorEl={anchorEl} id='account-menu' open={open} onClose={userAvatar_Close} onClick={userAvatar_Close} PaperProps={{ elevation: 0, sx: { overflow: 'visible', filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))', mt: 1.5, '& .MuiAvatar-root': { width: 32, height: 32, ml: -0.5, mr: 1, }, '&:before': { content: '""', display: 'block', position: 'absolute', top: 0, right: 14, width: 10, height: 10, bgcolor: … -
How to extract profile_pic of a user when they are signing in from Google
I'm making a django website, I have 2 login methods. One is the default email password login and another is by logging in from Google. What I want is when the user logs in from google django should automatically fetch the profile_pic of that user and save it in my user model. Here's my models.py for accounts app from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, Group # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, first_name, last_name, **extra_fields) def create_user_with_groups(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', False) user = self._create_user(email, password, first_name, last_name) group = Group.objects.get(name='Content Writer') user.groups.add(group) print(user.groups) return user def create_superuser(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, first_name, last_name, **extra_fields) # Custom user Model class … -
django nonrelated inlines with more models
Django nonrelated inlines with more models I have more than one model not related to each other I want in admin panel to fill these models together in one form this package is help https://pypi.org/project/django-nonrelated-inlines/ but I need an example for that !! -
Django/Vue -> Heroku: Static files not loading at production server
Static files load when DEBUG=True (locally and at the dev server), but not when DEBUG=False (production). STATICFILES_DIRS is set to my dist dir created by Vue, and dist is not in the .gitignore. Heroku runs collectstatic on every deploy by default (I have not changed this). The actual error is a 404 when trying to load any static file. The whitenoise package is being used. I've updated the middleware settings, and wsgi.py according to the docs, and have the settings variable which enables compression via whitenoise set (also according to the whitenoise docs). whitenoise usually works fine with other apps. I'm not sure what's wrong with this. The difference is that I'm using Vue for the first time. I'd never used a js framework before. Can anyone help? -
Is there a way or a tool which can help to map a line in server side script to its corresponding generated line in html page?
Which tool can be I used to determine which line in server side script has generated which line of code in html page in dynamic web application. for example in django application can we know which line of code in the django-template has generate which line of code in the corresponding html page -
how to extract data from an html form using django?
So guys i have a normal html form with some text input for a user registration, the form is like this: <form id="signup-form" action="#" method="post"> <label for="name">Full Name</label> <input autocomplete="off" type="text" name="username" id="name" class="name"> <label for="email">Email Adderss</label> <input autocomplete="off" type="email" name="emailAdress" id="email" class="email"> <label for="phone">Phone Number - <small>Optional</small></label> <input autocomplete="off" type="text" name="phone" id="phone"> <label for="password">Password</label> <input autocomplete="off" type="password" name="password" id="password" class="pass"> <label for="passwordCon">Confirm Password</label> <input type="password" name="passwordCon" id="passwordCon" class="passConfirm"> <input type="submit" form="signup-form" value="Signup Now" id="submit"> </form> and i wanna know how can i store the values of each input when the button is submitted and save them in the database, is there a way to call the input field by its ID and store it in Django?