Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nested data get request Django
Hi everyone I would like to Know hot to get data when i am using forenkey, i mean i have a many to one relarion but when i get data i don´t recive the responde how i would like. class AsigManager(models.Manager): def get_by_natural_key(self, Nom_Asig, horario): return self.get(Nom_Asig=Nom_Asig, horario=horario) class ProfManager(models.Manager): def get_by_natural_key(self, Nombre, profesion): return self.get(Nombre=Nombre, profesion=profesion) class Asignatura(models.Model): Nom_Asig = models.CharField(max_length=200) horario = models.CharField(max_length=200) objects = AsigManager() class Meta: unique_together = [['Nom_Asig', 'horario']] class Profesor(models.Model): asignatura = models.ForeignKey(Asignatura, on_delete=models.CASCADE) Nombre = models.CharField(max_length=200) profesion = models.CharField(max_length=200) objects = AsigManager() class Meta: unique_together = [['Nombre', 'profesion']] class ProfesorView(View): def get(self, request): profe = list(Profesor.objects.values()) if len(profe)>0: datos = {'message':'Succes','Profesores: ':profe} else: datos = {'message':'Profesor Not Found...'} return JsonResponse(datos) but i Woudl like to get de Asignatura data when i get de Profesor data such as a object or list inside the Profesor request enter image description here -
elasticsearch in django rest framework in virtualenvironment
I tried to use elasticsearch in virtual environment in django rest framework. I am not using docker. When I use the port 127.0.0.1:8000, I got following error. NewConnectionError(<urllib3.connection.HTTPConnection object at 0x06B3EC40>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) When I use the port :9200 or :9300 and call the api in postman, it doesnt connect and nothing happens. My elasticsearch.yml network: host: 0.0.0.0 :http: port: 9300 My setting.py ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9300'}, } I even tried using curl to call the api from cmd but it says the connection failed. I have written all the views for search and also all documents class, but I dont think I need to post these here because the main problem is how to run the api. I am using virtual environment. -
Nested for Loop in django template
{% for i in some_dict %} {% for value in some_dict.i %} {% endfor %} {% endfor %} as i understended python try to find value with 'i' key, but i want to find value with the key that contains in i Сan i make something like this? How if i can? Maybe there is another more correct way for unpucking dicts? Dict example: {a: [val1, val2, val3], b: [val1, val2, val3]} -
giving different related names for a foreign key for the children in django multitable inheritance
I have these models: class Theme(models.Model): name = models.charfield() class Product(models.Model): theme = models.ForeignKey(Theme) class PhysicalProduct(Product) class Course(Product): ........ class Book(Product): ........ and I want to is to fetch only the courses and the books related to a specific theme, with prefetch_related method but the problem is that I don't think there's a way to do that but to add the theme field to each child of the Product model and give each one a specifically related name: class Theme(models.Model): name = models.charfield() class Product(models.Model): ....... class PhysicalProduct(Product): theme = models.ForeignKey(Theme) class Course(Product): theme = models.ForeignKey(Theme) ........ class Book(Product): theme = models.ForeignKey(Theme) ........ is there a way that I can keep the theme field in the Product model and be able differentiate between specific types of products that I only wanna fetch with prefetch_related -
Can't create model field automatically error in querystring
I have: class ZipCode(models.Field): def __init__(self, *args, **kwargs): kwargs['verbose_name'] = "Cep" super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["verbose_name"] return name, path, args, kwargs def db_type(self, connection): return 'char(8)' class Address(models.Model) : zip = ZipCode() it works fine and make a verbose correctly in the field Now, i would like of implementand a automatic parameteres for lenght and verbose_name I did like follow: class ZipCode(models.Field): def __init__(self, length=None, verbose=None, *args, **kwargs): self.length = length self.verbose = verbose kwargs['verbose_name'] = self.verbose super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() return name, path, args, kwargs def db_type(self, connection): print (F"char({self.length})") return F"char({self.length})" class Address(models.Model) : zip = ZipCode(16, 'cep') .... The expression print (F"char({self.length})") returns char(16). as expected But it gear the error on mysql query **return self.cursor.execute(sql) File "C:\Users\Carlos\AppData\Roaming\Python\Python310\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "C:\Users\Carlos\AppData\Roaming\Python\Python310\site-packages\MySQLdb\connections.py", line 254, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, `address` varchar(200) NOT NULL, `number` varchar(10) NOT NULL, ' at line 1") PS D:\Softwares\python\dj\hotplateprensas> * Histórico restaurado** How i can fixed it? -
I am facing this problem continuosully whats error in my code
Im facing the above problem while training my models. Some of the datas in my dataset are float numbers. but i want to keep them as float. How can i solve this issue -
Why am I getting Unsupported media type "application/json" in request error?
I'm using Postman to test an api. My local unit tests pass. But when I use the same request in Postman, I get { "errors": [ { "detail": "Unsupported media type \"application/json\" in request.", "status": "415", "source": { "pointer": "/data" }, "code": "unsupported_media_type" } ] } Using a breakpoint, get that result when unpacking request.data in the View. I made sure to set application/json in the Content-Type header, and even specified it as a parser. I still get the error. Can you see why? Part of the code where things break: class ProvisionCustomerView(APIView): permission_classes = [IsAuthenticated] serializer_class = ProvisionCustomerSerializer def post(self, request): customer_data = request.data When using postman, request.data returns: *** rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/json" in request. Although it works fine in a unit test. -
How is my list_display and list_editable clashing?
When I started building this project, it went pretty smoothly. But when I reached the admin, list_display and list_editable clashed: admin.py Code: from django.contrib import admin from .models import Article, Author # Register your models here. @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'main_txt', 'date_of_publication'] list_editable = ['title', 'main_txt'] def __str__(self): return self.title @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'join_date', 'email'] def __str__(self): return f"{self.first_name} {self.last_name[0]}" models.py: from django.db import models # Create your models here. class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField() email = models.CharField(max_length=300) phone_num = models.CharField(max_length=15) join_date = models.DateField() participated_art = models.ManyToManyField('Article', blank=True) class Article(models.Model): title = models.CharField(max_length=500) date_of_publication = models.DateField() creaters = models.ManyToManyField('Author', blank=False) main_txt = models.TextField() notes = models.TextField() Error Code: Exception in thread Django-main-thread: Traceback (most recent call last): File "C:\Users\Zhiyue\AppData\Local\Programs\Python\Python39\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Users\Zhiyue\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\Zhiyue\PycharmProjects\djangoProject1\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Zhiyue\PycharmProjects\djangoProject1\venv\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Zhiyue\PycharmProjects\djangoProject1\venv\lib\site-packages\django\core\management\base.py", line 546, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'CodeJangoHome.admin.ArticleAdmin'>: (admin.E124) The value of 'list_editable[0]' refers to the first field in 'list_display' ('title'), which cannot be used unless 'list_display_links' is set. System check … -
Django view template responsiveness
I am trying to work on the responsiveness of my django application on mobile view. So here is our it looks on a smaller screen size So I want to remove all the white space that I have marked in blue, which is supposed to separate one post from the next. Here is the code snippet associated with that section <section class="category-section"> <div class="container" data-aos="fade-up"> <div class="section-header d-flex justify-content-between align-items-center mb-5"> <h2>Politics</h2> <div><a href="politics" class="more">See All Politics</a></div> </div> <div class="row"> {% for politic in politics%} {% if forloop.counter < 11 %} <div class="post-entry-1 col-lg-2 col-md-6 col-xs-12 mx-1"> <a href="/politicalpost/{{politic.id}}"><img src="{{politic.image.url}}" alt="" class="post_img img-fluid"></a> <div class="post-meta float-right"> <span class="date">{{politic.category}}</span> <span class="mx-1">&bullet;</span> <span>{{politic.created_at}}</span> </div> <h2 class="mb-2"><a href="/politicalpost/{{politic.id}}">{{politic.title}}</a></h2> <span class="author mb-3 d-block">Ole Pundit</span> <p class="mb-4 d-block">{{politic.body| safe | truncatewords:15}}</p> </div> {% endif %} {% endfor %} </div> </div> </section> And here are some of the css style classes that are at play .post-entry-1 { margin-bottom: 30px; } .post-entry-1 img { margin-bottom: 30px; } .post-entry-1 h2 { margin-bottom: 20px; font-size: 20px; font-weight: 500; line-height: 1.2; font-weight: 500; } .post-entry-1 h2 a { color: var(--color-black); } .post-entry-1.lg h2 { font-size: 40px; line-height: 1; } .post-meta { font-size: 11px; letter-spacing: 0.07rem; text-transform: uppercase; font-weight: 600; font-family: … -
ManyToMany in Django Admin as Muti Select CheckBox
i'm using python 3.9 with django 4.1. I have list of apartments and list of their commodities, each apartment can have zero or more commodities. the modes are created as such: class Commodities(models.Model): name_en = models.CharField(verbose_name=_('English Name'), unique=True, blank=True, null=True, max_length=200) name_he = models.CharField(verbose_name=_('Hebrew Name'), unique=True, blank=True, null=True, max_length=200) name_fr = models.CharField(verbose_name=_('French Name'), unique=True, blank=True, null=True, max_length=200) class Meta: constraints = [ models.CheckConstraint( check=Q(name_en__isnull=False) | Q(name_he__isnull=False) | Q(name_fr__isnull=False), name='not_all_null_commodities' ) ] def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class Apartment(models.Model): address = models.ForeignKey(Address, verbose_name=_('Apartment Address'), on_delete=models.CASCADE) floor = models.IntegerField(verbose_name=_('Floor'), null=True, blank=True) apartment = models.CharField(verbose_name=_('Apartment'), null=True, blank=True, max_length=10) def __str__(self): return self.address.__str__() + \ (' ' + _('Entrance') + ' ' + self.address.entrance if self.address.entrance else '') + \ (' ' + _('Floor') + ' ' + str(self.floor) if self.floor else '') + \ (' ' + _('Apartment') + ' ' + self.apartment if self.apartment else '') class ApartmentCommodities(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, verbose_name=_('Apartment')) commodity = models.ForeignKey(Commodities, on_delete=models.CASCADE) def __str__(self): return self.apartment.__str__() + ' - ' + getattr(self.commodity, 'name_' + get_2l_lang()) I want in the admin page, when I add or modify an apartment, to see the commodities as multi-checkbox instead of selecting adding and removing each commodity line by line. … -
User creation on registrations Django
In my app, I want the user to register this code is showing no error but it is not saving in the database; if guys have any suggestions that would be very helpful. The reason I'm creating in this method because I have lots of other user groups because of that reason I wanna create the database model, form and views in this manner Thanks in advance Models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16,null=True) is_active=models.BooleanField(default=False) class justforfun(models.Model): Name=models.CharField(max_length=100,null=True) Roll_no=models.CharField(max_length=100,null=True) User=models.ForeignKey(User,on_delete=models.CASCADE) Forms.py class just(forms.Form): Name = forms.CharField( label='Name', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name', 'rows':1 }) ) Roll_no = forms.CharField( label='Roll-no', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Roll_no', 'rows':1 }) ) views.py def test2(request): form=just() if request.method=='POST': if form.is_valid(): user21=User.ojects.create( username=form.data["Name"], password=str(random.random(000000000000,999999999999)) ) user21.save() just_data=justforfun.objects.create( user=user21, Name=form.data["Name"], Roll_no=form.data["Roll_no"] ) just_data.save() context={ "form":form } return render(request, "just.html", context) -
Django v3.1 gets django_admin_bootstrapped exception saying "'future' is not a registered tag library"
We have upgraded an old project from Python v2.7 + Django v1.8 to Python v3.7 + Django v3.1 and fixed some compatibility issues during the change. As a result, the project works as expected in most parts. However, we noticed an exception when logging out of the admin console, saying 'future' is not a registered tag library. We are new to this area and highly appreciate any hints or suggestions. Exception details: TemplateSyntaxError at /api/admin/logout/ 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log rest_framework static tz Request Method: GET Request URL: http://test.local/api/admin/logout/ Django Version: 3.1.4 Exception Type: TemplateSyntaxError Exception Value: 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log rest_framework static tz Exception Location: /data/app/venv3.7/lib/python3.7/site-packages/django/template/defaulttags.py, line 1038, in find_library Python Executable: /data/app/venv3.7/bin/python Python Version: 3.7.9 Python Path: ['/data/app/APPLICATION', '/data/app/APPLICATION', '/var/lib/snapd/snap/pycharm-professional/297/plugins/python/helpers/pycharm_display', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/data/app/venv3.7/lib/python3.7/site-packages', '/var/lib/snapd/snap/pycharm-professional/297/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Mon, 15 Aug 2022 14:56:10 -0600 Error during template rendering In template /data/app/APPLICATION/django_admin_bootstrapped/templates/registration/logged_out.html, error at line 2 'future' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls app_tags bootstrapped_goodies_tags cache humanize i18n l10n log … -
IntegrityError at /auth/userreg/ (1048, "Column 'user_id' cannot be null")
I am a newbie in django, I am at learning stage I am creating a project appointment system where user and doctor can login . I want to register them as multiuser type for that I have extended abstract class and given one to one relation to other tables but when The code is execute and I click submit This error appears. all fields are correct there is no error in the code everything is working correct just this integrity error is not getting solved. I have not created any foriegn key just trying to create user at of the user registration . authenticate.models from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User # Create your models here. class User(AbstractUser): is_user = models.BooleanField('user', default=False) is_doctor = models.BooleanField('doctor', default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) views.py from django.shortcuts import render from django.contrib import messages # from django.contrib.auth.models import get_user_model from django.contrib.auth.models import User from authenticate_me.models import User_reg, dr_reg def login(request): return render(request, 'user/login.html') def register(request): if request.method … -
Get specific uuid object in view from model in django
I have django app in which user can upload files in course with 3 editable fields. models.py class Course(models.Model): course_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=20) thumbnail = models.ImageField(upload_to='thumbnails', null=False, default='default.jpg') videofile = models.FileField(validators=[FileExtensionValidator], upload_to='videos') def path(self): return self.url I have view to display those the thumbnails of all courses and when user click on thumbnail it redirects him to course detail page. urls.py path('course/<uuid:course_id>/', views.course_detail, name='course-detail') So my question is how can I get information about fields of model Course in my html file to display them. views.py def course_detail(request, *args, **kwargs): course = models.Course.objects.get() context = { 'course': course, } return render(request, 'courses/info_course_view.html', context) Without uuid i would just write pk=pk in brackets but since i use uuid i don't know how to make it work. template <div class="container"> {{ course.title }} </div> Thank you all for help! -
How to iterate django template variable in the jQuery selected element?
I am working on a chat system in which I can open multiple chat of users (just like facebook). When the user clicks on the username that is in the contact list, a chat popup gets open. Following is the snippet from my models.py, class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() class Meta: unique_together = ['first_person', 'second_person'] class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.CASCADE, related_name='chatmessage_thread') user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) Following is a query that I pass from views.py to my html template, threads = Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread') Following is the html code, <div class="chat_box"> <div class="chat_header" > <h1 class="chat_heading">(6) Contacts</h1> </div> <hr> <div class="chat_content" style="display: none;"> {% for thread in Threads %} <div class="user" id="{{ thread.second_person.id }}" thread-id = "{{thread.id}}" chat-id="chat_{{ thread.id }}"> <img id="my_img" src="{{user_personal.picture.url}}" class="user_icon"> {% if thread.first_person == user %} <h3 class="username">{{ thread.second_person.first_name }} {{ thread.second_person.last_name }}</h3> {% else %} <h3 class="username">{{ thread.first_person.first_name }} {{ thread.first_person.last_name }}</h3> {% endif %} <i class="fa fa-circle"></i> </div> {% endfor … -
Django Rest Framework transforming my APIView into a ModelViewSet
I have the following model, class Schema(models.Model): week = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(53)]) users = models.ManyToManyField(MyUser, related_name="users") class Meta: ordering = ('week',) The model holds a week number and list of users related to that week number. I have then created an APIView where the GET request fetches all the Schemas (my model), and the POST request does the following, if the week number is not in the database then it simply creates a row in the database for the given week number and the given users. If the week number is already present in the database then I simply overwrite the users related to that week number with the newly given users, the view looks like this, class SchemaView(APIView): permission_classes = (SchemaPermissions,) def get(self, request): schemas = Schema.objects.all() serializer = SchemaSerializer(schemas, many=True) return Response(serializer.data) def post(self, request): data = request.data serializer = SchemaSerializer(data=data) if serializer.is_valid(): input_data = serializer.validated_data week = input_data.get('week') user_ids = input_data.get('user_ids') if Schema.objects.filter(week = week).count() > 0: schema = Schema.objects.get(week = week).first() else: schema = Schema.objects.create(week = week) schema.users.set(user_ids) schema.save() return Response(SchemaSerializer(schema).data, status=status.HTTP_200_OK) else: return Response(status = status.HTTP_400_BAD_REQUEST) Now this works as expected, however now comes my problem. This only works for a single "Schema" (my model) on … -
Highlighting the first repeating loop element in django
Please tell me how to select only the first repeating element of the cycle in Jinja django? <table id="{{el.slug}}_table" class="table table-striped table-bordered table-sm " cellspacing="0" width="100%" > <thead> <tr> <th>expand</th> <th>Тип алерта </th> <th>hostname</th> <th>username</th> <th>message</th> <th>Actions</th> </tr> </thead> <tbody> {% regroup alerts|dictsort:"username" by username as alrt %} {% for all in alrt %} {% for ell in all.list %} {% if el.title == ell.title %} {% if forloop.first %} <tr class="table-primary"> <td class="row1">+</td> <td class="{{ rowcolors }}">{{ell.title}}</td> <td>{{ell.hostname}}</td> <td>{{ell.username}}</td> <td>{{ell.message}}</td> <td><a href="#"><i class="fa fa-eye" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-user-plus" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-bug" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></i></a></td> </tr> {% else %} <tr class="table-light"> <td class="row2">+</td> <td class="{{ rowcolors }}">{{ell.title}}</td> <td>{{ell.hostname}}</td> <td>{{ell.username}}</td> <td>{{ell.message}}</td> <td><a href="#"><i class="fa fa-eye" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-user-plus" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-bug" aria-hidden="true"></i></a> <a href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></i></a></td> </tr> {% endif %} {% endif %} {% endfor %} {% endfor %} </tbody> </table> At the moment, it turned out to select only the first element in the loop, and you need the first repeating one -
Get user's information from Google Sign Up using Django?
I have added the "Continue with Google" button in my HTML code and all of that works and after the user has gone through that process it sends a POST request to my backend with the variables "credential" and "g_csrf_token". I want to know how to handle this information and get the user's name, email, profile picture, etc. This is the HTML code that sends the request: <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="188921335755-m1v9q2v7lghon45rlp89qq2rm7f4ko9c.apps.googleusercontent.com" data-login_uri="http://localhost:8000/accounts/signup/continue-with-google/" data-auto_prompt="false"> </div> <div id="continueWithGoogleButton" class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="continue_with" data-shape="pill" data-logo_alignment="left" data-width="300"> </div> -
Heroku deploy Django application
I'm trying to launch my Django application with Heroku but when I execute the command "Heroku local" I get the following error .... Anyone can explain why? Before writing this post I tried to make various changes and read up on the official website but it didn't work. To run heroku in local I ran Heroku local in my main directory, with gunicorn everything was fine but apparently with heroku I'm doing something wrong. I've also created a Procfile with the following line inside of it: web: gunicorn social_site.wsgi where social_site is the name of the app. -
Django datetime returning negative value even though the date is not over
I have this issue with date time, I don't understand the datetime module and django dates either, what I am trying to achieve is get the difference days between a constant datetime saved in the database and current date. See, the problem is even though today is not over I am getting negative -1 day and the day is not over yet. from django.utils.timezone import now class ExamplModel(models.Model): due_date = models.DateTimeField() # model method def get_due_date(self): days_left = due_date - now() return days_left if due_date is today a couple of hours ago, example I get result like this -1 day, 18:54:04.590519 instead of 0 day, 18:54:04.590519 How can I solve this. -
Django : Change data when model become a choice field
I have a form where I ask people's hobbies. It was a Charfield in my form. I transformed this field with multiple CHOICES. For my old datas, I would like to update their values: for example if they had entered: "football", "skiing", it would have to change to 'sport'. abstract_models.py class ReferencesProfileBase(models.Model, UsernameNaturalKeyMixin): HOBBY_CHOICES = ('sport', ('sport')), ('music', ('music')), ('travel', ('travel')), ('other', ('other')), ) customer = models.OneToOneField( 'customers.CustomerProfile', verbose_name=_('Customer'), related_name='referencesprofile', on_delete=models.CASCADE, ) hobby = models.CharField( ('Hobby'), max_length=250, choices=HOBBY_CHOICES, blank=True, null=True, ) what I want on my old data done automatically : sport = ["skiing", "football"] if hobby in sport : hobby = "sport" else : hobby = "other" return hobby but I don't know in which function to write this code -
KeyError: 'skip_checks on heroku run python manage.py migrate_schemas
After deployment in Heroku a Django app, I run a command as follows: heroku python manage.py migrate_schemas and throws this error: File "/app/.heroku/python/lib/python3.10/site-packages/tenant_schemas/migration_executors/base.py", line 58, in run_migrations run_migrations(self.args, self.options, self.codename, public_schema_name) File "/app/.heroku/python/lib/python3.10/site-packages/tenant_schemas/migration_executors/base.py", line 31, in run_migrations MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 365, in execute if self.requires_system_checks and not options['skip_checks']: KeyError: 'skip_checks' Any idea of how fix this error? -
Django Form Post but doesn't display data
I'm working on a project but I'm kind of stuck on a problem. My Django post form doesn't have any bug but every time I submit a form, it redirects as it should but doesn't display anything. And I have 5 forms of the same type but it's only one of them that does it. Code Snippet Below View.py ########################## PRESCRIPTION ##################################################### def patients_list(request): context = {'patients_list': Prescription.objects.all()} return render(request, 'dashboard/patients_list.html', context) def patients_form(request, id=0): if request.method == 'GET': if id == 0: pform = PatientsForm() else: prescription = Prescription.objects.get(pk=id) pform = PatientsForm(instance=prescription) return render(request, 'dashboard/patients_form.html', {'pform': pform}) else: if id == 0: pform = PatientsForm(request.POST) else: prescription = Prescription.objects.get(pk=id) pform = PatientsForm(request.POST, instance=prescription) if pform.is_valid(): pform.save() return redirect('/list') urls.py ########################## PRESCRIPTION ##################################################### path('form', views.patients_form, name='patients_form'), path('list', views.patients_list, name='patients_list'), path('update_patient/<str:id>/', views.patients_form, name="update_patient"), path('patients_delete/<str:id>/', views.patients_delete, name="patients_delete"), ########################## END PRESCRIPTION ##################################################### patients_form.html <form action="" method="POST"> {% csrf_token %} <div class="form-group"> {{pform.first_name|as_crispy_field}} </div> <div class="form-group"> {{pform.last_name|as_crispy_field}} </div> <div class="form-group"> {{pform.CNI|as_crispy_field}} </div> <div class="form-group"> {{pform.gender|as_crispy_field}} </div> <div class="form-group"> {{pform.marital_status|as_crispy_field}} </div> <div class="form-group"> {{pform.telephone1|as_crispy_field}} </div> <div class="form-group"> {{pform.telephone2|as_crispy_field}} </div> <div class="form-group"> {{pform.town|as_crispy_field}} </div> <div class="form-group"> {{pform.address|as_crispy_field}} </div> <div class="form-group"> {{pform.occupation|as_crispy_field}} </div> <div class="form-group"> {{pform.status|as_crispy_field}} </div> <div class="row"> <div class="col md 6"> <button class="btn btn-success my-4" … -
Traverse m2m,filter and aggregate data in django
Currently, I'm developing a CRM system for collecting/aggregating data about female models I got 3 DB models that interact with each other: class User(AbstractBaseUser, PermissionsMixin): """ User class """ email = models.EmailField( max_length=128, unique=True, null=False, blank=False) is_active = models.BooleanField(default=True) staff_type = models.CharField( max_length=128, choices=STAFF_TYPES, null=False, blank=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now, editable=False) USERNAME_FIELD = ("email") objects = UserManager() def __str__(self): return f'{self.email} - {self.staff_type}' class OnlyFansModel(models.Model): """ Class(Model) storing data for OnlyFans models""" username = models.CharField( max_length=128, unique=True, null=False, blank=False) plan = models.IntegerField() # Filters experience = models.CharField( max_length=128, choices=EXPERIENCE_TYPE, blank=False, null=False, default=EXPERIENCE_TYPE[0]) type = models.CharField( max_length=128, choices=TYPES, blank=False, null=False ) teamlead = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="teamleads", default=1, blank=True, null=True,) client_manager = models.ForeignKey( User, on_delete=models.SET_NULL, related_name="clientmanagers", default=1, blank=True, null=True) marketer = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="marketers", default=1, blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.username}' class Record(models.Model): """ Storing data """ ofmodel = models.ForeignKey( OnlyFansModel, on_delete=models.CASCADE, related_name='records') fact = models.IntegerField(blank=False, null=False) fact_percentage = models.DecimalField( max_digits=8, decimal_places=2, blank=True, null=True) run_rate = models.DecimalField( max_digits=8, decimal_places=1, blank=True, null=True) run_rate_percentage = models.DecimalField( max_digits=8, decimal_places=2, blank=True, null=True) lfl_sales = models.DecimalField( max_digits=6, decimal_places=2, blank=True, null=True, default=100.0) average_sales_per_model = models.DecimalField( max_digits=9, decimal_places=2, blank=True, null=True) all_fans_start = models.IntegerField(blank=False, null=False) … -
working with multi language data (translations) in db using django models
I'm using Python 3.9 with Django 4.1 and I want to store data in my database in 3 languages, English, French and Hebrew. currently I work on addresses so for country, city and street i have columns name_en, name_fr and name_he. I have country, city and street tables, and also relation tables CountryCity that contains country id and city id and CountryCityStreet that contains countryCityId and streetId. i can get the current used language using translation.get_language() and i can take only the first 2 characters to get the desired result (en, fr or he). so I created a service function to get the first characters: def get_2l_lang(): lang = translation.get_language() return lang[0:lang.find("-")] and I created the models for that: class Country(models.Model): class Meta: verbose_name_plural = "Countries" name_en = models.CharField(unique=True, verbose_name="English Country Name", max_length=100) name_fr = models.CharField(unique=True, verbose_name="French Country Name", max_length=100) name_he = models.CharField(unique=True, verbose_name="Hebrew Country Name", max_length=100) def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class City(models.Model): class Meta: verbose_name_plural = "Cities" name_en = models.CharField(unique=True, verbose_name="English City Name", max_length=100) name_fr = models.CharField(unique=True, verbose_name="French City Name", max_length=100) name_he = models.CharField(unique=True, verbose_name="Hebrew City Name", max_length=100) def __str__(self): return getattr(self, 'name_' + get_2l_lang()) class Street(models.Model): name_en = models.CharField(unique=True, verbose_name="English Street Name", max_length=100) name_fr = …