Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect to profile page with id user paramater?
I want redirect to user profile after click "Profile" dropdown. But profile need id user, I don't know to link views.py def profile(request, user_id): #Something.... return render(request, 'profile.html') urls.py path('profile/<int:user_id>/', views.profile, name='profile'), profile.html <a class="dropdown-item" href="{% url ???? %}">Profile</a> -
How to read csv file in html?
I have a code and the thing I am not understanding is why a function of some_view in views.py is not fetching files from CSV. Is there something wrong? There is also html file by the name of index.html. I want it to fetch the first column of CSV and make a loop in html so that I don't have to repeat it every time. views.py def some_view(request): reader = csv.DictReader(open('file.csv','r')) csv_output = [] data = csv.reader(reader) for row in data: csv_output.append(row) return render(request, 'index.html', context={'csv_content': csv_output}) index.html {% for content in csv_content %} <div class="row"> {% for k in content.items %} <div class="column"> <p> value is {{v}} </p> </div> {% endfor %} </div> {%endfor%} -
How to save a new column in User's model
I added a new column to my register form and admin page in Django. I'm able to register using that column, but after registration the User doesnt have that column applied when I look at admin page. It should be grade*choicefield in register form and Employee class with department var inside to save a grade from register page to department column to my database. What I'm doing wrong?? models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='media') def __str__(self): return f'{self.user.username} - プロファイル' # recreate save function of django for specified save- resized def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) # resize img.save(self.image.path) # save img class Employee(models.Model): #HERE user = models.OneToOneField(User, on_delete=models.CASCADE) #HERE department = models.CharField(max_length=100)#HERE def __str__(self):#HERE return f'{self.user.username} - プロファイル' #HERE def save(self, *args, **kawrgs): #HERE super().save(*args, **kawrgs) #HERE admin.py from django.contrib import admin from .models import Profile from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import Employee from django.contrib.auth.models import User admin.site.register(Profile) # Define an inline admin descriptor for Employee model # which acts a bit like … -
while trying to use celery with django on ElasticBeantalk with Amazon -SQS and running, I am getting [Errno 13] Permission denied?
I am trying to use celery with django. I have deployed my site on eleasticBeanStalk. I am also using AMAZON-SQS. On running the command celery worker --app=prisons --loglevel == INFO [prisons is the name of my django app & I have ran this command from eb ssh] I get the following error Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/bin/celery", line 11, in <module> sys.exit(main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/__main__.py", line 16, in main _main() File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 298, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 488, in handle_argv return self.execute(command, argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 420, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/worker.py", line 223, in run_from_argv return self(*args, **options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 252, in __call__ ret = self.run(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/worker.py", line 257, in run **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/worker/worker.py", line 101, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/worker/worker.py", line 141, in setup_instance self.blueprint.apply(self, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 214, in apply step.include(parent) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 343, in include return self._should_include(parent)[0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 339, in _should_include return … -
Django Model DateField with only year as CharField?
In my Model I need to have Date field but with only year, standard DateField want from me also month and day, so I downloaded python package named partial_date_field, which adding Date type field but month and day are optional and everything was fine until I started creating view with filter, and unfortunatelly filter dont recognize PartialDateField type. So I'm wondering if it's ok to create Year field as CharField, is this a good solution? or maybe I can help my filter to recognize this custom type field "PartialDateField"? My Model: from django.db import models from partial_date import PartialDateField class Book(models.Model): title = models.CharField(max_length=75, verbose_name='Book title') authors = models.CharField(max_length=150, verbose_name='Authors') published_date = PartialDateField(verbose_name='Publishing date') pages = models.CharField(max_length=4, verbose_name='Number of pages') language = models.CharField(max_length=2, verbose_name='Language') image = models.URLField(verbose_name='Image', default=None, blank=True) my filter: class BookFilter(FilterSet): class Meta: model = Book fields = ['title', 'authors', 'language', 'published_date'] -
Get context from QuerySet in Django
I would like to filter a QuerySet depending on User's attributes. I have a QuerySet which looks like this {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Event: Event object (1)>, <Event: Event object (2)>, <Event: Event object (3)>, <Event: Event object (4)>]>, 'event_list': <QuerySet [<Event: Event object (1)>, <Event: Event object (2)>, <Event: Event object (3)>, <Event: Event object (4)>]>, 'view': <cal.views.CalendarView object at 0x7fc7b0e062b0>} And I would like to be able to access a one value from all QuerySets. Name is a Choise*(column name in form) I'm using this code in views.py to get context(QuerySet) class CalendarView(LoginRequiredMixin, generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context -
Is there a way to authenticate a user over multiple WSGIDaemonProcesses?
I have two WSGIDaemonProcesses running on my apache server and I need users to be able to switch between them without logging in again on my Django app. One is for the HTTP server, the other for the HTTPS server. WSGIScriptAlias / /home/me/myproject/app/wsgi.py WSGIDaemonProcess https-www-my-app python-path=/home/me/myproject python-home=/home/me/myproject/venv WSGIProcessGroup www-my-app WSGIScriptAlias / /home/me/myproject/app/wsgi.py WSGIDaemonProcess www-my-app python-path=/home/me/myproject python-home=/home/me/myproject/venv WSGIProcessGroup www-my-app Is there a way that I can authenticate a user for both WSGIDaemonProcesses so that when a user goes from http://www.example.com to https://example.com they will remain logged in? Thanks for your help -
How can I store values in filtering fields in Django?
I'm trying to apply a filtering function in my website. After choosing options in the filtering fields, if you hit "Apply Filters" button, it submits the form tag and refreshes the page to bring an updated queryset. But, the fields get empy after submitting the form. The only way I think of here is use localStorage, but I was wondering if this can be done with Django. What can be the best practice to do that? -
string with negative value converted to float
I have django/python project, and a user enters a negative value as a string. But when I try to convert the string to a float I get an error. I understand that I am not using the hyphen or negative symbol but can not figure out how to replace the dash with a negative symbol. import os, sys from moneyed import Money from moneyed.localization import format_money moneystring = str('-$180.00') print Money(float(moneystring.strip("$").replace(',', '')), 'USD') Traceback (most recent call last): File "./moneytest.py", line 31, in print Money(float(moneystring.strip("$").replace(',', '')), 'USD') ValueError: could not convert string to float: -$180.00 Any Ideas? Thanks -
Cron job (using django_cron) not updating objects
I'm attempting to use a Cron Job to update the number of days each record in my database has been "open" for(ie. the number of days between today and the created date). The logic I'm using is for the cron job to run every night at 23:00 and to update the days_open field (IntegerField) by F('days_open') + 1 each time the job runs. I've set the run-time to once a minute for testing purposes. I've run "python manage.py runcrons "request_form_app.cron.DaysOpenCronJob" and " python manage.py runcrons --force" to force the jobs, and I receive no errors but the field is not updating on any of the records. settings.py 'request_form_app.cron.DaysOpenCronJob', ]``` cron.py ```from django_cron import CronJobBase, Schedule from django.db.models import F class DaysOpenCronJob(CronJobBase): RUN_EVERY_MINS = 1 # RUN_AT_TIMES = ['23:00'] schedule = Schedule(run_at_times=RUN_EVERY_MINS) code = 'request_form_app.cron.DaysOpenCronJob' def update_days(self,*args,**kwargs): data_request = Request.objects.all() for record in data_request: record.days_open = F('days_open') + 1 record.save(update_field=['days_open'])``` -
Problems with adding social_django to wagtail
I added this url in /projectname/urls.py: url(r'social-auth/', include('social_django.urls', namespace='social')), And then I added this in my wagtail homepage template (as shown in docs example): {% for name in social_auth.backends.oauth %} <li><a rel="nofollow" href="{% url "socialauth_begin" %}">{{ name|title }}</a></li> {% endfor %} But i saw nothing in template, but I have added AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) in settings/base.py. So how can I implement authentication in wagtail CMS, so users can add comments to blog? -
Why the form return 'Method not allowed' while extending CreateView CBV in DJANGO
I am not sure what is not working correctly here. I have extended the CreateView to include a form. when I try to click on submit I receive the 'error' Method Not Allowed (POST) forms.py class DateInput(forms.DateInput): input_type = 'date' class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('check_in', 'check_out') widgets = { 'check_in': DateInput(), 'check_out': DateInput() } class PropertyDetailView(DetailView): model = PropertyListing context_object_name = 'name' template_name = 'core/property-detail.html' def get_context_data(self, *args, **kwargs): context = super(PropertyDetailView, self).get_context_data(**kwargs) context['property_details'] = PropertyListing.objects.filter(pk=self.kwargs.get('pk')) # Form context['form'] = BookingForm() return context just the form HTML <form class="col-sm-3" role="form" action="" method="POST"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" value="Create" /> </form> Does anybody have an idea why? -
How to make a login view for django custom user?
I have made a custom user model using the AbstractUser , removed the username and replaced it with email and extended the model, tried creating superuser and it worked and also created some users by a signup form , logged in the admin interface and it worked however when tried to create a login form for the users it fails I tried this but it didn't work def LoginView(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('accounts:login') else: form = AuthenticationForm() return render(request,'accounts/login.html', {'form':form}) then i tried this class LoginView(FormView): form_class = AuthenticationForm template_name = 'login.html' def form_valid(self, form): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) # Check here if the user is an admin if user is not None and user.is_active: login(self.request, user) return HttpResponseRedirect(self.success_url) else: return self.form_invalid(form) Obviously i expect the user to be logged in i think the code in this post is badly formatted. mainly it's my fault as i'm new to this platform -
Signup page always redirecting to login page even if there are errors during signup
I am working on a signup page for users. It is working fine except the process when there are errors in the form introduced. After hitting the signup button, the page redirects to login with a notification saying username or password mismatch. This is the notification introduced by me into login page if there are any errors. inside views.py def signup(request): if request.method=='POST': form =SignupForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: error=form.errors return render(request,'registration/signup.html',{'error':error}) #return redirect('signup',{'error':error}) else: form = SignupForm() return render(request,'registration/signup.html',{'form':form}) my template for signup.html is: {% extends 'blog/base.html' %} {% block content %} <h2>Sign up</h2> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {% if form.errors %} <h1>Error {{error}}</h1> {{ error }} {% endif %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} path('signup/',views.signup,name='signup') path('accounts/login/',LoginView.as_view(), name='login') form for signup is: class SignupForm(UserCreationForm): first_name=forms.CharField(label="First Name",widget=forms.TextInput(attrs={'placeholder': 'First Name'})) last_name=forms.CharField(label='Last Name') #Removes the help_texts def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['password1'].help_text = None class Meta: model=User fields=('first_name','last_name','username','email','password1','password2') Why does this happen? How can I render the same signup page to user with extra information of showing errors . like **some_error** happened. Please fill out the form again. And why is this page redirecting to login page for … -
How to limit number of choices of a ManyToManyField to a specific number of choices
I am trying to build a multiple choice quizzes Django app. I have a model named Answer, and another model named Question. Here are the contents of Answer: class Answer(models.Model): text = models.CharField(max_length=255) and this is Question: class Question(BaseModel): correct_answer = models.ForeignKey('Answer', on_delete=models.CASCADE, related_name='correct_answers') other_answers = models.ManyToManyField('Answer') I want to limit the number of choices of other_answers in django-admin to 3 answers only. How to do that? Notes: I am ok with re-modeling my models. I will not use django-forms, I am only building an API for a mobile app. -
User matching query does not exist. and DoesNotExist at /messager/
The problem is that the code is written correctly to search for the user using his name, but the error is still visible, if I try to put it in the 'try' block, another error is caused. I tried to find a problem for a long time and looked at a lot of forums, but nothing helped, it’s interesting that this link doesn’t come into contact with the place where the error is caused, otherwise everything goes smoothly. The place where the error occurs. @login_required @lru_cache(maxsize=255) def showProfile(request, name): """Show user profile.""" user = User.objects.get(username=name) The place that is being called. @login_required @lru_cache(maxsize=255) def messager(request): """Show all user messages.""" render(request, 'instagrams/messager.html') I would like it to follow the transition to this template, and not an error, which, moreover, does not exist, because I tested the code in the 'manage.py shell' - there were no errors. -
Can't pass array into Django REST
I have a REST endpoint. When I access this endpoint through the DRF GUI, I can manually enter my data and it works successfully. My model looks like this: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at = models.DateField(auto_now_add=True) authors = models.ManyToManyField(User) My serializer and view looks like this: class CreatePostSerializer(CreateAPIView): serializer_class = PostSerializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'content', 'authors') When I actually try to submit my data through Ajax to the endpoint, like this: $.ajax({ type: 'POST', url: '/api/save-post/', data: { "csrfmiddlewaretoken": getCookie('csrftoken'), "title": "dasf", "desct": "dasf", "content": "fdasf", "authors": [1,2] }, success: function (msg) { console.log(msg); } }); I get an error that says: {"authors":["This list may not be empty."]} with a payload sending: title: dasf desct: dasf content: fdasf authors[]: 1 I've tried changing the contentType to application/json, I've tried almost everything but it seems like nothing is working. How can I make it so my endpoint understands what I'm sending? -
SAWarning: Unknown schema content:
What to do for this kind of warning and SAWarning: Unknown column definition ? How to rectify it? What changes are to be made in reflections.py? -
How to call a function before and after a function is called in django?
I have to check number of calls user has made to an function. I need to know what can be used i.e. Signal calls or logging. -
RuntimeError: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS for Django OAuth Toolkit
I want to access the models that are used by Django OAUTH Toolkit so I can periodically delete old tokens from the database. I thought I'd just import them: from oauth2_provider.management.commands.cleartokens import Command from oauth2_provider.models import AccessToken Command.handle() However when I try to run this file in the command line I receive the following error: Traceback (most recent call last): File ".\db_cleanup.py", line 5, in <module> from oauth2_provider.models import AccessToken File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\models.py", line 178, in <module> class Application(AbstractApplication): File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\db\models\base.py", line 95, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class oauth2_provider.models.Application doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding oauth2_provider.models.Application to my installed apps in my settings file as well but to no avail: `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'oauth2_provider', 'oauth2_provider.models.Application', 'rest_framework', 'rest_framework.authtoken', 'graphene_django', 'corsheaders', ]` I added app_label to the Application class it mentions as well, but that does not work either. -
Built-in UserCreationForm throws "The two password fields didn't match" when passwords match. Django==2.2.2
I'm setting up user registration with built-in User model and UserCreationForm. Problem is that form validation fails when proper credentials are given. And I can't understand why? It looks like form.cleaned_data lacks 'password2' for some reason. I have the same code in other project on django==2.1 and there's no problem. from django.contrib.auth.forms import UserCreationForm from django.http import JsonResponse def register_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] return JsonResponse({'username': username, 'password': password}) else: return JsonResponse({ 'error': 'Form not valid', 'messages': form.error_messages, 'cleaned_data': form.cleaned_data, 'data': form.data, }) Expected: {'username': 'test', 'password': 'qwe'} Actual: () {"error": "Form not valid", "messages": {"password_mismatch": "The two password fields didn't match."}, "cleaned_data": {"username": "test", "password1": "qwe"}, "data": {"csrfmiddlewaretoken": "long string:)", "username": "test", "password1": "qwe", "password2": "qwe"}} -
Django Rest Framework get method
I have some problems with Django rest framework. I don't know basics but it's a small piece of code that I need to do. So I have api.py that looks like: from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .thisisfile import Thisisfile class ScraperAPI(generics.RetrieveAPIView): permission_classes = [ permissions.AllowAny, ] def get(self, request): return Response({ "name": Thisisfile(), "result": True, }) What I need to do here is, to get value (name for example) that I'm defining in the get request. So this name must be passed from this API file to Thisisfile(). And to get a response like. { "user": { "name": "here is the name" }, "result": true } This is how Thisisfile looks like from rest_framework.response import Response from rest_framework import serializers import json class Thisisfile(serializers.ModelSerializer): def getsomething(name): return Response({ "name": name, }) getsomething() So to finalize the question. How to grab this name in Thisisfile and return it as a json? I know this is a stupid code for someone who knows Python but I'm not really good at it. -
Some questions about rbca in django
I have a url like: http://127.0.0.1:8000/course/17, a course associated with a teacher user, but when I change the course id like: http://127.0.0.1:8000/course/22, the user also can see this course, but they don't have association. How could I solve this bug? -
How to use value returned by javascript in onsubmit of HTML form, in Django?
This is my HTML form. There is a Javascript code define in the head tag. Assuming that the Javascript code is valid. The Javascript function returns some modified form of password. <l1> <b>Add:</b> <form action="{% url 'Student:append' %}" onsubmit="return DoPlayfair(add_password.value,ABC.value,Key1.value,'E',DupLet.value)" method="POST"> {% csrf_token %} <input type="text" name="ABC" size="42" value="ABCDEFGHIKLMNOPQRSTUVWXYZ" readonly hidden> <input type="text" name="DupLet" size="2" value="J"readonly hidden> <input type="text" name="Key1" size="33"rreadonly hidden> <label for="add_n">Name:</label> <input type="text" name="add_name" id="add_n" value=""> <label for="add_p">Password:</label> <input type="PASSWORD" name="add_password" id="add_p" value=""> <br> <input type="submit" value="add"> </form> </l1> This is my Django code. def add(request): get_name = request.POST["add_name"] get_password = request.POST["add_password"] print(type(get_name),type(get_password)) s = Student(student_name=get_name,student_password=get_password) context = { "astudent":s } s.save() return render(request,"sms_2/add.html",context) I want to use that javascript changed password in this Django view. How to access it? -
style of Django template is ignored when set as ReactJS dangerouslySetInnerHTML value
My ultimate target is to come up with Print functionality. For some reason, HTML just HAS TO BE generated on the backend. So I have the following code: <div ref={el => (this.componentRef = el)} dangerouslySetInnerHTML={{__html: this.state.htmlToPrint}}> </div> For sake of simplicity, let's assume that the htmlToPrint is just <div style='background: red'></div> Now, the problem is this inline css is ignored. And the strangest think is that when run locally, everything is fine. But after being deployed, the red effect is gone away. I have read that dangerouslySetInnerHTML can have issues with style, but why do I experience the issue only on the remote server? Does it have to do something with nginx ?