Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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?? -
Django custom form validator won't raise an exception when validation fails
I have a regex set up in my form.py and when i validate the number in the forms it successfully fails and refreshes the form but wont raise a ValidationError or display a message. i have tried RegexField and that also won't raise an error as well, but it correctly fails, what am i doing wrong? here's the example of the view set up: from django.shortcuts import render, redirect from django.http import HttpResponse, Http404 from django.urls import reverse from django.template import loader from django.core.mail import send_mail, mail_admins from .forms import Register # Importing Models from .models import Users # Create your views here. # Create your views here. def register(request): if request.method == "POST": forms = Register(request.POST) if forms.is_valid(): f_name = forms.cleaned_data["first_name"] l_name = forms.cleaned_data["last_name"] em = forms.cleaned_data["email"] num = forms.cleaned_data["phone"] user = Users( first_name=f_name, last_name=l_name, email=em, phone=num ) user.save() # Saving session request.session['f_name'] = f_name # User Mailing subject = f'Welcome to JSG {f_name}' message = 'Testing' from_email = 'example@gmail.com' recipient_list = [em] user_mail = send_mail( subject, message, from_email, recipient_list, fail_silently = False, ) # Admin Mailing subject = f'New member has joined the family {f_name}' message = ( f"Name: {f_name} {l_name}\n" f"Email: {em}\n" f"Phone: {num}\n" ) admin_mail = … -
How to check if object in list in Django Views
I'm trying to check whether an id matches an element in a list inside a Django view. I have looped through a filtered model and have appended the item.id to a list called items , I can see in my terminal that the list is being printed, but my "if" condition is not working : if product_obj in items: print('will be removed') added = False I'm not sure what I'm doing wrong ? any ideas? views.py def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) cart_items = CartItem.objects.filter(items_cart_id=cart_obj) items = [] for item in cart_items: items.append(item.item.id) print(items) if product_obj in items: print('will be removed') added = False else: newitem = CartItem(item=product_obj, items_cart=cart_obj, quantity=1) newitem.save() added = True request.session['cart_items'] = cart_items.count() # return redirect(product_obj.get_absolute_url()) if request.is_ajax(): # Asynchronous JavaScript And XML / JSON print("Ajax request") json_data = { "added": added, "removed": not added, "cartItemCount": cart_items.count() } return JsonResponse(json_data, status=200) # HttpResponse # return JsonResponse({"message": "Error 400"}, status=400) # Django Rest Framework return redirect("cart:home") -
Convert django uuid type to list
I have variable of a= dec76304-9a31-4a04-8165-02a121b3c7fb of django type : <class 'uuid.UUID'> Want to convert the same to list as below format : ['dec76304-9a31-4a04-8165-02a121b3c7fb'] Tried with list(str(a)) which gives below output-> ['d', 'e', '0', '1', '0', '5', 'a', 'f', '-', '9', '0', '1', 'f', '-', '4', '1', '4', 'd', '-', '9', '2', '4', 'f', '-', 'e', '3', 'f', '2', '7', '3', '8', 'd', 'c', 'c', '5', '2'] -
I cant add new data to mysql, though i can manipulate existing(imported) data. Django-python
I am struggling for 5 days, cant make it work. My code works perfectly fine on local server, but wont work when i upload application. It just won't accept any new data i just face some weird redirections to homepaage with the url of the page i made submit. The existing(imported) data can be manipulated and changed, just no way to submit new data. {% extends "baza.html" %} {% block content %} {% load static %} {% load crispy_forms_tags %} <div class="container-login100" style="background-image: url('/static/images/pticica.jpg');"> <div class="wrap-login100"> <form method="POST" action="{% url 'Registracija' %}" enctype="multipart/form-data" class="login100-form">{% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"><img style="border-radius:100%;padding:5px;" src="/static/images/login.png"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Registruj se </span> {{form|crispy}} <button type="submit" class="btn btn-success">Registruj se</button></div> </form></div> {% endblock %} my views from django.shortcuts import render, redirect from .forme import RegisterForm def register(request): if request.method == "POST": form = RegisterForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("login") else: form=RegisterForm() return render(request,"register/register.html", {'form':form}) and global settings from django.utils.translation import ugettext_lazy as _ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/ # SECURITY WARNING: keep the secret … -
Django Form dropdown fill with values
I have a from with fields I created in Django models.py. One of the fields is: res_person_1 = models.TextField(verbose_name="Odgovorna osoba 1") HTML page is: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Prijavite nesukladnost</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Prijava</button> </div> </form> </div> When I inspect the HTML page, ID of object is 'id_res_person_1'. At the page load I run script to get from database all users, which should fill the 'res_person_1' field and that field should be dropdown. Script is: <script type="text/javascript"> var endpoint = '/call_jquery_korisnici/' var korisnik_ime_prezime = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ korisnik_ime_prezime = data.korisnik_ime_prezime console.log(korisnik_ime_prezime) }, error: function(error_data){ console.log("error") console.log(error_data) } }) </script> I don't know how to fill that field and how to make it dropdown. It doesn't work with: $("#id_res_person_1").html(korisnik_ime_prezime); document.getElementById('id_res_person_1').value = korisnik_ime_prezime; If I console output var korisnik_ime_prezime: (2) ["TestName1 TestLastname1", "TestName2 TestLastname1"] -
The current path, {% url 'post_new' %), didn’t match any of these
I'm trying to get an app running in django but I encounter this error: The current path, didn't match any of these, even though I could not figure which part of the code is problematic. Here is my code: views.py: from django.shortcuts import render from django.http [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/QKhGg.png ---------------------------------------------------------------------------------------- views.py from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from django.contrib.auth.decorators import login_required #function based from django.contrib.auth.mixins import LoginRequiredMixin #Class based from blog.models import Post,Comment from blog.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.views.generic import (TemplateView,ListView,DetailView, CreateView,UpdateView,DeleteView) # Create your views here. class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') # "__lte" means less than or equal to and "-" means order_by descending order class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class UpdatePostView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DeletePostView(LoginRequiredMixin,DeleteView): login_url = '/login/' success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') @login_required def post_publish(request,pk): post = get_object_or_404(Post, pk=pk) post.publish return redirect('post_detail', pk=pk) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post, pk=pk) if request.method … -
How to access ManyToMany field without loop inside template
I have the following models defined for my portfolio projects: class Technology(models.Model): title = models.CharField(max_length=10) def __str__(self): return self.title class Meta: verbose_name_plural = 'Technologies' class Project(models.Model): title = models.CharField(max_length=100) description = HTMLField() technology = models.ManyToManyField(Technology) image = models.ImageField(upload_to='projects/') def __str__(self): return self.title And I have this in my views.py: def index(request): projects = Project.objects.all() context = {'projects': projects} return render(request, 'homepage/index.html', context) And the following piece of HTML to display the projects: {% for project in projects %} <div class="col-lg-4 col-md-6 portfolio-item filter-django"> <div class="portfolio-wrap"> <img src="{% static 'homepage/img/portfolio/portfolio-1.jpg' %}" class="img-fluid"> <div class="portfolio-info"> <h4>{{ project.title }}</h4> <p>FIRST TECHNOLOGY GOES HERE</p> </div> </div> </div> {% endfor %} My challenge is the <p>...</p> tag because each project has multiple technologies, but I need to print the first one only so I can't have a for loop here. I have tried {{ project.technology.[0] }} but that gives me Could not parse the remainder: '[0]' from 'project.technology.[0]' Please assist. -
Can not create multiple instance of Model using Factory Boy and Faker
I am trying to craate multiple instance of django model using django-factory-boy and faker. But the I need to create instance in bulk (not single). But I can not make both attribute to be corresponding (code and name of currency). I have a django model as: class Currency(models.Model): """Currency model""" name = models.CharField(max_length=120, null=False, blank=False, unique=True) code = models.CharField(max_length=3, null=False, blank=False, unique=True) symbol = models.CharField(max_length=5, null=False, blank=False, default='$') def __str__(self) -> str: return self.code I have a factory import factory from apps.Payment.models import Transaction, Currency from faker import Faker fake = Faker() class CurrencyFactory(factory.django.DjangoModelFactory): class Meta: model = Currency # code and name get assigned when the class is called hence if we use # create_batch(n) we get all n object same # code, name = fake.currency() code = factory.LazyAttribute(lambda _: fake.currency()[0]) name = factory.LazyAttribute(lambda _: fake.currency()[1]) symbol = '$' The problem I am facing is code and name gets different value and not matching. See what faker returns. >>> from faker import Faker >>> fake = Faker() >>> fake.currency() ('JPY', 'Japanese yen') See currency name is not corresponding to currency code. Also I need to create at least 5 to 6 object using CurrencyFactory.create_batch(5). # mismatch in code and … -
Django TruncMonth to return Count Zero
models.py class Subjectcalculation(models.Model): name = models.CharField(max_length=200, blank=True) updated = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name views.py math = Subjectcalculation.objects.filter(name='Math').annotate(month=TruncMonth('updated')).values('month').annotate(count=Count('id')) How to turn Count ZERO if no objects is present in that Month ? -
what should I learn to create an (image upload=>perform image recognition) webpage?
I understand a bit of programming with python, how make simple image recognition models that runs locally on my machine, I know how to use React.js, mongoDB and create some toy web apps. my question is, what do I need to learn to make a webpage that upload an image and do some analysis in python and send back the result? I hope my question is clear. Flask? Django? Learn to do analysis in Javascript? where should the images be stored? What tech allows me to make a python server that receive and image, do analysis, send back an image? Anyway that's my question, my apology if I sound ignorant to you. -
Django: the server responded with a status of 403 (Forbidden) (fix the error please)
I successfully registered from React app(front-end) and saved the key (Got from server) in local storage. here is my code: signupHandler=()=>{ fetch('http://127.0.0.1:8000/api/rest-auth/registration/', { method: 'POST', headers:{ 'content-type':'application/json', }, body:JSON.stringify({ 'username':this.state.username, 'email': this.state.email, 'password1': this.state.pass1, 'password2': this.state.pass2 }) }) .then((response)=>{ response.json().then((result)=>{ if (result.key !== undefined){ localStorage.setItem('login', JSON.stringify({login: true,token:result.key})) this.setState({registered: true}) } }) }) } I made a method , which will do this.setState({addedToCart: true}), if the result = 'response':'ok'. here is the method: addToCart=()=>{ var id = this.props.id let store = JSON.parse(localStorage.getItem('login')) console.log(store.token);//successfully print the key var url = 'http://127.0.0.1:8000/addToCart/'+id+'/' fetch(url,{ method:'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } and in Django(views.py): @api_view(['GET']) @permission_classes((IsAuthenticated,)) def addToCart(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(user=request.user) mycart.product.add(product) return Response({'response':'ok'}) but it shows >>>the server responded with a status of 403 (Forbidden) I know Django is saying I'm un-authenticated. but why i'm un-authenticated? (where i send the token/key to the server). so, How can I get the response:ok? how can i make me authenticated? -
Python, django: all objects in form works fine except only one
On website page user select 'flight_date', 'flight_number', 'suburb', 'no_of_passenger' on the form and hit summit button. after that, views.py calculate the price with those information and send them back to webiste page (html). all objects appear on webpage as User selected but only 'price' does not appear. 'price_cal()' works fine (I did test it - simple function). I don't know what the problem is... no error message come out. only price does not appear. it says "None" Here are the codes at views.py from django.shortcuts import render, redirect from .area import suburbs def price_detail(request): if request.method == "POST": flight_date = request.POST.get('flight_date') flight_number = request.POST.get('flight_number') suburb = request.POST.get('suburb') no_of_passenger = request.POST.get('no_of_passenger') def price_cal(): if flight_number == 'Drop off To airport': return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) - 10 elif flight_number == 'Pickup from airport': return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) price_cal() price = price_cal() return render(request, 'basecamp/price_detail.html', {'flight_date': flight_date, 'flight_number': flight_number, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price}, ) else: return render(request, 'basecamp/price_detail.html', {}) I am now struggling with this matter for several days... please help me or any hint, much appreciated. -
How to deploy Docker project(Django,nginx,gunicorn) to Production environment
I'm currently developing an application using Django, Nginx, Gunicorn, Postgresql, and Docker. I've created a simple project that just displays a welcome page of Django. I can check the display and operation in the local server(0.0.0.0/), but I cannot check the display and operation if I start the project in the production environment(remote server)()... How could I solve this problem? Directory structure docker_django ├─Dockerfile ├─docker-compose.yml ├─requirements.txt ├─entrypoint.sh ├─docker_django │ │─django_project │ │ ├─settings.py │ │ ├─urls.py │ │ ├─wsgi.py │ │ ├─asgi.py │ │ └─__init__.py │ └─manage.py ├─nginx │ ├─Dockerfile │ └─default.conf └─.env Here are the codes: Dockerfile FROM python:3 RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./django_project /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] docker-compose.yml version: "3.7" services: db: image: postgres environment: - "POSTGRES_USER=postgres" - "POSTGRES_PASSWORD=postgres" django_gunicorn: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" depends_on: - db nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - django_gunicorn volumes: static: requirements.txt Django==3.0.8 gunicorn==20.0.4 psycopg2 entrypoint.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn django_project.wsgi:application --bind 0.0.0.0:8000 settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') ALLOWED_HOSTS = ['*'] ... … -
SQL join that happens in the view of Django Rest Framework
I just want to know what type of SQL join is happening in the following view. I read about types of SQL joins but I am not able to figure out what is happening here. class WishListItemsView(ListAPIView): permission_classes = [IsAuthenticated] serializer_class = WishListItemsCreateSerializer def get_queryset(self): user = self.request.user return WishListItems.objects.filter(owner=user) My models: class WishListItems(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE,blank=True) #wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) wish_variants = models.ForeignKey(Variants,on_delete=models.CASCADE, related_name='wishitems') I can see it in Django debug toolbar, but it is authenticated so I cant see the quries. -
mw_instance = middleware(adapted_handler) TypeError: __init__() takes 1 positional argument but 2 were given
I have upgraded python and django version. resolved all the conflicts but unable to get the cause of this error. old -> python 3.5, django 1.8 upgraded -> python 3.9 django 3.2 Any Idea why this error is for? Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/m.susmita/code/seldon-hercules/sp-hercules/opdashboard/wsgi.py", line 29, in <module> application = get_wsgi_application() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/Users/m.susmita/code/venv3_9_0/lib/python3.9/site-packages/django/core/handlers/base.py", line 58, in load_middleware mw_instance = …