Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access and print 2d array in template in Django?
I am new to django. I am trying to build a soduku solver in django. When the user inputs the soduku board, I am storing the board in a 9x9 2D list. After the user presses submit I want to print the solved 2D list on the site in a table. Basically I want to access the list elements like arr[1][2] but django throws an error Could not parse the remainder: '[0][1]' from 'arr[0][1]' I know I can access elements by arr.1 but can this be used for a 2d list? -
i am getting error while importing _frozen_importlib
I have created a django app and in init.py while importing _frozen_importlib i got this error i have tried changing version of python but not worked currently my python version is 3.9 -
Auto resend Activation email in Djoser
I'm using djoser with unique email addresses and I want to be able to resend activation email if user try to login with correct user and pass and account is not already active or not receive activation email class CustomTokenObtainPairView(TokenViewBase): """ Takes a set of user credentials and returns an access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer_class = CustomTokenCreateSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.get_user(is_active=False) if user and not user.is_active: signals.user_activated.send( sender=self.__class__, user=self.user, request=self.request ) return Response(serializer.validated_data, status=status.HTTP_200_OK) Any advice would be welcome. -
Django DRF image field does not accept null values
Django DRF image field does not accept null values. My model consists of image = models.ImageField(upload_to='uploads/', blank=True, null=True) If I upload a file there's no problem. But, if I leave it blank it gives the following error: The submitted data was not a file. Check the encoding type on the form. I want to make the image field optional So I set null=True and blank=True. But this does not seem to work. -
How to use Django custom user tables are not extended user model?
custom use model class CustomUser(models.Model): account = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255) password = models.CharField(max_length=255) mobile = models.CharField(max_length=255, unique=True) email = models.CharField(max_length=255, unique=True) settings.py AUTH_USER_MODEL = 'user.CustomUser' How can I use the custom model to complete the functions of registration and login, can you give me some advice or references? Thanks -
TypeError: Field 'amount' expected a number but got datetime.datetime(2022, 3, 27, 10, 46, 51, 801087, tzinfo=datetime.timezone.utc)
I think I did something wrong and I need to delete it. but i can't fix it. How can I do it? I migrate and I get this error File "C:\Users\HP\Desktop\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value raise e.__class__( TypeError: Field 'amount' expected a number but got datetime.datetime(2022, 3, 27, 10, 46, 51, 801087, tzinfo=datetime.timezone.utc). (venv) C:\Users\HP\Desktop\markon> models.py class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) images = models.ImageField(upload_to='product/%Y/%m/%d/') detail = models.TextField() keywords = models.CharField(max_length=50) description = models.CharField(max_length=100) price = models.FloatField() sale = models.FloatField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) available = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Django Add Model Field Dynamically
I saw one application is using the same technique like user can add new field to a existing model. Suppose I have order form like the picture I Have attached below. It has some field for order creating. Now if user want then he can create another field for the order form and can set the fieldtype like email or datatime or text and then make it required or not to submit the form. How they do this using django? Which procedure to follow If I am able to pass the data dynamically how can sync the db without migrate command?? I don't know any good way help me if you can kindly. check the pictures -
How to get value in Django without POST or GET SIMILAR to FLASK request.args.get
how to get request.args.get in Django without changing url.py and no passing an argument/variable through def index(request, NO__EXTRA_VARIABLE_HERE) it is possible to get value without POST or GET form? What I can use to get this value in Django? I tried: request.GET but then I get WSGI Error or Exception Value: Reverse for 'index' with keyword arguments '{'currency_type': 'usa'}' not found. 1 pattern(s) tried: ['\\Z'] <a href="{% url 'index' currency_type=item.currency_type %}" class="btn btn-outline-primary {{item.active}}" role="button">{{item.display_text}}</a> FLASK CODE index.html in flask app <div class="card-footer text-center"> <a class="btn btn-primary" href="{{ url_for('movie_details', movie_id=movie.id) }}">Show more</a> </div> @app.route('/') def homepage(): selected_list = request.args.get('list_type', "popular") buttons = [ {"list_type": "now_playing", "active": "", "display_text": "now playing"}, {"list_type": "popular", "active": "", "display_text": "popular"}, {"list_type": "upcoming", "active": "", "display_text": "upcoming"}, {"list_type": "top_rated", "active": "", "display_text": "top rated"}, {"list_type": "favorites", "active": "", "display_text": "favorites"}, ] if selected_list not in ["now_playing", "upcoming", "top_rated","favorites"]: selected_list = "popular""" for button in buttons: if button['list_type'] == selected_list: button['active'] = 'active' if selected_list =="favorites": favorite_list = show_favorite() list_of_favorites = [get_single_movie(i) for i in favorite_list] if not favorite_list: flash("You dont have favorites movies", "alert-danger") return redirect(url_for("homepage")) return render_template("homepage.html",current_list=selected_list,buttons=buttons, list_of_favorites=list_of_favorites) else: movies = tmdb_client.get_movies(how_many=8, list_type=selected_list) return render_template("homepage.html",current_list=selected_list,buttons=buttons, movies=movies) What I tried to do in Django: def … -
Django 4.x Djongo MongoDb Support
i installed djongo requirements and django 4.x. Upgraded pip before install packeges in settings.py i used this connection string. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '<DB>', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': '<Host>', }, } } When i try to runserver having an issue. django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Packeges installed but why dont work? -
Key (email)=(macmusonda@gmail.com) already exists error in django
I am trying to register new users in my django ecommerce webapplication. I am using custombased model. But whenever i submit the form, my database shows that the user has been saved but then this error "duplicate key value violates unique constraint "account_account_email_key" DETAIL: Key (email)=(macmusonda@gmail.com) already exists." still comes up.The user can even login..How do i get rid of this error?? My views.py import email from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from account.forms import RegistrationForm from django.contrib import messages from .models import Account def registration(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid(): form.save() first_name = request.POST['first_name'] other_names = request.POST['other_names'] email = request.POST['email'] username = request.POST['username'] raw_password = request.POST['password1'] phonenumber = request.POST.get('phonenumber') Address_1 = request.POST['Address_1'] Address_2 = request.POST['Address_2'] user = Account.objects.create_user(first_name=first_name, other_names=other_names, email=email, username=username, password=raw_password, phonenumber=phonenumber, Address_1=Address_1, Address_2=Address_2) user.save() messages.success(request, ('Your account was successfully created!')) login(request, user) return redirect('home') else: messages.error(request, ('Invalid input.')) else: form = RegistrationForm() return render(request, 'account/register.html', {'form': form}) def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) try: user = Account.objects.get(username=username) except: messages.error(request, 'username does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: … -
How would I best handle two modelforms in a single submit/view flow with a FK relation?
I have the below two models # models.py class Applicant(models.Model): """ A table to store all applicants, relates 1-n to an offer """ name = models.CharField(max_length=50) job = models.CharField(max_length=50) start = models.DateField(null=True, blank=True) def __str__(self): return f'{self.name} applying for {self.job} starting {self.start}' class Offer(models.Model): """ A table to store created offers """ # Relations applicant = models.ForeignKey(Applicant, on_delete=models.CASCADE) # Self monthly_raise = models.FloatField() months = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(60)]) start_salary = models.FloatField() In my template I render all fields except for start (which I don't render at all) in the same <form></form> wrapper. Now in my view I want to create new instances for each of the modelforms but only if both are valid. This is what I have which throws NOT NULL constraint failed: planner_offer.applicant_id def render_dashboard_planner(request): site = 'planner' if request.method == 'GET': applicant_form = ApplicantForm() offer_form = OfferForm() context = { 'applicant_form': applicant_form, 'offer_form': offer_form, 'site': site } return render(request, "dashboard/dashboard_planner.html", context) else: # Process the created Offer applicant_form = ApplicantForm() offer_form = OfferForm() form_applicant = ApplicantForm(request.POST) form_offer = OfferForm(request.POST) if form_applicant.is_valid() and form_offer.is_valid(): form_applicant.save(commit=True) form_offer.save(commit=True) context = { 'site': site, 'offer_form': offer_form, 'applicant_form': applicant_form, } return render(request, "dashboard/dashboard_planner.html", context) How would I fix the relation issue and is … -
How to Get Text From Image in Django Web Application using tesseract?
i am building a django web application to extract text from images. i wanna use tesseract for it. but tesseract python code work normally in windows pc and not work in django web application. this is the error when i run python code using html click button tesseract-ocr/tesseract.exe is not installed or it's not in your path. this is the my python code for tesseract in django web app def text1(): global img import pytesseract as tess tess.pytesseract.tesseract_cmd = r'Tesseract-OCR\\tesseract.exe' from PIL import Image def program(): img = Image.open("./static/img/figure-65.png") text = tess.image_to_string(img) print(text) program() text1 function call by html click button and it correctly set to views.py and urls.py This image shows where the tesseract python code and tesseract.exe In imageToText.py have the python code. You can see Tesseract-OCR Folder, that's where **tesseract.exe** have. urls.py of web app from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('openC', views.openC, name="openC"), path('text1', views.text2, name="text1"), ] urls.py of main web project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from img2text.settings import MEDIA_ROOT urlpatterns = [ path('admin/', admin.site.urls), path('', include("imgtext.urls")) ]+ static(settings.MEDIA_URL, document_root=MEDIA_ROOT) views.py from django.shortcuts import render,redirect … -
What plugins in PYCHARM should you add for DJANGO?
I want to use PYCHARM for DJANGO and have seen in VS CODE plugins for the visibility of the code as: https://marketplace.visualstudio.com/items?itemName=batisteo.vscode-django Django - Visual Studio Marketplace Extension for Visual Studio Code - Beautiful syntax and scoped snippets for perfectionists with deadlines do you know which plugins I should add? thank you!! -
Django Rest Framework Allow a request to set a foreign key Field in CreateAPIView
A thread belongs to a board. So I would like the ThreadList view to accept a POST request with the foreign key board. What I have attempted results in an error. AssertionError: Relational field must provide a queryset argument, override get_queryset, or set read_only=True serializers.py class ThreadSerializer(serializers.ModelSerializer): post = PostSerializer(many=True, read_only=True) # board = serializers.ReadOnlyField(source='board.id') board = serializers.PrimaryKeyRelatedField(source='board.id') class Meta: model = Thread fields = ['id', 'title', 'post', 'board'] views.py class ThreadList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(thread_admin=self.request.user) queryset = Thread.objects.all() serializer_class = ThreadSerializer models.py class Board(models.Model): name = models.CharField(max_length=25, unique=True) created = models.DateTimeField(auto_now_add=True) board_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='board_admin') board_moderator = models.ManyToManyField(User, related_name='board_moderator') class Meta: ordering = ['created'] class Thread(models.Model): title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) thread_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='thread') board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="thread") class Meta: ordering = ['created'] -
AttributeError: 'WSGIRequest' object has no attribute 'query_params'
I'm trying to pull data from the site on the backend side everything will work: link from where I pull all the data https://swapi.dev/api/people count = {'count': 0, "next_page": 1, 'dates': [],} starwars = [count, ] # class StarView(APIView): # def get(self, request): # page = request.query_params.get('page', 1) # if starwars[0]['next_page'] == int(page): # url = f'https://swapi.dev/api/people/?page={page}' # response = requests.get(url).json() # starwars.append(response['results']) # starwars[0]['count'] += 10 # starwars[0]['next_page'] += 1 # starwars[0]['dates'].append(datetime.today()) # with open('story.csv', 'w') as file: # file.write(str(starwars[0])) # for i in range(1, len(starwars)): # for j in starwars[i]: # file.write('\n') # file.write(str(j)) # return Response(starwars, status=status.HTTP_200_OK) # return Response({"error": "Enter valid page"}) But as soon as I decided to create a template def index ..... for the place of this code, I get this error how to fix it (AttributeError: 'WSGIRequest' object has no attribute 'query_params') def index(request): if request.method == "GET": page = request.query_params.get('page', 1) if starwars[0]['next_page'] == int(page): url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() starwars.append(response['results']) starwars[0]['count'] += 10 starwars[0]['next_page'] += 1 starwars[0]['dates'].append(datetime.today()) with open('story.csv', 'w') as file: file.write(str(starwars[0])) for i in range(1, len(starwars)): for j in starwars[i]: file.write('\n') file.write(str(j)) return render(request,('index.html')) return Response({"error": "Enter valid page"}) What am I even trying to do? I … -
Fetched Json data from API is undefined
I m trying to populate a detail product page with data fetched from my API using useEfect() and useState() hooks in ReactJS, but everytime when i want to print into the console the object fetched it gives me a message with undefined, please help me . API model: from django.db import models class Product(models.Model): id = models.IntegerField(null=False, default=0, primary_key=True) product_name = models.CharField(max_length=60, null=False, default='no name') category = models.CharField(max_length=60, null=False, default='misc_product') author = models.CharField(max_length=60, null=False, default='anonim') collection = models.CharField(max_length=60, null=False, default='anonim') family = models.CharField(max_length=60, null=False, default='anonim') image_path = models.CharField(max_length=160, null=False, default='') likes_no = models.IntegerField(null=False, default=0) price = models.FloatField(null=False, default=0.00) def __str__(self): return self.product_name` API Serializer from rest_framework import serializers from .models import Product class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ( 'id', 'product_name', 'category', 'author', 'collection', 'family', 'image_path', 'likes_no', 'price', ) API Views from rest_framework import viewsets from rest_framework.views import APIView from .serializers import ProductSerializer from .models import Product from rest_framework.response import Response from rest_framework import status class ProductViewSet(APIView): queryset = Product.objects.all() serializer_class = ProductSerializer @classmethod def get_extra_actions(cls): return [] def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) def get(self, request, id=None): if id: item … -
Django production with Apache in Ubuntu not show image
I want to config my django project in Ubuntu server which use Apache but it not show image. I edit file settings.py like this. settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'static','media') I show image in html file like this. index.html {% load static %} {% block content %} <img src="{% static '/media/images/logo.png' %}"> {% endblock %} I set apache file in path /etc/apache2/sites-available/000-default.conf like this. <VirtualHost *:80> ServerName myweb.com DocumentRoot /home/user/myproject_dir/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/user/myproject_dir/myproject/static <Directory /home/user/myproject_dir/myproject/static> Require all granted </Directory> <Directory /home/user/myproject_dir/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject_dir python-path=/home/user/myproject_dir/myproject python-home=/home/user/myproject_dir/myproject_env WSGIProcessGroup myproject_dir WSGIScriptAlias / /home/user/myproject_dir/myproject/myproject/wsgi.py </VirtualHost> I upload image to path like this. /home/user/myproject_dir/myproject/static/media/images/logo.png I use command collectstatic and restart apache service but it not show image in my website. How to fix it? -
how can i create a table entry in django views
I want to make a system of likes on the site, and I need to create an entry in the table on the button. When a person clicks on like, the table writes row 1 and when dislike 0 views.py def forum(requset): model = Quetions.objects.all() answer = Answer.objects.all() count = Answer.objects.all().count() count_answer = Quetions.objects.all().count() paginator = Paginator(model, 1) # Show 25 contacts per page. page_number = requset.GET.get('page') question_id = requset.GET.get('id',False) page_obj = paginator.get_page(page_number) requestanswer = requset.GET.get('id',False) like_disli = like.objects.filter(like_dislike = "1").count() dislike = like.objects.filter(like_dislike = "0").count() createlike = objects = { 'model': page_obj, 'answer':answer, 'count':count, 'count_question':count_answer, 'page_obj':page_obj, 'question':question_id, 'id':model, 'request':requestanswer, 'like':like_disli, 'dislike':dislike, 'createlike':createlike, } return render(requset,'forum.html',objects) forum.html <span> <i class="fas fa-thumbs-up" style="color: blue;margin-right: 5px;" onclick="incrementClick()"></i>{{like}}<i class="fas fa-thumbs-down" style="color: red;margin-right: 5px;margin-left: 10px;" onclick="dislikeclick()"></i>{{dislike}} </span> {% block js %} <script> var a = "{{createlike}}" function incrementClick() { a } function dislikeclick() { dislikedisplay(++dislikecounter); } function updateDisplay(val) { document.getElementById("counter-label").innerHTML = val; } function dislikedisplay(val){ document.getElementById("counter").innerHTML = val } </script> {% endblock js %} tell me how to do it??? -
How can I enable directions on embeded google map in my web app
I am new in django and I am trying to create a web app for bycicle roads in a specific city.Till now I have managed to add a Map of the city in my project.Bellow a piece of the HTML: ''' <iframe width="100%" height="100%" frameborder="0" style="border:0" referrerpolicy="no-referrer-when-downgrade" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyB50AmUn73pxdoVuVhRAkjAjnhGjLp7ymM&q=streets+in+Sofia" allowfullscreen> </iframe> ''' The question is following: I have the Directions button on the map but it redirects to google.maps. I want to make the directions(Start and Endpoint) to appear right over the map(on the same page). Is this possible and how can I do this ? Thank you! -
Setting variable is not being set up during testing middleware (p
settings.py MY_VAR = os.get("MY_VAR", False) custom_middleware.py from my_proj.settings import MY_VAR from django.core.exceptions import MiddlewareNotUsed class CustomMiddleware: def _init_(self, get_response): if MY_VAR == 'False': raise MiddlewareNotUsed self.get_response = get_response def __call__(self, request): if MY_VAR == 'True': #My custom logic return response = self.get_response(request) return response test_custom_middleware.py import os from unittest.mock import Mock from api.middlewares.custom_middleware import CustomMiddleware class TestLCustomMiddleware: def test(self, settings): request = Mock() settings.MY_VAR = 'True' assert settings.MY_VAR with patch.dict('os.environ', {'MY_VAR': 'True'}): assert 'MY_VAR' in os.environ middleware = CustomMiddleware(get_response='response') middleware(request) In CustomMiddleware I always get "False" in MY_VAR variable of settings. How can I set it up? -
Is it possible to create a formset in a formset?
For an example I wanted to create quiz using formsets. User can add more questions and more answers to each question too(max=4). -
Django Select a valid choice error while poulate it via objects.none()
I am currently having issue to ModelChoiceFiled. I initilize it in form via objects.none() but in html I update it via ajax. when I want to save my form I encounter the " select a valid choice ". Forms: woPart = forms.ModelChoiceField(label="نام کاربر",queryset=Stock.objects.none(),required=False) -
Why save() method need to self argument in django?
I am trying to solve this problem for over 3 days but can't solve it yet. I know self use for a method that is under a class, but I am working with method base view so why this error occurs when I try to save the OrderItem model? models.py class OrderItem(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart, blank=True) name = models.CharField(max_length=200) district = models.ForeignKey(District, on_delete=models.CASCADE) city = models.CharField(max_length=200) postal_code = models.SmallIntegerField() area = models.TextField() phone = models.CharField(max_length=12) status = models.CharField(max_length=20, choices=STATUS_CHOICE, default="accepted",blank=True, null=True) email = models.EmailField() def __str__(self): return self.user.email views.py def checkout(request): context={} subtotal =0 forms = OrderItemForm() context['forms'] = forms if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user).order_by('-id') for product in cart: subtotal += product.total_cost context['subtotal'] = subtotal customer = Customer.objects.get(user=user) if request.POST: form = OrderItemForm(request.POST) if form.is_valid(): instance = OrderItemForm.save(commit=False) instance.user = user instance.customer = customer instance.cart = cart instance.save() else: messages.warning(request, form.errors) return render(request, 'checkout.html', context) command-line error: response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\bitspirits\rndm\shop\views.py", line 76, in checkout instance = OrderItemForm.save(commit=False) TypeError: save() missing 1 required positional argument: 'self' -
Writing test for race condition
I want to write unit test to check if race condition happens when multiple users send request at the same time. I'm using pytest. I have tried threading module of python and it didn't work. What is the standard solution? -
Django celery and heroku
I have configured celery to be deployed in heroku, all Is working well, in fact in my logs at heroku celery is ready to handle the taks. Unfortunately celery doesn't pick my tasks I feel there is some disconnection, can I get some help?