Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django or NodeJS for long-term web and business project?
Good afternoon all, we are struggling to decide which way to go for a project and would like to have some insight from people who have been dealing with this. We have to invest in training/time for the two people who are working on our business and we would like to understand which way to go. The people Both have a good understanding of HTML, CSS, SASS and some JS One has some experience with PHP One has more experience with Python The Project Database driven website that will host and display hundreds of products (laboratory products which will need specific templates for each product Shopping chart for reagents and lower cost products A section with a knowledge base The website(s) will be multilingual, with different products for different countries Integrated CRM, connected to the products, stock management and shopping chart Potentially (desirable, but not necessary) an APP for the phone An application that will link all the components AI services and big data analytics (as a separate product) The timeline 2-3 years, potentially 4 for completion This is to move what we are doing manually at the moment (and what we are planning to do) to something that is … -
best way to handle websocket jwt authetication using django channels for backend and android kotlin?
I have learned how to make a simple chat app with Django channels and android with Kotlin. I'm using rest framework in Django. What is the best way to handle authentication in both platforms? I couldn't find anything useful in the internet. -
what is a 'no such table' error in Django for creating a register page?
I'm trying to create a registration page. I'm getting this error the views.py: def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: print("momooo!") user = User.objects.create_user(username, email, password) print(("more mooomoo")) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/register.html") the register.html page: {% extends "auctions/layout.html" %} {% block body %} <h2>Register</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email Address"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> … -
How do I get the value from the field in a one-to-one relationship tabularinline
How do I get the value from the field in a one-to-one relationship. The tables Ojbects and Object_Info are linked using TabularInline. And I want to get a value from a field by OneToOneField relationship. How to do it with signals. In this case I'm using post_save. I get an error. class Ojbects(models.Model): title = models.CharField(max_length=10) class ServerInfo(models.Model): data = models.TextField() object = models.OneToOneField(Ojbects, on_delete=models.CASCADE, related_name="data") @receiver(post_save, sender = Ojbects) def create(instance, sender, **kwargs): print(instance.data) -
Django structure with directories don't load views
I'm coming from the larvae on Django and I have a problem on this side and I can't say 100% of the documentation that I understand exactly the structure. Do I have to make a directory for each part of the application, for example? For example for the user a special directory, for the management of the application another one and so on? Or can I have a main application like I did acm and have in it a folder view with several views.py and import them in urls? Because I can't do that, I get an error. For example this is my structure structure This is the error AttributeError: module 'main.views' has no attribute 'pages_views' Url function from main from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', views.pages_views.index, name='index'), ] AttributeError: module 'main.views' has no attribute 'pages_views' And url acces from project_management (core app I think) from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls) ] -
How can upload word or pdf file in django
I am trying to upload word/pdf file but it's not working. My form submit successfully but file not store in document field. It show empty field and it also not show any error during submit the form, i don't know where is the issue and how can i fix the issue. I add the MEDIA URL in setting and also define the path in urls View.py class SaloonRegistration(TemplateView): template_name = 'saloonRegistration.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloon = SaloonRegister( saloon_name=self.request.POST.get('saloon_name'), owner_name=self.request.POST.get('owner_name'), address=self.request.POST.get('address'), contact_no=self.request.POST.get('contact_no'), document=self.request.POST.get('document') ) saloon.save() return redirect('menu') Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() document = models.FileField(upload_to='doc/') is_active = models.BooleanField(default=False) Template {% extends 'home.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="saloon_name">Saloon Name <input type="text" name="saloon_name" placeholder="Enter Your first name"> </label> <label for="owner_name">Owner Name <input type="text" name="owner_name" placeholder="Enter Your last_name"> </label> <label for="address">Address <input type="text" name="address" placeholder="Enter email address"> </label> <label for="contact_no">Contact No <input type="number" name="contact_no" placeholder="Enter your username"> </label> <label for="document"> upload Doc <input type="file" name="document" id="document"> </label> <button type="submit">Submit</button> </form> {% endblock%} -
django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint
I'm trying to get a session_key from my React app (front-end) where Django-rest-framework is used for Backend. But it shows server error. Views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) urls.py: path('addToCartForSession/<str:pk>/', views.addToCartForSession, name='addToCartForSession'), When I go to this url directly from browser search bar, it works fine. But if I call this function(addToCartForSession) from my React app, it shows server error like this: django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint DETAIL: Failing row contains (54, null, null) in React: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrftoken } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } So, How can I get a session_key from front-end with drf? -
request cart_obj in template tag filter Django
Is it possible to add a cart_obj request in a Django Template filter I currently have in my template tag: @register.filter def existing_product(product): return CartItem.objects.filter(item_id=product.id).exists() and in my template: {% if product|existing_product %} {% endif %} the only problem is that this filter only finds the item_id that is equal to the product.id , I want to be able to add an additional filter that looks for the item_id in the cart_obj. views.py cart_obj, new_obj = Cart.objects.new_or_get(request) basically my template tag would be something like: return CartItem.objects.filter(item_id=product.id, items_cart_id=cart_obj).exists() with the addition of filtering the 'items_cart_id', but I'm not sure how to do this and what to put in the template 'if' condition. Any ideas? Thanks -
How to call the value of a key in JavaScript?
I am learning Django. I have an app name quizes In the models.py section I have this: from django.db import models DIFFICULTY_CHOICES = ( (1, 'easy'), (2, 'intermediate'), (3, 'difficult') ) class Quiz(models.Model): difficulty = models.IntegerField(choices=DIFFICULTY_CHOICES) This is how views.py looks like: from django.shortcuts import render from .models import Quiz from django.views.generic import ListView class QuizListView(ListView): model = Quiz template_name = 'quizes/main.html' def quiz_view(request, pk): quiz = Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj': quiz}) Now in the main.html I have a button that calls these values and it looks like this: <button type="button" class="btn btn-primary modal-button" data-difficulty="{{obj.difficulty}}" data-bs-toggle="modal" data-bs-target="#quizStartModal"> {{obj.name}} </button> When the user clicks on the button, I would like to display the value of the key in difficulty. the key is fetched by the button using the data-difficulty method. In the JavaScript part, this is what I am doing: const modalBtns = [...document.getElementsByClassName("modal-button")] const modalBody = document.getElementById("modal-body-confirm") modalBtns.forEach(modalBtn=> modalBtn.addEventListener('click', ()=>{ const difficulty = modalBtn.getAttribute('data-difficulty') modalBody.innerHTML = ` <div> difficulty: <b>${difficulty} </div> ` So I am getting the output as 1 for easy, 2 for intermediate and so on. But I want to output the value of those keys instead of those keys themselves. How do I do that? -
Connect create-react-app to django backend without having to run build
I connected my react app that I made with create-react-app to django by passing it in as a template. I followed the steps shown here: https://studygyaan.com/django/django-react-setup-best-project-structure. This works but if I want to try out a full backend server by running manage.py runserver, I have to do npm run build on the frontend app all the time. Is there a way to get it so that I could maybe connect the development components to django instead of the build components? Running the build command always takes a bit of time. -
Django - Can you overwrite the form.as_p or form.as_table methods? Or create your own?
I was wondering if something like this would be possible. I like to display my forms in tables, but not the same as the out of the box .as_table method. I have so far been iterating over each field, and doing it myself. But now that I'm doing my own error displays as well (form.non_field_errors and field.errors), it is a ridiculous amount of code to copy and paste for each form. I just want to be able to do form.as_....., where I can just have it display my own custom way in html, and with my own custom error message styling. Can this be done. Thanks so much! -
Python Django TypeError: 'Module' object is not callable
I am trying to setup my database using dj_database however I am getting the error db_from_env = dj_database_url(conn_max_age=600) TypeError: 'module' object is not callable The code that the traceback is calling is db_from_env = dj_database_url(conn_max_age=600) DATABASE['default'].update(db_from_env) If you have any knowledge on why this would be happening the help would be appreciated. -
Store the uploaded .txt file with newlines in a variable Django
I wanted to store the content of an uploaded .txt file (with newlines) in a variable, so that I could call my other functions on that variable. But I can not find a way to achieve this. I tried all the methods, but it doesn't work Here is the simple code example: Template <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="txt"> <button type="submit" name="encode">Encode</button> </form> View from .algorithms.algo import encoder def encoder(request): context = {'encoded':''} if request.method == 'POST': text = request.FILES['txt'].read() encoded = encoder(text) context['encoded'] = encoded return render(request, 'template.html', context) Also, when I tried to output the file, it showed me some strange text instead of the actual content of the file. Please admins don't close this question, I've surfed all over the internet, but didn't find the answer for my question -
How to use If else in queryset in django
I need to use if else condition for Value1 in my queryset..I have found average for my records in the queryset..I need to apply condition like..If my Value1 is between 90 and 110 then I have to get message as "great" and if its below 90 it must print as "low" and if above 140 it must print as "high" I need to be print this output on my html file Models.py: from django.db import models from django.contrib.auth.models import User class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField() Value2 = models.IntegerField() urls.py: def average(request): userid = None if request.user.is_authenticated: userid = request.user.id print(userid) dataset = graphinput.objects.filter(user=userid) \ .values('Value1') a=dataset.aggregate(Sum('Value1')) b=dataset.aggregate(Avg('Value1')) print(a) print(b) return render(request, 'profile.html') -
how to i pass this to django views? for example the url will call generateGamesNumber(), the parameters of the second function come from a form
how to i pass this to django views? for example the url will call generateGamesNumber(), the parameters of the second function come from a form esse é o princípio do que quero def gerarNumerosJogos(): """ valores da lista A """ vetorA = [] """ Gerando números aleatórios no vetor A sem repetição """ x = 0 while True: numAleatorioA = randint(1, 25) if numAleatorioA not in vetorA: vetorA.append(numAleatorioA) x += 1 if x == 15: break vetorA = sorted(vetorA) return vetorA I validate vetorA and return True or False: def validandoParametros(jogoGerado,result,minImpar,maxImpar,minRep,maxRep,minPrimo,maxPrimo,minMold,maxMold, minFibo,maxFibo,minMult,maxMult): *** I have some more code here to validade *** return valida -
Django Form is not submitting and print invalid at console
I have a profile form when the user submits it not submitting but it shows an invalid form in the console Here is my code. But when the same code is rendered with nonstyle HTML for example render form like {{form.as_p}} then it works fine. forms.py class CompanyProfileForm(forms.ModelForm): class Meta: model = Company exclude = ['followers','address','user','create_at'] widgets ={ 'name':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'comp_email':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'comp_type':forms.EmailInput(attrs={'class': 'form-control rounded-input'}), 'about':forms.Textarea(attrs={'class': 'form-control rounded-input'}), 'website':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'fb_link':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'linkedin':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'contact':forms.TextInput(attrs={'class': 'form-control rounded-input'}), 'comp_type':forms.TextInput(attrs={'class': 'form-control rounded-input'}), } class CompanyAddressForm(forms.ModelForm): class Meta: model = CompanyAddress fields = '__all__' widgets = { 'country':forms.TextInput(attrs={'class':'form-control rounded-input'}), 'address':forms.TextInput(attrs={'class':'form-control rounded-input'}), 'city':forms.TextInput(attrs={'class':'form-control rounded-input'}), 'state':forms.TextInput(attrs={'class':'form-control rounded-input'}), } views.py class CompanyProfileView(LoginRequiredMixin,View): login_url = reverse_lazy('login') def get(self, request, ): company = get_object_or_404(Company,pk=request.user.id) profile_form = CompanyProfileForm(instance=company) address_form = CompanyAddressForm() context = { 'address_form':address_form, 'profile_form':profile_form, } return render(request,'company/companyForm.html', context) def post(self, request): company = get_object_or_404(Company,pk=request.user.id) profile_form = CompanyProfileForm(request.POST or None ,request.FILES or None, instance=company) address_form = CompanyAddressForm(request.POST or None) if address_form.is_valid() and profile_form.is_valid(): address_cd = address_form.cleaned_data address_instance = CompanyAddress( country=address_cd['country'], state=address_cd['state'], city=address_cd['city'], address=address_cd['address'] ) address_instance.save() try: company.address = address_instance company = profile_form.save() except db.DataError: address_instance.delete() company.delete() return redirect('core:company-dashboard') print('invalid') return render(request, 'company/companyForm.html',{'profile_form':profile_form, 'address_form':address_form}) profile.html <form action="" method='POST' enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> … -
How to redirect CBV login_required to a specific route?
I have a HomeView Class which I added a login_required, but I don't know how to redirect it with custom login page I made. Here are the urls.py and settings.py in my project: myblog\urls.py from django.contrib import admin from django.urls import path,include from .settings import DEBUG, STATIC_URL, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT from django.conf.urls.static import static # from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('myblog_app.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] # + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) if DEBUG: urlpatterns += static(STATIC_URL,document_root =STATIC_ROOT ) urlpatterns += static(MEDIA_URL,document_root = MEDIA_ROOT) myblog_app\urls.py from django.urls import path from django.contrib.auth.decorators import login_required from .views import HomeView,ArticleDetailView,AddPostView,UpdatePostView,DeletePostView,AddCategoryView,CategoryView,CategoryListView,LikeView,AddCommentView urlpatterns = [ path('', login_required(HomeView.as_view()),name='home'), path('article/<int:pk>', ArticleDetailView.as_view(),name='article-detail'), path('add_post/', AddPostView.as_view(),name='add_post'), path('article/<int:pk>/comment/', AddCommentView.as_view(),name='add_comment'), path('article/edit/<int:pk>', UpdatePostView.as_view(),name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(),name='delete_post'), path('add_category/', AddCategoryView.as_view(),name='add_category'), path('category/<str:cats>', CategoryView,name='category'), path('category-list', CategoryListView,name='category_list'), path('like/<int:pk>', LikeView,name='like_post'), ] members/urls.py from django.urls import path from .views import UserRegisterView,UserEditView,UserLoginView,PasswordsChangeView,ShowProfilePageView,EditProfilePageView from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/',UserLoginView, name='login'), path('register/',UserRegisterView.as_view(), name='register'), path('edit_profile/',UserEditView.as_view(), name='edit_profile'), # path('password/',auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')), path('password/',PasswordsChangeView.as_view(template_name='registration/change-password.html')), path('password_success/',views.password_success,name='password_success'), path('<int:pk>/profile/',ShowProfilePageView.as_view(),name='show_profile_page'), path('<int:pk>/edit_profile_page/',EditProfilePageView.as_view(),name='edit_profile_page'), ] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_REDIRECT_URL='home' LOGOUT_REDIRECT_URL='login' -
How to save static/class variables in Django
Since Django loads its code dynamically, I am currently facing the problem of not being able to use class variables. My intention: I wanted to run a few threads that repetitively do the same thing over and over again. However, the threads should only exist once. That's why I collected them in a dictionary. Problem: The dictionary is reset again and again, because Django constantly reloads code. The question now is: How can I solve this cleverly? This is the Wrapper module with thread & abstract parent class. If you want a spcecific task you have to inherit from here: class TaskThread(Thread): def __init__(self, delay_time: timedelta = None, repeat_time: timedelta = None, task: Callable = None, thread_name: str = None, daemon=None, *args, **kwargs): super().__init__(name=thread_name, daemon=daemon, args=args, kwargs=kwargs) self.sleep_time = delay_time if repeat_time is None: raise ValueError('No repeat interval given') else: self.repeat_time = repeat_time if task is None: raise ValueError('No task given') else: self.task = task self.next_execution: Optional[datetime.datetime] = None def run(self): if self.sleep_time: time.sleep(self.sleep_time.total_seconds()) del self.sleep_time self.execute_task() def execute_task(self): self.next_execution = self.__calculate_next_execution__() time.sleep(self.repeat_time.total_seconds()) self.task() self.execute_task() def get_next_execution(self) -> datetime.datetime: return self.next_execution def __calculate_next_execution__(self) -> datetime.datetime: current_time = timezone.now() return current_time + self.repeat_time REPEATING_TASKS: Dict[str, TaskThread] = dict() class RepeatingTasks(ABC): TIME_ZONE … -
Edit multiselect field?
So I have a ManyToMany field in my model and Django admin renders it as a multiselect field. It works fine and I have no issues — except that I can't Edit it after creating a record. I tried Del key, mouse right-click, nothing worked. Looks like I have to delete the record and create it again? This is the field I want to edit. I want to remove one or two of the above items. I'm on Windows. -
Django: Session_key generate new key every time the function is called
I'm using Django-rest-framework views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) if not request.session.exists(request.session.session_key): request.session.create() mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) When this function is called, it create a new key. and for new key, it create a new Cart. But every single user should have only one cart. So, How can I stop creating new session_key for a single user? but one session_key will be created if there is no session_key. how can i do that? also I want to add that: @api_view(['GET']) def addToCartForSession(request, pk): print(request.session.session_key) #>>> None return Response({'response':'ok'}) when I make this, It prints None. -
Querying a database and returning checkboxes for each result
My goal here is to implement the following behavior in the simplest, most future-proof, and most django-y way possible. Other people will have to use and modify this webapp in the future, though it's also somewhat of a learning project for me. Right now, it feels sort of hack-ey, and I'm trying to learn django, and produce something easy to use and modify if needed. Here's the behavior I currently have. The user queries a database and gets a list of words back. There's a special word (or series of them) called a lemma and some others that are called variants. The lemma is in a special sticky box at the top of the list. After the user selects the words they want, they can then do another search from this list of selected words. My question is: have I implemented this correctly? I've made no use of forms, mostly just HTML, and I'm concerned I'm not using django to its full potential. For example, I've looked into forms and FormSets but I'm not quite sure how to use them here, or if they will make my life any easier. I'm attaching the relevant parts of my code so you … -
Okta Authentication Django redirect
I am implementing OpenID with Okta, but I am experiencing some issues with the redirect. Basically I can see in the Okta admin page that the authorization was successful:okta log But the login won't redirect to the specified url. Here are the settings in okta admin for the application: Okta settings The login page with the widget: div id="okta-login-container"></div> <script type="text/javascript"> var oktaSignIn = new OktaSignIn({ baseUrl: '{{config.url}}', clientId: '{{config.clientId}}', redirectUri: '{{config.redirectUri}}', authParams: { issuer: '{{config.issuer}}', responseType: ['code'], scopes: "{{config.scope}}".split(" "), pkce: false, }, }); oktaSignIn.renderEl( {el: '#okta-login-container'}, function (res) { console.log(res); }) </script> My okta settings in the app: "REDIRECT_URI": "http://localhost:8000/callback", "LOGIN_REDIRECT_URL": "http://localhost:8000/profile", # default "CACHE_PREFIX": "okta", # default "CACHE_ALIAS": "default", # default "PUBLIC_NAMED_URLS": (), # default "PUBLIC_URLS": (), # default "USE_USERNAME": False, # default The project URLS: urlpatterns = [ path('admin/', admin.site.urls), path('', include(("okta_oauth2.urls", "okta_oauth2"), namespace="okta_oauth2")), path('', include("django.contrib.auth.urls")), path('', include('request.urls')), The app urls: urlpatterns = [ path('', views.login, name='login'), path('request_form/', views.request_form, name='request_form'), path('profile/', views.profile, name='profile'), The views: def login(request): return render(request,'okta_oauth2/login.html', {}) And my folder structure: folder structure This is what I get in the terminal when I log in: [06/Jun/2021 17:35:06] "GET /login/ HTTP/1.1" 200 2012 [06/Jun/2021 17:35:09] "GET /callback?code=aL7yGY48sTPR7n5fKtciUlJfIwRIsyhuB2ADFD1ruDA&state=oa4dsoLnayMWPZ02N20DxNABenXif8QASQXy4vvdoep9MbvaLFh5gIbaRPzdQdeU HTTP/1.1" 302 0 [06/Jun/2021 17:35:09] "GET /login/ … -
Can UUIDField be used as default_auto_field in Django 3.2.^?
I have been using UUIDField as my primary key in Django. My project has a hierarchy of models with inherited fields, and at the top, I have the following superclass: import uuid from django.db import models class HasIDMixin(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True, name='id') After updating to Django 3.2.4, I get the following warning: WARNINGS: app_base.MyProject: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the AppBaseConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Following the advice of the warning, I tried both the DEFAULT_AUTO_FIELD in settings.py and the default_auto_field in the app_config and I get the following error: ValueError: Primary key 'django.db.models.UUIDField' referred by DEFAULT_AUTO_FIELD must subclass AutoField. I have seen others approach this problem with a custom child class to both UUIDField and AutoField (https://code.djangoproject.com/ticket/32577) but no working solution has been posted. Is this currently possible in Django 3.2.^? If not should I find a different primary key solution or roll back? -
Weasyprint django - generates an empty PDF
Good afternoon, I have the following problem in my app: I am working on generating pdfs via WEASYPRINT for some of my views. My app is a search engine that aggregates external information, what I am looking for is: That the user makes a search and the results are shown. When he clicks on report, he can download a pdf with the search results. (via AJAX without having to reload the page). So far this works perfect using xhtml2pdf, but I want to change it to WEASYPRINT because it allows more flexibility in the design of the pdf. As I said there is an ajax function that sends the data to the pdf generation view, it receives them and generates a pdf with converting the html to pdf and sends a response that with a ".done()' function in javascript activates the download of the pdf. The problem is that this pdf is shown empty because there must be some decoding problem, or so I think. Views.py def ViewPDF(request, *args, **kwargs): response = request.POST.get('nombre', None) hits = request.POST.get('hits', None) response2 = request.POST.get('query1', None) info = {'searched': str(response2), 'customer': request.user.customer.name, 'type_of_search': '', 'lists_covered': 'OFAC', 'Date_of_search': str(request.POST.get('date', None)), 'hits': hits} if response is … -
Using select_related in django view increases query times
I thought of trying to use select_realted in Django view to boost the performance. And I compare the results before using select_realted and after using it. Although I see the reduction of significant number of queries, the time however rises. So I am not sure whether to use select_related in every view or not use them. I just want to know when to use them and when not to. My view is : Before: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer queryset = Product.objects.all() After: class ProductAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProductSerializer #queryset = Product.objects.all() queryset = Product.objects.select_related('merchant','brand','collection','sub_category') pagination_class = CustomPagination My models: class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? The images before and after the use of select_related. After: Here we can see that the number of queries are reduced to 124, but the time is increased to 227. So, should i be using select_related? When to use it or when not to use it??