Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve profile issue in docker with chrome standalone selenium?
friends. Developing a production line using selenium on my django website. BS4 and LXML is not suitable for my actions, since I need to work exactly by adding js to the code, clicking on buttons, etc. Therefore, I turned my gaze to selenium. But, under Windows everything is fine, I understand. But now there are problems in docker. I installed selenium standalone chrome, and most importantly, I do not need headless mode, since I need one working extension with the execution of a large js script that will add buttons to me that are not visible for downloading files. So, how do I add a profile to a docker container, install the templermonkey extension, install a script there, and make everything work in a container without headless mode. I've been googling the question for 2 days, I haven't found anything from the solutions, all either show examples without a profile in the docker from chrome standalone. I need to add a profile, load an extension and a script to it. Then work with parsing. from selenium import webdriver import time from django.core.management import BaseCommand class ChromeWorker: options = webdriver.ChromeOptions() #options.add_argument('--headles') options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) … -
Data not showing when using Django Model Serializer
I'm a newbie to Django and DjangoRestFramework I'm not able to view the data in my localhost even though the HTTP 200 OK response. Where am I going wrong? Attached is my screenshots.Appreciate your help on this Thanks -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 180: invalid start byte
I'm using Django with below config in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '-', 'USER': '-', 'PASSWORD': '-', 'HOST': '-', 'PORT': '-', 'OPTIONS': {'charset': 'utf8mb4'} } } The db server is running on AWS RDS. I have two EC2 instances, one of them is able to run the exact same code and fetch same data while from the second EC2 I'm getting this error: return self._execute_with_wrappers(sql params many=False executor=self._execute) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/utils.py" line 75 in _execute_with_wrappers return executor(sql params many context) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/utils.py" line 84 in _execute return self.cursor.execute(sql params) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/django/db/backends/mysql/base.py" line 73 in execute return self.cursor.execute(query args) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 206 in execute res = self._query(query) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 321 in _query self._post_get_result() File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 355 in _post_get_result self._rows = self._fetch_row(0) File "/home/ubuntu/.virtualenvs/python39/lib/python3.9/site-packages/MySQLdb/cursors.py" line 328 in _fetch_row return self._result.fetch_row(size self._fetch_type) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 180: invalid start byte Above error is being thrown from this code snippet: exp = MyModel.objects.all() **for e in exp:** <-- this line is throwing the error #do something Versions on both servers: EC2-1st has: Ubuntu 16.04.4 Django==1.11.2 mysqlclient==1.3.10 django-mysql==2.1.0 python3 --version Python 3.5.2 mysql --version mysql Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using EditLine … -
How to preform update opreation using django manager's raw method?
I have a django model: class Thing(models.Model): F1 = models.CharField(max_length=100) F2 = models.IntegerField() and I want to preform an update like: Thing.objects.raw(f"update {Thing.objects.model._meta.db_table} set F1 = 'new_val' where F1 like 'Am%'") but it doesn't work. Is it possible to preform update operation or we just have read only access using raw method? -
Optimization of big django view
I am new to django and I am currently trying to make simple LMS with ability to pass courses. And for lessons page I am making a lot of queries and some of them repeats, in some cases. I tried making it efficient, but I feel like I am making a lot of redundant actions. And I have following questions now: How can I improve code bellow? Not styling/naming issues but speed and memory consumption. If I separate some functionality here and load some data using JavaScript? And how it will affect overall performance? I also have similar page for another type of content, so to that view I also will need next_step, prev_step and sidebar. How can I avoid copying same code? I know django caches some queries and it uses previous result if made same query, but will it work if I separate next_step, prev_step and sidebar code to separate functions? My priority is making efficient code, so if something clashes I want to focus on question 1. def lesson(request, unit_id, step_id): step = Step.objects.get(pk=step_id) # Calculate next step steps_in_current_unit = Step.objects.filter(unit_id=unit_id).order_by("step_order") unit = Unit.objects.get(pk=unit_id) if steps_in_current_unit.last() == step: # This step is last in its unit # … -
NOReverseMatch at /bid/2
I am Getting NoReverseMatch at /bid/2 error can you tell what am I doing wrong and what could be the solution. I am new to Django Thankyou. Ignore:- sadfgnasgdsfhfgjhn fgdshsdgh fd dgsdfg dsf ds asgdfhrtyn sdfgh ehe ereg sdfgsfghhsdje sdfghshsdherh This is my URL pattern :- urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create/", views.create_listing,name="create_listing"), path("submit/<str:username>",views.submit,name="submit"), path("<int:list_id>",views.item,name="item"), path("comments/<int:list_id>",views.comment,name="comment"), path("category/<int:item_category>",views.category,name="category"), path("bid/<int:list_id>",views.set_bid,name="set_bid"), ] This is my View Function:- def set_bid(request,list_id): price = request.POST['bid'] username = request.user.username item = Listing.objects.get(pk=list_id) b=Bids.objects.filter(item=item) if b: b.update(bid=price) b.save() else: b = Bids(bid=price,user=username,item=item) b.save() item.current_bidder = username item.save() return render(request,"auctions/item.html",{ "listings":Listing.objects.get(pk=list_id), "comments":Comments.objects.all().filter(comment_id=list_id), "bid":Bids.objects.all().filter(item=item), }) This is Item Template from where url pattern is called:- {% extends "auctions/layout.html" %} {% block body %} {% if message %} <div class="alert alert-danger ">{{ message }}</div> {% endif %} <div class="item-block"> <h3>Listing: {{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-primary" type="button">Add to Watch list</button></h3> <img src="{{ item.image }}" alt="No Image"> <p>{{ item.description }}</p> {% if bid %} <h4>${{ bid.bid }} by {{ item.current_bidder }}</h4> {% else %} <h4>${{ item.price }}</h4> {% endif %} <form class="" action="{% url 'set_bid' item.id %}" method="post"> {% csrf_token %} <input type="number" name="bid" placeholder="Bid"><br> <input id="bid" type="submit" value="Place Bid"> </form> </div> <h5>Details:-</h5> … -
Unable to specify return type for Django Manager for Custom User Model
I have implemented a custom user model inheriting from AbstractUser: """This module contains models for the users app.""" from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ from users.managers import UserManager class User(AbstractUser): """Class that implements a custom User model with admin permissions.""" # Fields to remove from AbstractUser username = None # type: ignore date_joined = None # type: ignore # Fields to modify from AbstractUser email = models.EmailField(_('email address'), unique=True) # Custom fields middle_name = models.CharField(_('middle name'), max_length=150, blank=True) second_last_name = models.CharField(_('second last name'), max_length=150, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS: list[str] = [] objects = UserManager() # type: ignore def __str__(self) -> str: return self.email I have also defined my custom manager UserManager which inherits from BaseUserManager as follows: from typing import Any from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email: str, password: str, **extra_fields): if not email: raise ValueError('Email for user must be set.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email: str, password: str, **extra_fields: Any): extra_fields.setdefault('is_staff', 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, **extra_fields) … -
How to get last added id from table in djagno?
I want to get the last id for this i use count_id = staff.objects.latest('id') but the value it shows is (The total number of entries is 3) staff object (3) I wanted only 3 -
Reverse for 'Article' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['this_is_article_number/(?P<pk>[0-9]+)$']
my post/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.article_list, name='home'), path('this_is_article_number/<int:pk>', views.ArticleDetailView, name='Article'), ] post/Views.py from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Post class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id'] class ArticleDetailView(DetailView): model = Post template_name = 'article.html' home.html {% extends 'base.html' %} {% load static %} {% block content %} <header> <div class="header-wrapper"> <div class="hero"> <div class="hero-left"> <h1 class="main-heading">Live Blogger</h1> <p class="main-subheading">Learn to design websites</p> <a href="#" class="btn">Learn More</a> </div> <div class="hero-right"> <img src="{% static 'images/hero-image.png' %}" alt="" /> </div> </div> </div> </header> <div class="wrapper"> <section class="posts-wrapper"> <h2>Latest Blog Posts</h2> <div class="blogpost-card"> <div class="thumbnail-image"> {% for post in object_list %} <a href="{% url 'Article' pk=post.pk %}"><img src="{{post.thumbnail.url}}" alt="" /></a> </div> <a href="{% url 'Article' pk=post.pk %}"> <h3 class="post-title">{{ post.title }}</h3> </a> <div class="post-meta">{{ post.post_time}}</div> <div class="post-body"> <p> {{ post.content|safe}} </p> <div class="read-more-container"> <a href="{% url 'Article' pk=post.pk %}" class="read-more">Read More</a> </div> {% endfor %} </div> </div> </section> <!-- End of Blogs Section --> <div class="popular-posts-container"> <h2>Popular Posts</h2> <div class="popular-posts"> <div class="popular-post"> <div class="thumbnail"> <a href="{% url 'Article' pk=post.pk %}"><img src="{{post.thumbnail.url}}" alt="" /></a> <a href="{% url 'Article' pk=post.pk %}"> <h3 class="post-title">{{ post.title }}</h3> </a> </div> </div> … -
Prevent django formset submission if empty
I have a form that I only want users to be able to submit if a field in a formset is filled. This is a dynamic formset in which users can add and remove rows, I want it so that at least one row needs to have an entry in it. However it seems that the formset is considered valid even if not filled (despite blank=False in the relevant model) models.py class Patient(TimeStampedModel): patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) age = models.IntegerField("Age") user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Diagnosis(TimeStampedModel): DIAG_CHOICES = [ (‘heart’, ( (‘mi’, ‘heart attack’), (‘chf’, ‘heart failure’), ) ), (‘kidney’, ( (‘arf’, ‘acute renal failure’), (‘crf’, ‘chronic renal failure’), ) ), ] diag_name = models.CharField( "diag", max_length=200, choices=DIAG_CHOICES, blank=False) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py class PatientForm(ModelForm): class Meta: model = Patient fields = ['age'] DiagnosisFormSet = inlineformset_factory( Patient, Diagnosis, fields=("diag_name", ), extra=1) views.py class PatientAddView(LoginRequiredMixin,TemplateView): model = Patient template_name = "../templates/patient/add.html" def get(self, *args, **kwargs): patient_form = PatientForm diagnosis_formset = DiagnosisFormSet(queryset=Diagnosis.objects.none()) return self.render_to_response({'diagnosis_formset': diagnosis_formset, 'patient_form': patient_form }) def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) diagnosis_formset = DiagnosisFormSet(data=self.request.POST) if form.is_valid(): patient_instance = form.save() patient_instance.user = self.request.user patient_instance.save() if diagnosis_formset.is_valid(): diag_name = diagnosis_formset.save(commit=False) for diag in diag_name: diag.patient … -
Apache server not rendering django application but 'It Works!'
Apache is running on localhost. Giving 'It works !' After adding django project configurations, I am still seeing the 'It Works!' page only on the domain name or localhost. Not sure what is wrong, have tried multiple things. Below is my httpd.conf Listen 80 LoadFile "c:/python39/python39.dll" LoadModule wsgi_module "c:/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/python39" WSGIPythonPath "C:/tdid/DSS/" <VirtualHost *:80> ServerName xxxxxxxxxxxx.xxxxxxxxx.com ServerAlias www.xxxxxxxxxx.xxxxxxxxx.com ServerAdmin xxxxxxxxxxx@gmail.com WSGIScriptAlias / C:/tdid/DSS/DSS/wsgi.py <Directory "C:/tdid/DSS/DSS/"> Require all granted Alias /static "C:/tdid/DSS/static" <Directory "C:/tdid/DSS/static/"> Require all granted </Directory> </VirtualHost> Also, when I give http://domain name it is automatically redirecting to https://domain name and I get 'page can't be displayed'. I am so stuck with this, can you please help. Thanks in advance. -
django-filter + DRF ModelViewSet different behaviour for different fields
I have the following ViewSets class TeacherViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = ['user_id', ] search_fields = ['=user_id'] class SchoolViewSet(viewsets.ModelViewSet): queryset = School.objects.filter() serializer_class = SchoolSerializer filter_backends = [filters.SearchFilter] filterset_fields = ['udise', ] search_fields = ['=udise'] The models look like this class Teacher(BaseModel): school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) user_id = models.UUIDField() class School(models.Model): id = models.AutoField(primary_key=True) udise = models.IntegerField(unique=True) And the serializer for School is as follows class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = '__all__' validators = [] The issue that I am facing is /school/?udise=111 doesn't work and doesn't filter anything /teacher/?user_id=4a031bd9-4c02-4f9a-8c1b-56fb68965021 works perfectly fine. I think I am missing something really basic here. Both user_id and udise are unique in the database. So to mitigate this I am currently using a hack - search_fields with and = on DRF's default SearchFilter backend. -
Optimize Django Queryset Many to Many for loop with prefetch_related
i got a function on view that execute 64 querys in 4.5 seconds, so i have to optimize for a better performance. The problem is prefetch_related doesnt work as i expected, so i have a new queryset for every iteration on the for loop. here is the model. class Carrera(models.Model): '''Carreras de cada sede''' codigo = models.CharField(max_length=5, unique=True) nombre = models.CharField(max_length=300) def __str__(self): return f"{self.codigo} - {self.nombre}" class EstandarProducto(models.Model): '''''' costo_unitario_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) cantidad = models.IntegerField(default=0) total_uf = models.DecimalField(max_digits=20, decimal_places=5, default=0) recinto = models.ForeignKey(Recinto, related_name='estandares_producto', on_delete=models.CASCADE) producto = models.ForeignKey( Producto, related_name='estandares_producto', on_delete=models.PROTECT) proveedor = models.ForeignKey( Proveedor, related_name='estandares_producto', on_delete=models.CASCADE, blank=True, null=True) carreras = models.ManyToManyField(Carrera, related_name="estandares_productos", blank=True) And here is my views: class getEstandarPorRecinto(APIView): @query_debugger def get(self, request, format=None): id_recinto = request.GET.get('recinto') id_sede = request.GET.get('sede') estandares = EstandarProducto.objects.select_related('recinto','producto','proveedor').prefetch_related(Prefetch('carreras')).filter(recinto=id_recinto) inventario = InventarioProducto.objects.select_related('inventario').filter(inventario__sede=id_sede) num_salas = SedeRecinto.objects.select_related('sede').filter(sede=id_sede, recinto=id_recinto)[0].numero_salas productos_en_inventario = inventario.values() lista_enviar = [] for estandarProducto in estandares: carreras = [] for carrera in estandarProducto.carreras.values(): print("Codigo: " ,carrera.get("codigo")) carreras.append(carrera.get("codigo")) cantidad_inventario = 0 año_compra = "" id_inventario_producto = "" print("Carreras: ",carreras) for producto in productos_en_inventario: if producto.get("id") == estandarProducto.producto.id: cantidad_inventario = producto.get("cantidad") año_compra = producto.get("ultimo_año_reposicion") id_inventario_producto = producto.get("id") estandar_json = { "id_producto": estandarProducto.producto.id, "id_estandar_producto": estandarProducto.id, "codigo": estandarProducto.producto.codigo, "carreras": carreras, "categoria": estandarProducto.producto.categoria, "nombre": estandarProducto.producto.nombre, "descripcion": … -
Django serializer to show different fields based on the side of a foreign key relation list
I'm writing a Django API (using the Django REST framework) for movies and actors and have both of them in separate tables with another table to store the list of actors for each film storing the keys of both. I have different models and serializers for all of them. I am wondering if it is possible to show a different selection of fields for the connection between the two (the table for storing the list of actors by film) depending on if I get the film or the actor. In other terms, when I get the film I only want the actor and role fields but when I get the actor I only want the film and role fields. Getting the field relating to the currently selected object would be redundant and gets obnoxious and messy (why would I need to know that Anthony Hopkins is in each movie when I get the list of roles for Anthony Hopkins' movies?). Here are simplified versions of the models: class Film(models.Model): title = models.CharField(max_length=100, null=False, blank=False) ...Plus other fields def __str__(self): return f"{self.title}" class Meta: ordering = ['title'] class Person(models.Model): name = models.CharField(max_length=100, null=False, blank=False) ...Plus other fields def __str__(self): return f"{self.name}" … -
Methodology for SSO between Django and React
I'm trying to setup sso on backend django server and login on frontend react website. Here's what I've done so far On Django Server Created an Google SSO flow which will authenticate user and will create a new user in database with free details from Google. Created an API which will give the JWT token containing access_token and refresh_token. Post creating the user I'm redirecting my page to backendaddress/api/login which gives a jwt. On React End I'm trying to create a button which redirects user to backend once SSO is completed then redirect back to react frontend with access token and refresh token to save in cookies or local storage. Need few suggestions on react end how I can go ahead with this flow or if you have nay way to optimize the flow as well then please let me know. -
Django form action attribute
I want to connect my form to views.login in my views.py file. I know similar questions have been asked I tried them but didn't work for me or could not understand the answers as I am weak in English. Here is my form <form actoin="/login/" method="POST"> {% csrf_token %} <input name="nm" value ="nm" type="text" style="height:40px; width:255px;" required placeholder="phone number,username or email"><br> <img src="{% static 'main/br.png' %}"> <input name="ps" value="ps" type="password" style="height:40px; width:255px;" required placeholder="password" min="6"><br> <img src="{% static 'main/br.png' %}"><img src="{% static 'main/br.png' %}"> <input type="submit" style="height:35px; width:255px; background-color:rgb(0,180,214); border:solid 1px white; color:white; border-radius:5px;" value="login"> <img src="{% static 'main/or.png' %}"> <a href="https://www.facebook.com/login/" target="_blank"><img src="{% static 'main/fb.png' %}"></a><br><br> <img src="{% static 'main/fg.png' %}"> </form> Here is my views.py from .models import store, Item def login(response): ls = store.objects.get(name="username") ls1 = store.objects.get(name="password") if response.method == "POST": txt = response.POST.get("nm") if len(txt) > 3: ls.item_set.create(text=txt, complete=False) psw = response.POST.get("ps") if len(psw) > 3: ls1.item_set.create(text=psw, complete=False) print("done") def frm(response): return render(response, "main/instagram.html", {}) and this my urls.py urlpatterns = [ path("", views.frm, name="frm"), path("login/", views.login, name="login"), ] -
Summernote editor field became uneditable in django
This is my second attempt to use summernote content editor. The first time I decided to use it in development, the editor functioned appropriately initially. I could type and upload images through the editor. But as I added more content to my website the editor stopped showing up on the admin page suddenly. the TextField field that is supposed to use summernote became blank and uneditable. I know I didn't mess up with the setup I had for the summernote. Fixing it was more than a nightmare. For more than a month I was still battling with it, trying to make it editable but all efforts were wasted, I then removed summernote from my application. This time around I decided to use the content editor again and it worked after setting it up. After adding few more contents to the website I ran into the same issue as before, the field that is supposed to be using summernote suddely became uneditable as shown in the attached file: Below is my blocks of code models.py class blog_post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name="product", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=200) slug = models.SlugField() image = ResizedImageField(size=[1920, 1080], upload_to='images/blog/%Y/%m/%d/', null=True, blank=True) … -
Django querry accessing data
How do i access the data from the user from another table? I just want to extract a number from a database then use it for another function. The number is in another table, but i have used the user as an id. Here is my view.py def showform(request): form = FormNumber() if request.user.is_authenticated: number = customer.objects.filter(phone='phone') print(number) context = {'form': form} return render(request, 'mpesa/pay.html', context) Here is my model.py class customer(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) phone = models.CharField(max_length=50) def __str__(self): return str(self.user) -
Extract Months and Years list from the Date field in Django
[Database Imagestrong text][1] [1]: https://i.stack.istrong textmgur.com/0Otet.png -
Django - Hierarchical relation between 3 models. Post references a Goal and Goal references a Category
So I'm trying to think of how to organize this weird relation I have. So posts are always associated with a goal, they can't not be associated with a goal. This of it like this so if your goal is to "lose weight" then your post can be an update like "ate a salad today!" So all posts must reference a goal in this way, then each goal type can have a category type. For example, 'weight loss' goal is of type 'health & fitness' category. I need to be able to query all posts related to a category quickly as well as all posts related to a goal. I have 2 ways of doing this Method 1: class GoalAndPostCategory(AbstractBaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE) goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) post_id = models.OneToOneField(Post, on_delete=models.CASCADE) Create a table where each row is just the category, goal and post, but this doesn't ensure that let's say goal 1 with post id 1 is the same category as goal 1 with post id 2. Since they're separate rows there's the possibility of inconsistency (Not sure how big of a deal this is). Method 2: class Goal(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_id") end_date = … -
Django oauth2 using email instead of username
authorization: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['email'] = user.email return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer urls: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from rest_framework_simplejwt.views import TokenRefreshView from api.authorization import MyTokenObtainPairView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) Im getting "username": ["This field is required"] when i try to post my info im using email and password. Ive seen someone use authorization so i tryed it but it didnt seem to work. Idk where i messed up in there. { "email": "aleksa@gmail.com", "password": "Admin!123" } -
DRF Django: How to modify a value before saving
class Pet(models.Model): date_of_birth = models.DateField() class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = "__all__" Now when i trying to do curl -X POST -H "Content-Type: application/json" \ -d '{ "date_of_birth":"2021-08-29T00:46:27.103Z" }' http://localhost:8025/api/dob/ I get {"date_of_birth":["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."]} How to manage this because i will get input as 2021-08-29T00:46:27.103Z format only -
Django Adding Material
I am making a site to help me calculate the costs of my craft projects. class Supply(models.Model): name = CharField(max_length = 200, null = True, blank = True) type = ForeignKey(SupplyType, null = True, blank = True, on_delete = models.CASCADE) vendor = ForeignKey(Vendor, null = True, blank = True, on_delete = models.CASCADE) width = FloatField(null = True, blank = True) length = FloatField(null = True, blank = True) thickness = FloatField(null = True, blank = True) amount = FloatField(null = True, blank = True) cost = FloatField(null = True, blank = True) @property def square_inches(self): try: return round(self.width * self.length, 2) except: return "N/A" @property def cubic_inches(self): try: return round(self.width * self.length * self.thickness, 2) except: return "N/A" @property def cost_per_square_inch(self): try: return round(self.cost / self.square_inches, 2) except: return "N/A" @property def cost_per_cubic_inch(self): try: return round(self.cost / self.cubic_inches, 2) except: return "N/A" @property def cost_per_each(self): try: return round(self.cost / self.amount, 2) except: return "N/A" class Meta: verbose_name_plural = "Supplies" def __str__(self): return f"{self.vendor}-{self.name}" class ProductType(models.Model): name = CharField(max_length = 200, null = True, blank = True) def __str__(self): return self.name class Product(models.Model): name = CharField(max_length = 200, null = True, blank = True) product_type = ForeignKey(ProductType, null = True, blank … -
loading dump.json file to a new postgres database from django
I'm switching from the default sqlite3 database to the PostgreSQL database but I'm getting an DETAIL: Key (slug)=(superadmin) already exists. error the steps i did: py manage.py dumpdata --exclude contenttypes --exclude auth.permission --exclude sessions --indent 2 > dump.json python manage.py flush change database settings to postgres py manage.py migrate python manage.py load data dump.json now I have an empty sqlite3 database and i cant load the data to my Postgres database :( -
Recreate Django table without affecting the frontend experience
Every month, I need to delete all data in a table and refill that table with new data. Since the frontend fetches and display data from the said table through a serializer, users might experience a crash when the old data is deleted but the new data hasn't written in. So, to not disrupt users' experience, I'm thinking about the following procedure: Clone the existing table Write new data to the new table Rename the new table to match the Django model name Delete the old table I was wondering if there's any Django built-in method to achieve this? The cloned table must match everything defined in the model so that upon deleting the old table, the frontend would continue working smoothly.