Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User is not logging in despite login() being called in Django
I am new to Django and I'm trying to implement a custom backend called PlayerBackend that is meant to be separate from the default Backend Django provides. Here is my view: def login_player(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(request, email=email, password=password) if user is not None: pdb.set_trace() login(request, user) messages.success(request, "Successfully logged in!") else: messages.error(request, "Credentials were invalid") else: form = LoginForm() return render(request, 'users/login.html', {'form': form}) The success message is being displayed, but when I try to check if the user is authenticated... def view_player(request, player_id): return HttpResponse(request.user.is_authenticated) I get False. I did not extend the AbstractUser class and just added the last_login fields. Here is my model: class Player(models.Model): first_name = models.CharField(max_length=50, validators=[validators.RegexValidator(regex='^[A-Za-z]+$', message="Names can only contain letters")]) last_name = models.CharField(max_length=50, validators=[validators.RegexValidator(regex='^[A-Za-z]+$', message="Names can only contain letters")]) password = models.CharField(max_length=255) email = models.CharField(max_length=50, unique=True, validators=[validators.validate_email]) registered_date = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField() is_authenticated = False backend = None def __str__(self): return self.first_name + " " + self.last_name Am I required to do what the documentation says and specify a custom model, extend the abstract model, etc? I want to have both a login for admins and players. … -
Is there a way in Python to make an array with two elements in it and make it as a single index in a dictionary?
I just want to make the elements as one index. For example, array = ['a', 'b'] to array_of_dict = [{a,b}] -
ListFields not generating the right data output
I am new to Django, and I'm trying to generate a list of strings using my model and serializer. Model changes : ABC = ListTextField(max_length=64, base_field=models.CharField(max_length=32, blank=True, default=''),blank=True) Serializer code : class Test(serializers.Serializer): class Meta: fields = (ABC) associated_brands = fields.ListField( child=fields.CharField(max_length=64), max_length=64, allow_empty=True, required=False ) the output from the API get a response that I get us : {'ABC': ['15']} But when it print the drf.data {'ABC': ['1','5']} Any guidance as to what I'm doing wrong? -
Cannot access Django administrator site
Successfully created an admin user using py manage.py createsuperuser. Entered username, e-mail, password but whenever I try to access this link http://127.0.0.1:8000/admin/ it says "This site can’t be reached" and "127.0.0.1 refused to connect, " How do I fix this error and access the administrator site ? I'm using Windows 10 with the latest version of Django. -
Expression contains mixed types: SmallIntegerField, BigIntegerField. You must set output_field
i create a model in django i want to set monthly_wage as monthly_wage=working_days*daily_wage in annotation from django.db.models import F class AnnotationManager(models.Manager): def __init__(self, **kwargs): super().__init__() self.annotations = kwargs def get_queryset(self): return super().get_queryset().annotate(**self.annotations) class DetailsList(models.Model): month_list=models.ForeignKey('MonthList',on_delete=models.CASCADE,verbose_name='لیست ماهانه ') worker=models.ForeignKey('Workers',on_delete=models.CASCADE,verbose_name=' نام کارگر') working_days=models.SmallIntegerField('تعداد روز کارکرد') daily_wage=models.BigIntegerField('دستمزد روزانه') advantage=models.BigIntegerField('مزایای ماهانه') _monthly_wage=0 objects = AnnotationManager( monthly_wage=F('working_days') * F('daily_wage') ) but because working_days is smallinteger and daily_wage is biginteger this error raise: Expression contains mixed types: SmallIntegerField, BigIntegerField. You must set output_field. how can i fix this -
DJANGO: CustomUser model doesn't create objects
I have created a CustomUser model and it has a one to relationship with my two other models. ''' class User(AbstractUser): is_learner = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Teacher(models.Model): #teacher_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) class Learner(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) ''' They do not show up when I try to create learner and teacher objects in their respective databases, as shown: ''' class LearnerSignUpForm(UserCreationForm): email = forms.EmailField() class Meta(UserCreationForm.Meta): #User = CustomUser model = CustomUser fields = ["username", "email", "password1", "password2"] #fields = UserCreationForm.Meta.fields + ("username", "email", "password1", "password2") @transaction.atomic def save(self, *args, **kwargs): user = super().save(commit=False) user.is_learner = True user.save() learner = Learner.objects.create(user=user) return user ''' How do I get it to save in learner and teacher tables respectively? -
Django forms CheckboxSelectMultiple
Im trying to change a form from RadioSelect to MultipleChoice with this form, I can see and the form in my tempalte as RadioButtons and can fill and save. class TestForm(forms.Form): def __init__(self, question, *args, **kwargs): super(TestForm, self).__init__(*args, **kwargs) choice_list = [x for x in question.get_answers_list()] self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=RadioSelect) But, when I change to widget=CheckboxSelectMultiple Then I can see and select all Choices, but after saving the page is reloading without saving. class TestTake(FormView): form_class = TestForm template_name = 'question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: return render(request, self.single_complete_template_name) return super(TestTake, self).dispatch(request, *args, **kwargs) How can I insert a Multiple Select checkbox here? -
In Django, filter a query set for two datetimes being within one day
I have a Django model like: from django.db import models class Person(models.Model): # ... last_login = models.DateTimeField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) I want to find all Persons where last_login is within one day of date_created. So far I have: from datetime import timedelta from django.db.models import F Person.objects.annotate( duration=F("last_login") - F("date_created") ).filter(duration__lte=timedelta(days=1)) But the tail end of the error when I do that is like: File ".../lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1316, in to_python parsed = parse_datetime(value) File ".../lib/python3.7/site-packages/django/utils/dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object I'm not sure what I'm doing wrong, probably with that timedelta(days=1). Also (and I don't think this is the immediate error), I'm not sure if that query will take account of the fact that last_login could be None. -
My heroku website looks empty and no html files are rendering
I was trying to deploy my django website to heroku. Basically I have done everything step by step and no errors in deploying as well. But there is nothing in my webpage just a side panel is showing nothing else. No navigation bars, no buttons, no html renderings ... nothing. But when I viewed the source code the html codes are there. I can access different urls as well but nothing renders in the webpage its weird really. The website works perfectly in localhost but not in heroku. I need a fix for this, thanks. Here is how the webpage looks right now, enter image description here -
Edit Session Variable in Javascript/JQuery
I have a session variable in my Django views: request.session['count'] = 0 I can access this variable in Javascript and log it to the console easily, but I'm wondering what the best way is to pass an updated version of the variable back to the views? I'd ideally like to edit the value in the Javascript of the HTML template and then have the updated value passed back to the Django view so that it could be called something like so: count=request.body['count'] print(count) I am able to pass the variable via the URL parameters but I am looking for a way to pass the value without modifying the URL if possible. Thanks in advance! -
Can't apply migrations in Django SQLlite memory database
I'm writing some tests, and I want to be able to run django server with my test settings (that's why I'm using in-memory database). It seems to be working, no errors reported when running. But migrations are not applied, I can't perform any action on the database, because model tables do not exist. when I run python manage.py migrate, all my migrations get applied (I see these Applying migrations... OK messages), but it has no effect. When I run python manage.py showmigrations, none of the migrations are applied (I see [ ] 0001_initial etc., without the X). When I go to django shell, I can't perform any action, because table does not exist. Any idea what might be the reason? It works fine with normal, postgres database. My settings: DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'TEST_NAME': ':memory:', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } -
Image not uploading in Django Model
I am able to update the image of each user's profile picture. But not through the code. Though it doesn't give me any error. u_form = For changing the username. p_form = For changing the picture in their profile. NOTE: Profile has one to one relation with the Profile model. settings.py file section: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' models.py for Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpeg', upload_to='profile_pics') status = models.TextField(max_length='200') def __str__(self): return self.user.username forms.py for the same: class ProfileUpdate(forms.ModelForm): class Meta: model = Profile fields = ['image',] Main views.py file: . . from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm as uc from django.contrib.auth.forms import AuthenticationForm as af . . @login_required(login_url='/login') def update_profile(request): user = request.user if request.method == 'POST': u_form = UserUpdate(request.POST, instance=user) p_form = ProfileUpdate(request.POST, request.FILES, instance=user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'The profile has been updated.') return redirect('/profile') else: #instance: to get pre-filled data of user u_form = UserUpdate(instance=user) p_form = ProfileUpdate(instance=user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'update_profile.html', context) HTML form "update_profile.html": <form action="{% url 'update_profile' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form … -
Is there a way to pass the value of a model field as a parameter to models.ImageField(storage=function) within same Model
class StorageModel(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="profile", null=False) file_meta = models.ImageField(storage=UserDataStorage(profile=user), blank=False, null=False) class UserDataStorage(S3Boto3Storage): location = common.AWS_LOCATION_TEST file_overwrite = False def __init__(self, *args, **kwargs): for k, v in kwargs.items(): print("omg") print(v) super(UserDataStorage, self).__init__(*args, **kwargs) How to pass the field user as an argument to the object UserDataStorage? The problem here is, field user gets passed down to UserDataStorage but as a type <django.db.models.fields.related.ForeignKey>. I want a Profile instance here. Is this achieveable in Django? -
Why is it not getting paginated?
I'm trying to develop a website, where I wrote a function based view, and now want to add pagination.I'm following the django documentation, but it's just not coming together. Can anyone help me please? my views.py: from django.shortcuts import render, Http404 from django.http import HttpResponse from .models import Product from django.core.paginator import Paginator def home(request): products = Product.objects.all() paginator = Paginator(products, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'index.html', {'products': products}) -
Auto height paper Reportlab Python (case study about ribbon paper for printing shopping receipts)
How to make height measurements automatically based on content (shopping lists and prices) that will be printed on ribbon paper with a width of 110mm (currently I use that size paper to print - using thermal printer - shopping receipts). The following is a sample code snippet that I have: class TOPDFBarcodeThermal(TOPDF): width = 110 * mm limit = 110 * mm # auto height in here def set_pdf(self): self.pdf = SimpleDocTemplate( self.response, title=self.title, rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0, pagesize=(self.width, self.limit) ) On the ribbon paper, I want to make it have a dynamic height that matches the list of items purchased. Are there other easier ways or what? Thank you -
django-cms Documentation: django.urls.exceptions.NoReverseMatch: 'polls' is not a registered namespace
Description Using the tutorial found here: http://docs.django-cms.org/en/latest/introduction/05-apphooks.html. Up to step 5, there has not been any major issue. However, when completing the steps in step 5, the following error appears: django.urls.exceptions.NoReverseMatch: 'polls' is not a registered namespace Screenshot available here: https://imgur.com/6i0hnTG. This is after completing step 5.1.3 Restart the runserver. Steps to reproduce Followed tutorial up to step 5.1.3. Expected behaviour Should not cause 500. Actual behaviour Causes 500. Additional information Any page with the following causes the 500 error to be raised: <form action="{% url 'polls:vote' instance.poll.id %}" method="post"> However, I can also add back to urls.py the following, which fixes the error (although I believe this is not the purpose of the documentation tutorial): url(r'^', include('polls.urls', namespace="polls")), Also have ran into a few other issues in part 4 and part 8 of tutorial. In part 4, there is an on_delete error which is fixed by adding the following argument to models.ForeignKey function call: poll = models.ForeignKey(Poll, on_delete=models.CASCADE) Environment: Python version: 3.7.6 (tutorial recommends 3.6) Django version: 2.2.11 django CMS version: 3.7.1 -
Why can't Django model object be added to a list?
I'm trying to add an instance of a model in Django to a list and get these results (from Shell): Import the model and instantiate an object >>> from base.models import Service >>> s = Service.objects.first() Check the type of the object >>> type(s) <class 'base.models.Service'> Instantiate the list >>> mylist = [] Try to add the model object to the list >>> mylist += s Error Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'Service' object is not iterable Why exactly can I not add a model instance to the list? -
Failed to load resource: the server responded with a status of 403 (Forbidden)?
i am posting javascript localstorage object to backend(django). I am passing it through ajax. this is the code in frontend. function checkout_(){ console.log("checkout"); for(v in list1){ object=Object.values(localStorage)[v]; object = JSON.parse(object) } //ajax here console.log(object.length); $.ajax({ url: '{% url "chout" %}', data: { 'object': object }, method: "POST", dataType: 'json', success: function (data) { alert("success"); } }); i have given this function to a button via onclick. <button class="bg-danger text-white " onclick="checkout_()">Go To Checkout Counter</button> when i click on this button this error "Failed to load resource: the server responded with a status of 403 (Forbidden)" happens. in the views.py this is the code. views.py def checkoutnow(request): return render(request, "mart/checkout.html") I hope this detail is enough to explain the problem..Thankyou -
Django Rest join models on multiple field
I have two models as below. These models store budget sales data and actual sales data for each project by each month. # To test join on multiple keys class ActualSales(models.Model): time_id = models.CharField(max_length=8) project = models.CharField(max_length=100) actual_sales = models.DecimalField(max_digits=20, decimal_places=3) adjustment = models.DecimalField(max_digits=20, decimal_places=3) class BudgetSales(models.Model): time_id = models.CharField(max_length=8) project = models.CharField(max_length=100) budget_sales = models.DecimalField(max_digits=20, decimal_places=3) And the data will somewhat looks like this. Model A | time_id | project | sales | adjustment | +---------+-----------+-------+------------+ | 2019JAN | Project A | 1000 | 10 | | 2019JAN | Project B | 2500 | 5 | | 2019FEB | Project A | 1100 | 0 | | 2019FEB | Project B | 2400 | -10 | +---------+-----------+-------+------------+ Model B | time_id | project | budget | +---------+-----------+--------+ | 2019JAN | Project A | 1100 | | 2019JAN | Project B | 2400 | | 2019FEB | Project A | 1000 | | 2019FEB | Project B | 2500 | +---------+-----------+--------+ And I'm looking to produce an array of objects with each object represent each project's result each month, similarly to the way we join 2 tables with sql. However, I'm unsure how to write the serialiser and API Viewset … -
Set default image to CloudinaryField in Model
I have recently started using Cloudinary for media storage. I have a Profile model with image and cover image fields Without Cloudinary Before changing to cloudinary media storage the model looked like this: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) # setup without Cloudinary image = models.ImageField(default='profile_image/default.jpg', upload_to='profile_image', blank=False) cover_image = models.ImageField(default='cover_image/default.jpg', upload_to='cover_image', blank=False) It allowed me to set default image for both fields. With Cloudinary Now, after adding Cloudinary, it looks like this: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) # setup with Cloudinary image = CloudinaryField('image') cover_image = CloudinaryField('cover_image') I want to be able to set default images for both fields. Here are relevant libraries' versions Django==2.1.5 cloudinary==1.17.0 django-cloudinary-storage==0.2.3 olefile==0.46 cloudinary-cli==0.3.4 -
when i first ran my django project on local host 127.0.0.1:8000 it opened properly but now after adding product it shows 127.0.0.1 refused to connect
so this is the code and something i found weird is that my db.sqlite3 has a '?' (question mark) icon but the tutorial i am following has a white paper icon when i ran 127.0.0.1:8000 for first time it showed me my django local host but now it says this site cant be reached. i tried changing local host in settings.py to 127.0.0.1 #view from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello world! ') def new(request): return HttpResponse('New products ') #urls from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] -
How to display ellipsis to user
I'm a Django beginner. I have posts of users I follow and those who follows me,and I want to display different ellipsis ontop of other users post and not mine. For example if user A is friend user B, I want an ellipsis to be displayed only in user B post. What i tried doesn't give me what I wanted: {% if post.user == request.user %} <i fas fa-ellipsis></i> {% endif %} def home(request) all_images = Image objects.filter( Q(imageuploader_profile=request.user)| Q(imageuploader_profile__from_user__to_user=request.user)| Q(imageuploader_profile__to_user__from_user=request.user)) context = {'all_images': all_images } {% for post in all_images %} .... my codes here..... <i class="fas fa-ellipsis"></i> {% endfor %} -
Django: how to send one time messages like messages framework using rest api
I know in DJango using django.contrib.messages we can show messages Eg in the view of Login: from django.contrib import messages if form.is_valid(): ... messages.success(request, 'Login Successful') return redirect('Home Page') In the template of Home Page we can show the messages: {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} Because my Rest API will not be using any cookies or session. Is there any similar thing when i am working with rest api. -
how to implement database transactions mannulally in django?
I am new to django and i want to implement database transactions manually?is there anyway we can implement django transactions on specific models only? i have choice model on which i want to handle each user's transaction manually. models.py class choice_filling(models.Model): stud_id = models.ForeignKey(student, on_delete=models.CASCADE) clg_id = models.ManyToManyField(college) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() -
Is it safe to enable cors for DRF using TokenAuthentication?
I have a Django web app which serves a REST API (via Django Rest Framework) for users to make them able to retrieve some data from my website. I use TokenAuthentication method that requires you to set a Authorization header with the given token, then requests are accepted. Today I figured out that while my users can retrieve data by using Python requests library or httpie HTTP client, they can't retrieve data with their Javascript code (which's using fetch() method of Javascript). They see this error: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..." So I think I should enable CORS for my API then to accept requests from any web server of my users? I still want my users to authenticate with TokenAuthentication. So if I enable CORS, is it safe for my api and web app? Is there anything I should consider before doing this?