Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create() takes 1 positional argument but 2 were given
I'm using Django and allauth trying to get a signup page working but for some reason it does not work. Whenever I have entered all the sign up data that's required and press Create an account it gives me this error; TypeError at /accounts/signup/ create() takes 1 positional argument but 2 were given This is my signup script; {% extends "account/base.html" %} {% load i18n %} {% load crispy_forms_tags %} {% block head_title %}{% trans "Signup" %}{% endblock %} {% block content %} <main> <div class="container"> <section class="mb-4"> <div class="row wow fadeIn"> <div class='col-6 offset-3'> <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class='btn btn-primary' type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </section> </div> </main> {% endblock %} -
How to fix NoReverseMatch? Reverse for 'porumbei' not found. 'porumbei' is not a valid view function or pattern name
I'm trying to edit some objects in django but when I'm accessing the view for editing it says that reverse not found. I've read almost all articles about noreversematch but none answered to my question. I'm new to django and maybe that could be the reason. Can anyone help me to fix that? Thanks! My code bellow. My view: @login_required(login_url='/auth/login/') def editareporumbei(request, pk): """ Pagina editare informatii porumbel """ global semi_frati sts = StatusPorumbei.objects.all() porumbel = get_object_or_404(Porumbei, pk=pk) if porumbel.crescator != request.user: raise PermissionDenied() descendenti = Perechi.objects.filter(Q(mascul=porumbel) | Q(femela=porumbel)) if porumbel.tata and porumbel.mama: frati = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))).exclude(serie_inel=porumbel) rude_tata = Porumbei.objects.filter(Q(Q(tata=porumbel.tata)) & ~Q(Q(mama=porumbel.mama))) rude_mama = Porumbei.objects.filter(~Q(Q(tata=porumbel.tata)) & Q(Q(mama=porumbel.mama))) vitregi = rude_tata | rude_mama semi_frati = vitregi.distinct() else: frati = None semi_frati = None try: rating_porumbel = Rating.objects.get(porumbel=porumbel) except Rating.DoesNotExist: rating_porumbel = None if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES, instance=porumbel) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return redirect('/porumbei/vizualizare') else: form = AdaugaPorumbel(instance=porumbel) context = { 'form': form, 'porumbel': porumbel, 'descendenti': descendenti, 'rating_porumbel': rating_porumbel, 'sts': sts, 'frati': frati, 'semi_frati': semi_frati, } template = loader.get_template("editare-porumbei.html") return HttpResponse(template.render(context, request)) My urls: urlpatterns = [ path('porumbei/vizualizare/', porumbei.views.viewpigeons, name='allpigeons'), path('porumbei/adaugare/', porumbei.views.porumbelnou, name="porumbelnou"), path('porumbei/editare/<int:pk>/', porumbei.views.editareporumbei, name='editareporumbei'), ] Template: <a href="{% url 'editareporumbei' … -
List objects of logged current user
I would like to ask how I could list all objects of logged current user via class based view in django. I have two apps in the project. One is called users and the other one is badminton. users/models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) badminton/models.py from django.db import models from users import models as users_models class Player(models.Model): name = models.OneToOneField(users_models.Profile ,null=True, on_delete=models.CASCADE) matches_played = models.IntegerField(default=0, blank=True, null=True) class Match(models.Model): player_home = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_home') player_away = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_away') How I can access all matches of logged user via queryset? Thank you for your help! -
Cannot find template url in django
I have this project structure, foo_project - templates - base.html - photo_list.html - photo_create.html - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - photo - __init__.py - admin.py - apps.py - models.py - tests.py - urls.py - views.py In apps.photo.views.py, from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.views.generic.detail import DetailView from .models import Photo class PhotoList(ListView): model = Photo template_name_suffix = '_list' class PhotoCreate(CreateView): model = Photo field = ['title', 'body', 'created', 'image'] template_name_suffix = '_create' success_url = '/ in foo_project/settings.py from os.path import abspath, dirname, join BASE_DIR = dirname(dirname(abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In foo_project/urls.py, from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static urlpatterns = [ path('', include('apps.photo.urls')), ] photo.urls, from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import PhotoList, PhotoCreate, PhotoDelete, PhotoDetail, PhotoUpdate app_name = 'photo' urlpatterns = [ path('', PhotoList.as_view(), name='index'), path('create/', PhotoCreate.as_view(), name='create'), ] When I hit the localhost:8000, it cannot find my template photo/photo_list.html, but I don't see anything missing. … -
TemplateDoesNotExist at / error in Django
I'm new to Django, and trying to create my first project. I tried to resolve the above mentioned error, spent hours banging my head against the wall, but was unable to correct it.. Given below are the relevant files. I guess it must be a small thing that I am missing, but unable to pin point it. Views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from datetime import timedelta def home(request): if request.GET.get('type') == 'formdata': options = {'fruits': [], 'vendors': [], 'release_version': []} try: options['fruits'] = ['Mango', 'apple', 'banana'] options['vendors'] = ['Amazon', 'flipkart', 'myntra'] options['release_version'] = ['2015','2016','2017','2018'] today = datetime.today() options['end_date'] = today.strftime('%Y-%m-%d') last_week_date = today - timedelta(days=7) options['start_date'] = last_week_date.strftime('%Y-%m-%d') return JsonResponse({'options': options}) except: return JsonResponse({'message': 'An error occured while getting form data'}) return render(request, 'index.html') else: return render(request, 'index.html') Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home') ] The index.html is the template I want the urls.py to point to, and is in the templates/project_name folder in my project. I have also set the TEMPLATES_DIR in the settings.py. I wonder where I am going wrong. Any help is appreciated. -
Django- how to use server time in views when retrieving data from different timezone?
I have set a timezone in America in settings.py. All data are set in American Timezone in database. If today's date in America is 14 march but in Asia it's 15 March. So if I retrieve today's object from Asia it's not showing anything because it is stored in American time which is 14 march and in Asia it's 15. So it is not showing anything. So how to use server time in views.py so that it will retrieve object based on server time no matter where you stay -
Django let's you go back after logout and see the previous pages
I just noticed that, in Firefox, if you go back to the previous pages after logging out, you are still able to see the pages you navigated. As soon as you click to another page you are asked to login, but if you don't click anything you are able to navigate the pages you used while logged in. Has anyone seen this behaviour and was able to solve it? -
Using environment variables for mysql database password and host throws errors
I'm trying to set up a mysql database and secure sensitive information in an .env file. I was able to successfully store the database NAME, but using environment variables for the PASSWORD and HOST throws two different errors: Error for PASSWORD: Exception Type: OperationalError at / Exception Value: (1045, "Access denied for user 'studio413'@'10.0.0.32' (using password: NO)") Error for HOST: AttributeError at / 'NoneType' object has no attribute 'startswith' Putting the actual PASSWORD and HOST directly into the settings.py works perfectly, and I believe I've properly set up the environment variables, as the database NAME works fine. Typing echo $DATABASE_PASSWORD and echo $DATABASE_HOST into my console yields the correct information from my .env file. I'm using PythonAnywhere and followed the instructions for setting up environment variables here: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps/ If it helps, here is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'studio413$default', 'USER': os.getenv("DATABASE_USER"), 'PASSWORD': os.getenv("DATABASE_PASSWORD"), 'HOST': os.getenv("DATABASE_HOST"), } } If anyone could help me solve this, I would greatly appreciate it! Note: I tried providing the full traceback for each error, but stackoverflow would not let me post them (it thought I was posting spam). -
Testing multiple viewport sizes with Django/Selenium
I'm trying to test characteristics of certain UI elements given different viewport sizes and media defined in CSS. I have a setup function to instantiate a headless Chrome browser with I believe a default viewport size of 800x600: class NewDesktopVisitorTest(StaticLiveServerTestCase): def setUp(self): self.chrome_options = Options() self.chrome_options.add_argument('--headless') self.browser = webdriver.Chrome(options=self.chrome_options) This works well for testing what I would consider the desktop version of a page, but I'd also like to make sure the mobile version renders as I'd expect. I can create a completely separate class with a different setup and specify the viewport size like so: class NewMobileVisitorTest(StaticLiveServerTestCase): def setUp(self): self.chrome_options = Options() self.chrome_options.add_argument('--headless') self.chrome_options.add_argument('--window-size=375,800') self.browser = webdriver.Chrome(options=self.chrome_options) This has the benefit of very cleanly showing where a given test is failing (i.e. desktop or mobile). The trouble is that I want the exact same tests to run against both (and potentially multiple) viewport sizes, and I don't want to have to maintain the exact same tests in multiple classes. Most of my searches for parameterized testing yield solutions for running the same tests against different data sets, but I've yet to find examples of solutions for setting up and running the same tests against multiple starting configurations. I'm hesitant … -
Have to use model name instead of field name when queriyng ManyToManyField from django model
I have the following model: class ShoppingList(models.Model): name = models.CharField(max_length=100, default='Main') owners = models.ManyToManyField(User, through='ListOwner') class ListOwner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) shopping_list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE) is_main_owner = models.BooleanField(default=False) Next, I'm trying to query ShoppingList for the current user. I used this https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships as an example. I expected that right way to do it is to use this construction: @login_required def index(request): shopping_list = ShoppingList.objects.filter(owners__user=request.user)\ .order_by('id').first() # something else but in this case, I get an error: Related Field got invalid lookup: user Everything works fine if use listowner instead of owner in filter() function like this: shopping_list = ShoppingList.objects.filter(listowner__user=request.user)\ .order_by('id').first() Can anybody please explain to me why the first one isn't working (while it is recommended to use it in Django documentation)? -
Integration with paypal redirect issue
I am integrating paypal with my openedx ironwood install. To implement ecommerce capabilities - openedx ironwood uses django oscar shopping cart. It works to the point where one can enter their credit card information and submit the form. However after submitting the form the following error occurs and this is the corresponding address in the address bar: https://http/payment/paypal/execute/?paymentId=PAYID-LZWTHVY60U970153W662623L&token=EC-45D081042G524235T&PayerID=UBRT2SFRKASXL Any idea on how I can fix this? -
Extending UserCreationForm new field doesn't appear in admin pannel
I am adding a new field to django UserCreationForm. Everything is working fine - I can see the new fields in the html form but when I open django admin panel the new field is not there. Any ideas what am I missing? forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserSignupFrom(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) is_worker = forms.BooleanField(required=False) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'is_worker', 'password1', 'password2'] views.py from django.shortcuts import render from django.http import HttpResponse from .forms import UserSignupFrom from django.contrib import messages def sign_up(request): if request.method == 'POST': form = UserSignupFrom(request.POST) if form.is_valid(): form.save() messages.success(request, 'account was created') else: form = UserSignupFrom() return render(request, 'login/sign_up.html', {'form': form})``` if you need to see some other files please let me know! -
Wagtail CMS not rendering navigation icons/images
I've recently taken over working on a Django/Wagtail app that has a few bug that needs fixing. One of which is the icons/images in the CMS are not displaying in the menus and throughout the entire CMS, which is making navigation confusing for the users. Anyone have insights as to why fonts etc are loading, but not the icons (see image below for one example) Wagtial CMS Rendering Issue -
How do I pass a boolean for each post in my function view?
My views.py def problems_list(request): queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31']) def is_liked(self): is_liked = False if self.likes.filter(user=request.user.username).exists(): is_liked = True return is_liked context = { 'posts': queryset, 'is_liked': is_liked } return render(request, 'main/problem.html', context) I want each post to have a variable is_liked that is True or False so that I can pass it in my html. -
Is there are difference between working with Django vs Django on Anaconda
I am learning Django and I saw that you can install it regularly, according to the Django documentation. But I also saw that you can work with it in Anaconda. Is there a difference in developing? Or is it all just the same. Thanks -
how to customize django jwt graphql authentication
Hi I'm trying to customize jwt graphql Django default authentication I need to achieve log in with username or email normal Django we customized authentication backend. mutation{ tokenAuth(username:"myemail@email.com" password:"pass") { token } } Authenticate with username mutation{ tokenAuth(username:"myname" password:"pass") { token } } the normal username is working fine. how I can authenticate the user by username or email in jwt graphql I tried this link https://django-graphql-jwt.domake.io/en/latest/customizing.html I don't get any idea about that... Does anyone have any idea about that?? -
How to build Bootstrap collapse (dropdown) plugin in Django-CMS 3.x?
Building plugins in Django-CMS 3.x is wonderfully documented. It would be awesome if I was able to drag some of my custom plugins and nest them into a dropdown (Bootstrap 4 Collapse). Initially, I figured I could just have a placeholder in a custom model and drag other plugins into that placeholder. But that doesn't fly. Anyone have a suggestion on how to get this done? -
CORS fonts Issue Google Cloud Storage with Django application
I just deployed a Django app, using Django Storages which is connected to a Google Cloud bucket of mine. But I am getting these CORS errors in my console (** resembles my domain, just removed it for safety): Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff2' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff2 net::ERR_FAILED Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.woff net::ERR_FAILED Access to font at 'https://storage.googleapis.com/**_static/static/css/fontawesome/webfonts/fa-solid-900.ttf' from origin 'https://**.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/**/static/css/fontawesome/webfonts/fa-solid-900.ttf net::ERR_FAILED I followed this SO post and answer: https://stackoverflow.com/a/39758208/10938976 Settings the CORS rules for my bucket like this: [ { "origin": ["*"], "responseHeader": ["Content-Type"], "method": ["GET"], "maxAgeSeconds": 3600 } ] But it does not fix my problem, even after recollecting all my static files, I still get the same error. What is going wrong? -
Django Choice Field initial value ignored when form is rendered
I'm running into an issue where I set the initial value on a Choice field for County but when I render the form, the corresponding option doesn't render as selected. I can't figure out why this isn't working. Does anyone have any ideas? Models.py class State(models.Model): name = models.CharField(max_length=30, db_index=True) abbreviation = models.CharField(max_length=2, unique=True, db_index=True) class County(models.Model): name = models.CharField(max_length=30, db_index=True) state = models.ForeignKey(State, on_delete=models.CASCADE) Forms.py class MyForm(forms.Form): state = forms.ChoiceField(choices=[], required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) county = kwargs.get('county') state_qs = State.objects.all().values('id', 'name', 'abbreviation') state_choices = [ (choice['id'], f"{choice['name']} ({choice['abbreviation']})") for choice in state_qs] self.fields['state'].choices = [('', '---------')] + state_choices county_qs = County.objects.select_related('state').filter(state__id=state).order_by( 'name').values('id', 'name', 'state', 'state__abbreviation') county_choices = [ (choice['id'], f"{choice['name']}-{choice['state__abbreviation']}") for choice in county_qs] initial = None if county: initial = county.id self.fields['county'] = forms.ChoiceField(choices=county_choices, initial=initial) -
What is the propper way to handle certain CRUD exceptions in Django
I have these models. class Brand(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=100, null=False, blank=False) class Ingredient(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=100, null=False, blank=False) cost = models.DecimalField(max_digits=14, decimal_places=2, null=False) class Meta: unique_together = ['account', 'brand', 'name'] So sometimes a name for the same brand and account might be repeaten. Should I handle these constraint exceptions in views, in forms? What is the more clean way to do it? Django is really versatile and you can do things in many different ways. -
Django - ModuleNotFoundError
I'm trying to import a python file from another python file in Django. There is a function I want to call from the other file, but every time I import the file I get an error. Traceback (most recent call last): File "ams/faces-train.py", line 6, in <module> from ams.conn import conn ModuleNotFoundError: No module named 'ams' Could someone kindly tell me what the problem is?? I have tried everything but I have not been able to fix it, does anyone know have a work around to this problem?? -
Python & Django tips
I am starting a new project, which would teach math online, I want to build a web based (probably django) app, which would include videos, interactive excersises and online store, where you can purchase the online course. I have experience with coding, just not in this field. I am hoping you could give me some tips on what resources should I use to learn, and if I can build this app purely in django, or if there is a better option, Sorry if this question is too broad, I honestly just don't know where to start. Thank you -
UNIQUE constraint failed: user_profile.StudentID error
I am getting this error(IntegrityError at /register/) every time I try to create a new user. In user creation form I am creating both User and profile. here is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.CharField(max_length=8,unique=True) Branch = models.CharField(max_length=255,choices=Departments,default="CSE") YearOfStudy = models.IntegerField(default=1) ContactNumber = PhoneField(help_text='Contact phone number') image = models.ImageField(default='default.jpeg' , upload_to='profile_pics') parentsContactNumber = PhoneField(help_text="Parent's phone number") def __str__(self): return f'{self.user.username} Profile' here is forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username','email','first_name','last_name','password1','password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ['StudentID','Branch','YearOfStudy','ContactNumber'] here is views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) form1 = ProfileCreationForm(request.POST) if form.is_valid() and form1.is_valid(): form.save() form1.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() form1 = ProfileCreationForm() context = { 'form': form, 'form1': form1 } return render(request, 'user/register.html', context) here is register.html {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">JOIN TODAY</legend> {{ form|crispy }} {{ form1|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> </div> {% endblock content %} please help me … -
i am trying to add functionality like/dislike without page refresh in django
i am trying to add functionality like/dislike without page refresh but i can not set the logic here is my models.py file code from django.db import models # Create your models here. class EmployeeDetail(models.Model): emp_fname = models.CharField(max_length=50, default="") emp_lname = models.CharField(max_length=50, default="") emp_uname = models.CharField(max_length=100, default="") emp_email = models.EmailField(max_length=254, default="") emp_password = models.CharField(max_length=100, default="") emp_dob = models.DateField(max_length=50, default="") emp_doj = models.DateField(max_length=50, default="") emp_designation = models.CharField(max_length=100, default="") emp_salary = models.IntegerField() emp_leaves = models.IntegerField() emp_contact = models.CharField(max_length=12, default="") emp_photo = models.ImageField(upload_to="employee/images", default="") def __str__(self): return self.emp_fname class Post(models.Model): emp_id = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.CharField(max_length=150) content = models.TextField() author = models.CharField(max_length=15) timeStamp = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) def __str__(self): return self.title + ' by ' + self.author class Preference(models.Model): user_id = models.ForeignKey(EmployeeDetail, on_delete=models.CASCADE) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.IntegerField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user_id) + ':' + str(self.post_id) + ':' + str(self.value) and my urls.py code blow here from django.urls import path from .import views urlpatterns = [ path('', views.login, name='Login'), path('logout', views.logout, name='Logout'), path('employee/home/', views.home, name='Home'), path('employee/manageuser/', views.manageuser, name='manageuser'), path('employee/blank/', views.blank, name='blank'), path('employee/font_awesome/', views.font_awesome, name='fontawesome'), path('employee/map_google/', views.map_google, name='map google'), path('employee/not_found/', views.not_found, name='map google'), path('employee/register/', views.register, name='Registration'), path('employee/employee_profile/<int:id>', views.employee_profile, name='Employee Profile'), path('employee/delete_employee/<int:id>', views.delete_employee, … -
upload_to attribute is being overwritten by unknown source
upload_to attribute is being overwritten and I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should be just 'img/posts'. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media)