Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use choicefield in django
i have table in db in which i stores countries and i dynamically pass those countries in template and and in forms.pt i have a ChoiceField(widget=forms.Select,required=True) like this but i didnot get the value from this filed but when i chane it into CharField i get the value. <div class="form-group col-md-4 select-border"> <label>Country</label> <select class="form-control basic-select" name="country"> {% for country in countries %} <option value="{{ country.value }}">{{ country.value }}</option> {% endfor %} </select> </div> form.py country = forms.ChoiceField(widget=forms.Select,required=True) views.py users_meta.candidate_country = ProfileForm.cleaned_data['country'] -
Can we use override_settings other than unit tests in Django?
Django uses a setting PASSWORD_RESET_TIMEOUT_DAYS whose default value is 3 Days. In my code, I am using reset password functionality of Django also as One Time Link (just like One time password) to set the password for the user upon registration. But this link also has the same expiry duration i.e. 3 Days Can I do something which will increase its expiry duration but doesn't mess with the default reset password functionality of my app? Something like override_settings which we use in unit tests. -
Validation fail - field is required. ManyToMany serialization Django
I have form data that I want to serialize to create two objects, Account and AccountClub. AccountClub is the in between table between Account and Club with additional fields, rakeback and chip_value. I can serialize the formdata but when i call the is.valid() function before saving, I get returned an error with the manytomany fields empty Here is my models: class Account(models.Model): nickname = models.CharField(max_length=64) club_account_id = models.IntegerField() agent_players = models.ManyToManyField( AgentPlayer, related_name="accounts") clubs = models.ManyToManyField( Club, through='AccountClub', related_name='accounts') def __str__(self): return f"{self.nickname} ({self.club_account_id})" class AccountClub(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='club_deal') club = models.ForeignKey( Club, on_delete=models.CASCADE, related_name='account_deal') rakeback_percentage = models.DecimalField( max_digits=3, decimal_places=3, validators=[MinValueValidator(Decimal('0.01'))]) chip_value = models.DecimalField(max_digits=3, decimal_places=2, validators=[ MinValueValidator(Decimal('0.01'))]) def __str__(self): return f"{self.account.nickname} belongs to {self.club.name} with rakeback of {self.rakeback_percentage} and chip value of {self.chip_value}" Serializers: class AgentPlayerSerializer(serializers.ModelSerializer): class Meta: model = AgentPlayer fields = "__all__" class ClubSerializer(serializers.ModelSerializer): agent_players = AgentPlayerSerializer(many=True) class Meta: model = Club fields = '__all__' class AccountSerializer(serializers.ModelSerializer): agent_players = AgentPlayerSerializer(many=True) clubs = ClubSerializer(many=True) class Meta: model = Account fields = [ 'nickname', 'club_account_id', 'agent_players', 'clubs', ] def create(self, validated_data): rakeback_percentage = validated_data.pop('rakeback_percentage') chip_value = validated_data.pop('chip_value') club = validated_data.club account = Account.objects.create(**validated_data) account.account_club.rakeback_percentage = rakeback_percentage account.account_club.chip_value = chip_value AccountClub.create(account=account, club=club, rakeback_percentage=rakeback_percentage, chip_value=chip_value) return account views.py: def … -
Django Channels 2 and Signals: Websocket Connections failed
I am using channels 2 and signals in order to detect when a certain type of model is saved and push a notification to all clients. I get the error: WebSocket connection to 'ws:/account/home' failed: WebSocket is closed before the connection is established. I don't see where I made a mistake. Many thanks in advance for your help. In my Project: FUNDBOOK_V5/ROUTING.PY from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import FundBook_Core.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( FundBook_Core.routing.websocket_urlpatterns ) ), }) In my App: FUNDBOOK_CORE\ROUTING.PY from django.urls import re_path from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^account/home/$', consumers.NotificationConsumer), url(r'^fund/(?P<fund>[\w-]+)/$', consumers.NotificationConsumer), ] FUNDBOOK_CORE\CONSUMERS.PY import json import asyncio from django.contrib.auth import get_user_model from channels.generic.websocket import AsyncJsonWebsocketConsumer, AsyncConsumer class NotificationConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.channel_layer.group_add("task", self.channel_name) await self.send({ "type": "websocket.accept" }) print("Connected!", event) async def websocket_disconnect(self, event): await self.channel_layer.group_discard("task", self.channel_name) print("Disconnected!", event) async def send_message(self, event): await self.send({ "type": "websocket.send", 'text': 'Oy, mate!' }) SIGNALS.PY from FundBook_Core.models import ThreadTask from django.db.models.signals import pre_save from django.dispatch import receiver from asgiref.sync import async_to_sync from channels.layers import get_channel_layer @receiver(pre_save, sender=ThreadTask) def notify_thread_task_save(sender, **kwargs): if "instance" in kwargs: instance = kwargs["instance"] # check … -
How to use Formset to display questions and corresponding choices?
I have some models namely, Exam, Question, MCQ, Choices for the creation of exams, and ExamTaker, UserAnswers to record the answers. Each MCQ is a model from the base model Question. Now, I want to list the questions to the users from an Exam and save the answers. I am trying to use the Formset Factory but it is not quite working. url is path('exam/<int:exam_id>/take-exam', ShowQuestion, name='take-exam' ), What I wants to do is, when a user visits this url, I wants to show the questions from a queryset and take the answers from them. My models are from django.db import models from django.utils import timezone from django.contrib.auth.models import User from exam.models import Exam, Question from mcq.models import Choice class ExamTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) exam = models.ForeignKey(Exam,on_delete=models.CASCADE) score = models.FloatField(default=0) started_at = models.DateTimeField(default = timezone.now) completed_at = models.DateTimeField(default = timezone.now) completed = models.BooleanField(default=False) def __str__(self): return f'{self.exam.sub_code}: {self.user.first_name}' class UserAnswers(models.Model): user = models.ForeignKey(ExamTaker, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete= models.CASCADE, null=True) choice = models.ForeignKey(Choice, on_delete = models.CASCADE, null=True) My forms are from django.forms import ModelForm from .models import ExamTaker, UserAnswers class ExamTakerForm(ModelForm): class Meta: model = ExamTaker fields = '__all__' class MCQForm(ModelForm): class Meta: model = UserAnswers fields = '__all__' … -
django query year of datefield not being extracted
In my django project I have two models Person & Child. class Person(models.Model): first_name = models.CharField('Name', max_length=200) family_name = models.ForeignKey(Family, on_delete=models.PROTECT) gender_is_male = models.BooleanField(default=True) birth_place = models.CharField(null=True, blank=True, max_length=200) year_of_birth = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(datetime.date.today().year), MinValueValidator(1800)]) month_of_birth = models.PositiveIntegerField(null=True, blank=True, validators=[MaxValueValidator(12), MinValueValidator(1)]) birth_date = models.DateField(null=True, blank=True) class Child(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True) father = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='father_of', limit_choices_to={'gender_is_male': True}) mother = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='mother_of', limit_choices_to={'gender_is_male': False}) A Person may have birth_date or only year_of_birth and/or month_of_birth. I need to sort the children from oldest to youngest and I made the following query: children = person.mother_of.all().annotate( year_sort=Case( When( person__birth_date__isnull=False, then=('person__birth_date__year') ), default=('person__year_of_birth'), output_field=PositiveIntegerField() ) ).order_by('year_sort') But I get the following error: ValueError at /members/237/ invalid literal for int() with base 10: '1956-08-25' When I traceback, I see this: connection:<django.db.backends.sqlite3.base.DatabaseWrapper object at 0x7f0bd3264700> converter:<function BaseExpression.convert_value.<locals>.<lambda> at 0x7f0bd1e76d30> converters:[(3, ([<function BaseExpression.convert_value.<locals>.<lambda> at 0x7f0bd1e76d30>], <Case: CASE WHEN <WhereNode: (AND: <django.db.models.lookups.IsNull object at 0x7f0bd1f8d970>)> THEN Col(T3, members.Person.birth_date), ELSE Col(T3, members.Person.year_of_birth)>))] convs:[<function BaseExpression.convert_value.<locals>.<lambda> at 0x7f0bd1e76d30>] expression:<Case: CASE WHEN <WhereNode: (AND: <django.db.models.lookups.IsNull object at 0x7f0bd1f8d970>)> THEN Col(T3, members.Person.birth_date), ELSE Col(T3, members.Person.year_of_birth)> pos:3 row:[266, 263, 237, '1956-08-25'] rows:<itertools.chain object at 0x7f0bd1e8f580> self:<django.db.models.sql.compiler.SQLCompiler object at 0x7f0bd1e8f3d0> value:'1956-08-25' It seems that the expression then=('person__birth_date__year') is being converted into THEN Col(T3, … -
Is there a way to display the color of a (hex color) field in the Django Admin site?
I have a model in Django 3: class Ingredient(models.Model): name_EN = models.CharField(max_length=100, unique=True, null=True) hexcolor = models.CharField(max_length=7, default="#ffffff") def __str__(self): return self.name_EN This lists Ingredients and has associated a name with it, e.g. 'Dill' or 'Tomato', and a 'hexcolor' e.g. #C5E1A5 or #DD2C00. Currently, from the admin site, I can see the ingredients listed as name_EN of the Ingredient, and when I click through also the hexcolor value (#......). But I would like to see the actual color listed next to the name_EN, so I can see it (and change when needed). It doesn't necessarily need a color picker, could be nice, but I seek in the first place how to display the color (e.g. the background color of the hexcolor field?). Any suggestions where and how to do this? Would be appreciated. -
How do I solve ValueError: too many values to unpack (expected 2) in Django
I have been working at a Django App. Basically, the function of the app is to take the input as a subject name from user using a Form, take the details of progressed activities of that subject of that specific user, and save each of that detail in a single variable. It involved 3 Models viz. User Model (Django's default), finally it will use those variables to which details are assigned, and calculate the performance using fuzz_algo(), and then return the result in the form of Messages to the Template. Everything seems to be fine, but when I click the button Calculate in the template users/performance_calculator.html, it give this error ValueError: too many values to unpack (expected 2) at this statement skype = Detail.objects.filter(subject__subject=sub, user__username=User.username).get('skype_session_attendance') in views.py My views.py: from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, PerformanceCalculatorForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Subject, Detail from .fuzzy_logic_algo import fuzz_algo def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your Student Account has been created! You can log in ESACP now.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': … -
How to query automatically in Django?
I can retrieve data by explicitly giving the 'Id' but I want to retrieve it automatically the top 3 'Id' data. How can I do that. please check my code below and help me out this is models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) def __str__(self): return self.title this is admin.py class PostAdmin(admin.ModelAdmin): list_display = ('id','title') admin.site.register(Post, PostAdmin) this is views.py def index(request): post3 = get_object_or_404(Post, id=3) post2 = get_object_or_404(Post, id=2) post1 = get_object_or_404(Post, id=1) context = { "post3": post3, "post2": post2, "post1": post1, } return render(request, 'contents/index.html', context) as you can see in the above am giving the id number and it works fine but I want it to retrieve the top id automatically this is my remplate <h3>{{post3.title}}</h3> <h3>{{post2.title}}</h3> <h3>{{post1.title}}</h3> -
How to perform OKTA SSO integration to Django Web Application on Windows platform?
I am trying to integrate OKTA Single-Sign-On to my Django web application. The web page has a single page that interacts with the database in order to fetch the records from MSSQL Server. I want to allow this web application available to only the users registered in my OKTA. The development needs to be done on Windows platform. Approach 1: SAML I have tried https://github.com/fangli/django-saml2-auth But this has a dependency on xmlsec.exe and xmlsex1.exe I found the binary for xmlsec1, but installation is failing while installation since dependencies required for xmlsec1 are not available. This is a known issue reported by many other users. Approach 2: OpenID I also have tried https://github.com/zeekhoo-okta/okta-django-samples to connect my application with OKTA. But it is failing because of errors on views.py It would be great help if someone can provide a working sample for OKTA-Django integration with SAML or OpenID. -
Unable to get AWS SSL Certificate
I am trying to make my Django REST API get HTTPS, For that using AWS Certificate manager,I tried to create a certificate using public DNS IPV4 ec2-52-66-238-9.ap-south-1.compute.amazonaws.com It shows validation failed with both Email validation and DNS validation and i don't wanna buy a domain to get it.Is there any way? -
docker stuck on django runserver
Dockerfile: FROM python:3.6-slim ENV root=/test ENV django=$root/test COPY ./code $root WORKDIR $django RUN pip install -r requirements.txt --no-cache-dir CMD ["python3", "manage.py", "runserver", "--noreload"] without --noreload it will stuck on Watching for file changes with StatReloader FYI, "docker run hello-world" is working fine. -
AJAX gives success code 200, but does not trigger function in views.py
I am trying to call a function in Django. The POST request returns code 200, but the response back is bad. Is the sendCommand function being called? I think it is not... Am I missing something? VIEWS.py @csrf_exempt def sendCommand(request): if request.method == 'POST': print("\n\n\n\n sendCommand \n\n\n\n"); return HttpResponse( json.dumps({'result': 'ok',}), content_type="application/json" ) From HTML $.ajax({ type:'POST', url: 'user/camcontrol', data: { ip : $("#hiddenp").attr("name"), code:'d', csrfmiddlewaretoken: csrf_value }, // handle a successful response success : function(json) { if (json.result=== 'ok'){ console.log('It works!'); }else{ console.log('Something wrong with response'); } } }); URLS.py url('index/user/camcontrol/',views.sendCommand, name="sendCommand") Server "POST /webapp/index/user/camcontrol HTTP/1.1" 200 8301 Console Something wrong with response -
Very specific and strange error : Axios Getting the wrong token for jwt authentication
im currently using django-simplejwt with axios to authenticate my requests from react frontend to my django backend. The problem: The problem only occurs when the component first mounts upon authentication. It has no issues in the componentDidUpdate method (AKA when i refresh the page it works) I created a API component to house the axios and token refreshing logic here: axiosApi.js import axios from 'axios' import * as actions from './../redux/actions/auth'; import { connect } from 'react-redux'; const baseURL = 'http://127.0.0.1:8000/api/' const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { 'Authorization': "JWT " + localStorage.getItem('access_token'), 'Content-Type': 'application/json', 'accept': 'application/json' } } ); axiosInstance.interceptors.response.use( response => response, error => { const originalRequest = error.config; // Prevent infinite loops if (error.response.status === 401 && originalRequest.url === baseURL+'token/refresh/') { window.location.href = '/login/'; return Promise.reject(error); } if (error.response.data.code === "token_not_valid" && error.response.status === 401 && error.response.statusText === "Unauthorized") { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken){ const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); // exp date in token is expressed in seconds, while now() returns milliseconds: const now = Math.ceil(Date.now() / 1000); console.log(tokenParts.exp); console.log('this is within the interceptor'); if (tokenParts.exp > now) { return axiosInstance .post('/token/refresh/', {refresh: refreshToken}) .then((response) => { localStorage.setItem('access_token', response.data.access); localStorage.setItem('refresh_token', response.data.refresh); axiosInstance.defaults.headers['Authorization'] = … -
Docker in windows 10 pro: python: can't open file 'manage.py': [Errno 2] No such file or directory
I am using docker in windows 10. My docker project was running well but after updating the docker desktop to 19.03.8, i am facing this error for my existing project. Before updating docker desktop, the project was running very well. But I created another django project for testing which is running without any error. This is dockerfile of my projectThis is docker compose file This is the error message -
Can a heroku deplayed django app access local file system?
My django app requires me to access folders in 'C' drive and execute a program on these files. Can I access the local file system after deploying it on heroku? -
Error while uploading file through form in Django
I am trying to save a file and some other details in django using forms. And I only want it to save a CharField and a FileField but not the country field. For country field I want it to take its value through a post request. But the form isn't saving. The errors says "data didn't validate". Also this method works fine if I don't use a FileField. models.py class Simple(models.Model): name = models.CharField(max_length=100) city = models.FileField(upload_to='marksheet') country = models.CharField(max_length=100) forms.py class SimpForm(forms.ModelForm): class Meta: model = Simple fields = ['name','city'] A snippet from upload.html <form action="upload" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Test input</label> <input type="text" name="cont"> {{form.name}} {{form.city}} <button type="submit">Submit</button> </form> views.py def upload(request): if request.method == 'POST': a = request.POST.get('cont') form = SimpForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.country = a post.save() return HttpResponse('saved') else: return HttpResponse('ERROR SAVING') else: form = SimpForm() return render(request,'upload.html',{'form':form}) -
Does Django have correlated queries?
This answer is perfect for my if I was using RAW SQL in my code https://stackoverflow.com/questions/17038193/select-row-with-most-recent-date-per-user/17038667#= MySql has no DISTINCT ON so I can't use that either Is there a way to make this query a Django ORM statement? -
Django Contact form not showing the sender
I create a contact form but unable to show the sender, the sender and receiver is same value of admin@gmail.com. Here is my settings.py, views.py and models.py. settings.py # Registration Notification EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'admin@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 views.py def contacView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] recipients = ['admin@gmail.com'] try: send_mail(subject, message, from_email, recipients, fail_silently=False, ) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') models.py class ContactForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
OrderFilter() got an unexpected keyword argument 'queryset'
I want to build a filter form for Table Search and I am facing this error while creating a django filter(Order Filter). my filters.py--- from .models import * import django_filters class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = '__all__' my model---- class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return str(self.product) my views.py--- def customer(request,id): customer = Customer.objects.get(id=id) order = customer.order_set.all() total_order = order.count() myFilter = OrderFilter(request.GET,queryset=order) order = myFilter.qs context = {'customer':customer,'order':order,'total_order':total_order,'myFilter':myFilter} return render(request,'accounts/customer.html',context) my customer.html--- <form method="get"> {{ myFilter.form }} <button class="btn btn-primary" type="submit">Search</button> </form> -
IntegrityError in Django even after defining form_valid
I'm trying to create and store the model form in the database. The model represents a product, and has field like the category, image, price... etc. Here's the model class Product(models.Model): categories = (("Books", "Books/Study Materials"), ("Notebooks", "Notebooks/Rough Pads"), ("Equipments", "Equipments/Tools"), ("Cloths", "Cloths/Uniforms"), ("Sports", "Sports/Sportswear"), ("Miscellaneous", "Miscellaneous")) user = models.ForeignKey(User, on_delete = models.CASCADE) date_posted = models.DateTimeField(default = timezone.now) category = models.CharField(max_length = 13, choices = categories, default = "Miscellaneous") description = models.CharField(max_length = 75, null = True, blank = True) image = models.ImageField(default = "product/default.png", upload_to = "product") price = models.PositiveIntegerField() def __str__(self): return f"{self.category} by {self.user.username} for {self.price}" def save(self, *args, **kwargs): super().save() image = Image.open(self.image.path) image.thumbnail((600, 600), Image.ANTIALIAS) image = image.crop(((image.width - 600)//2, (image.height - 400)//2, (image.width + 600)//2, (image.height + 400)//2)) image.save(self.image.path) Here's the form that same model class ProductAddForm(forms.ModelForm): description = forms.CharField(max_length = 75, widget = forms.TextInput(attrs = {'placeholder': 'Description'}), help_text = "Not more than 75 characters") image = forms.ImageField(required = False) price = forms.IntegerField(required = False, widget = forms.TextInput(attrs = {'placeholder': 'Price'})) class Meta: model = Product fields = ('category', 'description', 'image', 'price') def clean_description(self, *args, **kwargs): description = self.cleaned_data.get('description') if len(description) == 0: raise forms.ValidationError('Description is required!') if len(description) > 75: raise forms.ValidationError(f'Description should … -
How to pull an array from POST request with-in Django
I am trying to extract an Array from a POST request using Django. def settlements_orders(request): database = "####" if request.method == 'POST': first_date = request.POST.get('first_date', False) last_date = request.POST.get('last_date', False) brands = request.POST.getlist('brands[]') else: first_date = '2020-01-01' last_date = '2020-05-13' brands= ['ICON-APPAREL'] settlements_orders = SettlementOrders.objects.using(database)\ .filter(posted_date__date__range=[first_date, last_date]) \ .filter(sku__brand__in=brands) \ .select_related('sku').select_related('posted_date') \ .values('sku__company','sku__brand','sku__department','sku__category','sku__sub_category', 'sku__parent_asin','sku__asin','sku__vendor', 'sku__color','sku__size','sku__case_pack', 'posted_date__year', 'posted_date__month' )\ .annotate(count=Count('order_id'), qty_sold=Sum('quantity_sold'), qty_returned=Sum('quantity_returned'), order_revenue=Sum('order_revenue'), refund_revenue=Sum('refund_revenue'), promotion=Sum('promotion'), giftwrap_collected=Sum('giftwrap_collected'), giftwrap_paid=Sum('giftwrap_paid'), shipping_fees_collected=Sum('shipping_fees_collected'), shipping_fees_paid=Sum('shipping_fees_paid'), sales_tax_collected=Sum('sales_tax_collected'), sales_tax_paid=Sum('sales_tax_paid'), shipping_tax_collected=Sum('shipping_tax_collected'), shipping_tax_paid=Sum('shipping_tax_paid'), fulfillment_fees=Sum('fulfillment_fees'), comission_fees=Sum('comission_fees'), closing_fees=Sum('closing_fees'), other_fees=Sum('other_fees'), restock_fees=Sum('restock_fees'), goodwill_paid=Sum('goodwill_paid'), goodwill_reimbursed=Sum('goodwill_reimbursed'), return_fees=Sum('return_fees'), reimbursements=Sum('reimbursements'), margin=Sum('margin') ) return JsonResponse(settlements_orders[::1], safe=False) I am using the Array to filter data When I make a GET request I am returned data but on a POST request, I get a 500 response. Any help would be appreciated. -
Testing A @verified_email_required View
Im trying to unit test one of my views that is decorated with @verified_email_required. I am unable to find out how to set the user as having their email verified so that it will allow them to view the page and assert that it uses the correct template (creating a superuser doesnt help). This is the error im getting AssertionError: False is not true : Template 'enrolment/index.html' was not a template used to render the response. Actual template(s) used: account/verified_email_required.html, account/base.html, base.html And this is my test def test_verified_user_uses_correct_template(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.get('/enrolment/') self.assertTemplateUsed(response, 'enrolment/index.html') Thank you. -
Docker container cannot find Django package
I am new to docker. I am trying to dockerize a simple django app, which I create in anaconda3 in ubuntu. My dockerfile looks like this: # Pull base image FROM continuumio/anaconda3 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code COPY requirement.txt /code/ RUN conda install --file requirement.txt # Copy project COPY . /code/ The requirement.txt is the list of dependency packages from my conda virtual enviroment. I obtain that by running this line in my conda activated environment: conda list -e > requirement.txt and the package django=3.0.3=py_0 is in this requirement.txt Also, at this point, I have properly installed docker and pulled the base image continuumio/anaconda3. Here is my docker-compose.yml file: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 Now, when I run docker-compose up, I got this chain of error messages: web_1 | Traceback (most recent call last): web_1 | File "/code/manage.py", line 10, in main web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent … -
request.GET.get can not read the full request on a search bar in a django app
I have a problem with the search bar in my django app, when i type a sentence, trying to look for an item, it interprets the sentence as a single name. For example i have two items ( shirt and sweatshirt ) , when i type 'shirt sweatshirt' in the search bar, it says that this item isn't available. I there any way i could fix this problem? this is the function that implements the request in my views file: def search(request): try: q = request.GET.get('q') except: q = None if q: item = Item.objects.filter(Q(title__icontains=q)) context = {'query': q, 'item': item} template = 'results-page.html' else: template = "home-page.html" context = {} return render(request, template, context)