Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hide django-allauth model from admin page
I want hide all django-allauth model from admin page after I see the source code in github I see it use three models SocialAccount, SocialToken and SocialApp. now I use this to hide model from admin page and it works when I try to use it on my own model but when I use it to hide django-allauth model it doesnt work, I think I stuck on the part from x import SocialAccount, SocialToken, SocialApp because the error message is always like this ImportError: cannot import name 'SocialAccount' from 'x' I dont know the x part what to import, where to import -
Two different session value type in Django
I have one dictionary type session and one integer type session in my django request.session. It is giving me an error when it redirects to another view. The error is >>> TypeError at Object of type Product is not JSON serializable. Here is the sample session json: {'com_order_id': 59, 'cart': {'3': {'quantity': 1, 'product': <Product: Christmas With Prestige>, 'total_price': 30000, 'total_weight': Decimal('2.30')}}} If I try to delete the dict session first, it works. Storing both values is giving the error. -
Django AJAX Infinite Scroll Error on page reload
I'm trying to implement infinite scroll with django and jquery(Waypoint). Right now, i have a ListView with a pagination of 5, but when waypoint loads second page, AJAX requests are no longer performed so I added the AJAX function on the onAfterPageLoad which helps bring back AJAX function to the newly loaded page. That's fine, but then it introduces a bug to my code making the page loaded initially (First Page) no longer perform AJAX functions very well. It makes AJAX on the first page run 3 times if I just loaded a third page and makes AJAX on the second page run twice and so on depending on the number of pages loaded already. I don't know if there are any cool ways to achieve this because I tried using just jquery without waypoint, but still get same errors as I get when using just waypoint making it an error. This is kinda tricky so far. class GroupListView(LoginRequiredMixin, ListView): model = Group paginate_by = 5 context_object_name = 'groups' template_name = 'group/group_list.html' ordering = ['-date_created'] <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function () { $('.loading').hide(); $(document).ready(function(){ function updateText(btn, newCount, … -
TemplateDoesNotExist at
I am new at django. I try to 3.1.4 version django on AWS ec2-instance installed. I get error TemplateDoesNotExist at /. In my settings.py file I have added app to installed apps, and path to templates in dir. This is my base dir. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How to update data in Django when getting unique field error
first thing first I'm sorry for my bad english. I hope so u can understand me easily. I'm trying to make a blog with django but there's a place I can't solve. I used unique slug field instead of id for url, whenever I want to update the data I get the UNIQUE constraint failed: post_post.url_text error (url_text is slugfield variable name). Here is the my model, and the Form looks like this, At first I followed a way to update the data here: @login_required(login_url='login') def post_update(request, url_text=None): post = get_object_or_404(Post, url_text=url_text) form = PostWrite(request.POST or None, instance=post) if form.is_valid(): post_author = request.user post_title = form.cleaned_data.get('post_title') post_content = form.cleaned_data.get('post_content') post_tags = form.cleaned_data.get('tags') post = Post(post_author=post_author, post_title=post_title, post_content=post_content, tags=post_tags) post.save() context = { 'post': post, 'form': form, } return render(request, 'post/re_write.html', context) and I got the error I mentioned at the beginning of the post. Then I found a solution like this in the forums, if form.is_valid(): form.save() This time it does not give any error but does not update the data. Despite hours of research, for some reason I could not find a tangible solution. I wanted to ask you esteemed coders as a last resort and I look forward … -
object has no attribute 'is_valid'
I am receiving an error, object has no attribute 'is_valid', when trying to insert form data into a form. Below is the structure of my code: model.py enter image description here view.py enter image description here index.html enter image description here -
How to hide a particular attribute of a template from being inherited/included in another template in django?
For example, there are two html templates parent.html which contains button a,button b. and child.html Now I'm extending/including parent in child template and I want only button a to be inherited. How do I achieve this? -
Django Allauth - Override login
I added a field to User model. Now I want to override the django-allauth login view, so I can deny the access to a user with the state "denied". The user after registration active the account but need the admin approval before he is able to login. I have done this without allauth, but now I integrated social account from allauth and I wanted this to be centralized in one app. How can I do this with minimum interference with the native methods from django-allauth? -
from models import Event ModuleNotFoundError: No module named 'models'
from __future__ import unicode_literals from django.contrib import admin from . import models from models import Event I try to build an app from github I get into this problem y", line 6, in from models import Event ModuleNotFoundError: No module named 'models' I am not sure how to fix it.No info onlain this is the repo : https://github.com/alexpnt/django-calendar -
which hashing algorithm should I choose for django? [closed]
I see there are several in the documentation: PBKDF2 is by default and old BCrypt is a popular password storage algorithm Argon2 is the winner of the 2015 Password Hashing Competition Is there an algorithm how to choose one of them? For which situation each is better? Argon2 is the best choice for any situation? I'm not too strong in these area, I need help to choose one. -
python- Why does using a variable not yet defined in "string" manner solves the NameError?
I'm doing some Django project. class Post(models.Model): tag_set = models.ManyToManyField(Tag) class Tag(models.Model): pass The code above invokes 'NameError: name 'Tag' is not defined'. When I change the code by turning the argument into 'Tag', tag_set = models.ManyToManyField('Tag') The problem is solved. I don't know whether it is python's own mechanism or django's. Please help if you know the fundamental principle of the mechanism! -
Django filter - I want to sort the previous query and not the entire model
I use django-filter. I have a multiple choices select menu and when the user select a value, the table is sort by date or price. My PROBLEM: when I filter the table by city, for example, it works; but if I want to sort by date or price, django-filter sorts the entire model by the selected value. How can I fix this problem? -
IntegrityError at * NOT NULL constraint failed: main_post.owner_id
I want to create a PostModel(just like instagram) and while the form is created to connect the user to the model with One-to-one/foreign key relationship, anyway I'm getting a problem while trying to upload an image and the db doesn't updates. I've tried this solution ... # models.py from django.contrib.auth.models import User from django.conf import settings class Post(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) image = models.ImageField(upload_to='images') uploaded_at = models.DateTimeField(auto_now_add=True) ... # forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('description', 'image', ) def save(self, commit=True): if commit: Post.save() return Post -
How to pass multiple variables or context dictionary to context processors in Django?
I have a view called shopcart() which has multiple variables. Here's the code: def shopcart(request): category = Category.objects.all() current_user = request.user # Access User Session information shopcart = ShopCart.objects.filter(user_id=current_user.id) total=0 tax = 0 grand_total = 0 for i in shopcart: total += i.variant.price * i.quantity url = request.build_absolute_uri() domain = urlparse(url).netloc biz_id = Business.objects.get(domain_name=domain) get_tax = Tax.objects.get(business__business_id=biz_id.business_id) tax_percent = get_tax.tax_percentage tax = round((tax_percent * total)/100, 2) grand_total = round(total + tax, 2) context={'shopcart': shopcart, 'category':category, 'total': total, 'tax_percent': tax_percent, 'tax': tax, 'grand_total': grand_total, } return render(request,'shop/cart.html', context) Currently, it is sending context dictionary to only one template i.e 'shop/cart.html'. But, I want to access all the variables of this context in all the templates. I know the context processors are used to make the variables available in all templates, but not sure how to properly do it in my situation. Can anybody help me. Thanks. -
I am running into an error with an npm command in react. "ERROR in main Module not found: Error: Can't resolve ..."
I have been following a django-react tutorial and ran into a problem with the command npm run dev. I thought it was a problem with the webpack file but maybe not. [error message][1] [webpack file][2] [package.json][3] [file structure and app.js][4] [index.js][5] This is the error that I am receiving: [1]: https://i.stack.imgur.com/vCK8g.png (django_venv) C:\Users\bostm\Documents\CodingProjects\React-Django \music_controller\frontend>npm run dev > frontend@1.0.0 dev > webpack --mode development --watch [webpack-cli] Compilation starting... [webpack-cli] Compilation finished asset main.js 0 bytes [compared for emit] [minimized] (name: main) ERROR in main Module not found: Error: Can't resolve './src/index.js' in 'C:\Users\bostm \Documents\CodingProjects\React-Django\music_controller\frontend' webpack 5.10.2 compiled with 1 error in 136 ms [webpack-cli] watching files for updates... This is the webpack file. I assumed the problem was here because the error message said that it couldn't resolve "./src/index.js" in the path to the frontend directory, which is the name of the webapp folder that src/index is in. I tried using a solution from another post by using path.resolve(__dirname, /path/). It did not work so this is what I had originally. [2] const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: … -
Django input forms not showing up in my template
My problem is that when I go to my add.html page the input forms for title and textarea do not show up. For context, this is for an online course where I have to design a "wiki". This section of code is for adding an entry (a title and body content) Here is my code: views.py def create(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): title = form.cleaned_data["title"] textarea = form.cleaned_data["textarea"] entries = util.list_entries() if title in entries: return render(request, "encyclopedia/error.html") else: util.save_entry(title, textarea) page = util.get_entry(title) page_converted = markdowner.convert(page) context = dict(body=page_converted, title=title) return render(request, "encyclopedia/entry.html", context) else: return render(request, "encyclopedia/create.html", { "post": Form() }) add.html {% extends "encyclopedia/layout.html" %} {% block body %} <h1> Add Post </h1> <form action="{% url 'create' %}" method="post"> {% csrf_token %} <h6 class="post-title">Title: {{ post.title }}</h6> {{ post.textarea }} <input type="submit" value="add entry"> </form> <a href="{% url 'index' %}">View Entries</a> {% endblock %} -
django: I accidentally deleted the manage.py file. how to recover it?
I accidentally deleted the manage.py file with vim nerdtree. apparently, there isn't a way to recover it I I don't know what the hell to do. can I somehow create a new one or restore it? -
Is possible group nested objects from the same queryset?
I have a Viewset that looks like this: class EstadisticasEquipoViewSet(viewsets.ModelViewSet): """ Trae estadísticas totales de todos los equipos de una zona en una respectiva liga. """ serializer_class = EstadisticaEquiposSerializer def get_queryset(self): queryset = Estadistica_Equipo_Partido.objects.filter(id_partido__id_zona=self.request.query_params.get('id_zona')).values('id_equipo').annotate( ... tot_puntos=Sum('puntos'), prom_puntos=Avg('puntos'), prom_q1=Avg('q1'), prom_q2=Avg('q2'), prom_q3=Avg('q3'), prom_q4=Avg('q4'), tot_tiros_campo_convertidos=Sum('tiros_campo_convertidos'), prom_tiros_campo_convertidos=Avg('tiros_campo_convertidos'), ... ).annotate( ... prom_pts_poss=F('tot_puntos') / F('tot_poss'), prom_eficiencia_tiro_campo=(F('tot_tiros_campo_convertidos') + 0.5 * F('tot_tiros_3_convertidos')) / F('tot_tiros_campo_intentados') * 100, prom_true_shooting=(F('tot_puntos') / (2*(F('tot_tiros_campo_intentados') + 0.44*F('tot_tiros_tl_intentados')))) * 100, prom_eficiencia_ofensiva=(F('tot_puntos') / F('tot_poss')) * 100, prom_eficiencia_defensiva=Avg('eficiencia_defensiva'), ... ) return queryset How can I group annotate fields in this groups: promedios -> all fields that starts with prom totales -> all fields that starts with tot Actually i've this serializer: class EstadisticaEquiposSerializer(serializers.ModelSerializer): ... tot_puntos = serializers.IntegerField() prom_puntos = serializers.FloatField() tot_tiros_campo_convertidos = serializers.IntegerField() prom_tiros_campo_convertidos = serializers.FloatField() tot_tiros_campo_intentados = serializers.IntegerField() prom_tiros_campo_intentados = serializers.FloatField() porc_tiros_campo = serializers.FloatField() ... class Meta: model = Estadistica_Equipo_Partido fields = (... 'tot_puntos', 'prom_puntos', 'tot_tiros_campo_convertidos', 'prom_tiros_campo_convertidos', 'tot_tiros_campo_intentados', 'prom_tiros_campo_intentados', 'porc_tiros_campo', ... ) -
Django two same signal types
I don't understand how 2 signals executed together relate to each other. For example consider the following: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' # Overriding save method-image resizing def save(self, **kwargs): super().save(kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) # save() of parent class #Signals when a user is registered his profile is automatically updated @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile(user=instance) #could do Profile.objects.create(user=instance) instead to replace the 2 lines instance.profile.save() #reverse query I understand the following: create_profile: is my receiver function. It will do something when .save() method takes place, in our case will create a Profile instance and save it. sender: is the Model that is actually signalling this to take place. So in our case, if we want a signal to take place when the save method is executed on User model then the sender would be the User. post_save is the signal Regarding my question now. I have seen the above function broken … -
408 Request Timeout Using Apache + mod_wsgi + Python Django in Windows
I have a Django app which is deployed in local network using Apache + mod_wsgi under Windows. When I run python manage.py runserver, everything works fine. But when I start the Apache Service, I cannot access the app. The only response I get from the access.log is the error code 408. Below is my httpd.conf: LoadFile "c:/users/felix/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/felix/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/felix/appdata/local/programs/python/python37" ServerName localhost WSGIScriptAlias / "D:/dev/test_server/django/django/wsgi_windows.py" Listen 8000 <VirtualHost *:8000> WSGIPassAuthorization On ErrorLog "logs/django.error.log" CustomLog "logs/django.access.log" combined Alias /static "D:/dev/test_server/staticfiles" <Directory "D:/dev/test_server/staticfiles"> Require all granted </Directory> <Directory "D:/dev/test_server/django/django"> <Files wsgi_windows.py> Require all granted </Files> </Directory> <Directory /> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> </VirtualHost> And below is the wsgi_windows.py file: # Activate the virtualenv activate_this = 'D:/dev/test_server/.venv/Scripts/activate_this.py' exec(open(activate_this).read(), dict(__file__=activate_this)) import os # noqa import sys # noqa import site # noqa # Add the site-packages of the chosen virtualenv to work with site.addsitedir('D:/dev/test_server/.venv/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('D:/dev/test_server/django') sys.path.append('D:/dev/test_server/django/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'django.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django.settings") from django.core.wsgi import get_wsgi_application # noqa application = get_wsgi_application() I'd appreciate any ideas or hints on the issue. -
Django key error "request" when using inlineformset
I created an Class Based(CreateView) with in inlineformset. I need to pass the request.user to the form to enable a filter finction on one of the form fields. I however get a Key Error: request on the line: self.request = kwargs.pop('request') in the def init(self, *args, **kwargs): of the form. Assistance will be appreciated. Tips on my programming is also welcome. models.py: class ttransactions(models.Model): transaction_type = models.CharField(max_length=10, choices=tx_choices) description = models.CharField(max_length=50, null=False, blank=False, default='Description') transaction_date = models.DateField(default=datetime.today, db_index=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) def __str__(self): return self.description class ttransaction_lines(models.Model): transaction = models.ForeignKey(ttransactions, on_delete=models.CASCADE, db_index=True) sequence = models.IntegerField() transaction_type = models.CharField(max_length=6, choices=debit_credit) ledger_account = models.ForeignKey(tledger_account, on_delete=models.PROTECT, db_index=True) amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) quantity = models.IntegerField(blank=True, null=True) posted = models.BooleanField(default=True) forms.py: class TransactionLinesForm(forms.ModelForm): class Meta: model = ttransaction_lines fields = ['transaction_type', 'ledger_account', 'amount'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(TransactionLinesForm, self).__init__(*args, **kwargs) user = self.request.user current_company = user.current_company self.fields['ledger_account'].queryset = tledger_account.objects.filter( company=current_company) TransactionLineFormset = inlineformset_factory(ttransactions, ttransaction_lines, # fields=['transaction_type', 'ledger_account', 'amount'] , form=TransactionLinesForm, can_order=True, can_delete=True) views.py: class JournalCreateView(LoginRequiredMixin, CreateView): template_name = 'accounting/journal.html' model = ttransactions transaction_lines_form = TransactionLinesForm form_class = TransactionLinesForm success_url = '/accounting/transaction_list' def get_form_kwargs(self): kwargs = super(JournalCreateView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def get(self, request, *args, **kwargs): self.object = … -
django 3.1 user not staying logged in
So, I have a django 3.1 project and a Foo app that is going to have a user login, but I am running into the problem where users will not retain a logged in status after any additional requests. the code is similar to that below, but pretend that all relevant imports are made that are otherwise absent. views.py from django.shortcuts import render from django.contrib import auth from django.http import HttpResponseRedirect def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) if request.user.is_authenticated: return HttpResponseRedirect(reverse("Foo:stays_loggedin_check")) return render(request, template_name="Foo/loginfailed.html") return render(request, template_name="Foo/login.html") def stays_loggedin_check(request): if request.user.is_authenticated: return render(request, template_name="Foo/staysloggedin.html") return render(request, template_name="Foo/weirdly_doesnt_stay_logged_in_despite_documentaion.html") urls.py from django.urls import path from . import views app_name = "Foo" urlpatterns = [ path("login", views.login, name="login"), path("shouldnt_need_to_do_this", views.stays_loggedin_check, name="stays_loggedin_check"), ] When one fills out the login form at Foo/login.html incorrectly it, as expected, renders the page Foo/loginfailed.html. but when filled out correctly this form returns Foo/weirdly_doesnt_stay_logged_in_despite_documentaion.html. Is there a way to model behavior to be in line with django documentation where this will return Foo/staysloggedin.html instead? -
Django Class Base Views - muti model query
I am trying to create a class-based view that needs to query two models and render a joined context. Can someone please suggest how to achieve it in CBV? Example: Models: class model1(models.Model): number= models.CharField(max_length=16, null=True) location= models.CharField(max_length=64, null=True) status = models.CharField(max_length=64, null=True) class model2(models.Model): macaddress = models.CharField(max_length=64) unitnumber= models.CharField(max_length=64) device_number= models.ForeignKey(model1, default=1) How to create a class base view that will return a context which I can render to display all the 5 different fields of the two tables, mapped by 'number' filed indeed. -
How to disable a particular link after used once?
Here Admin invites the user by the email, firstname, lastname and username. After user saved with (is_active=False), a link will be send to the user email address. After clicking the link user will be redirected to a view where the user can set a new password for them. What I want is, the url which will be used to set a new password should not be valid once a user sets a new password. Right now when the user sets a new password through a url, user can use the same url to reset the password again. I want to invalid this url once a user sets a new password. OR what another approach will be better in this case while inviting a new user ? urls path('set/<uidb64>/<new_token>/password/', views.set_user_password, name='set_user_password'), path('confirm/user/<uidb64>/<token>/', views.activate_account, name="activate_user"), views class AddUser(View): template = 'user/add_user.html' form = AddUserForm def get(self, request): return render(request, self.template, {'form': self.form()}) def post(self, request): form = self.form(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() # sending email subject = "New User Invitation" context = { 'user': user, 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user=user), } message = render_to_string('user/user_invitation_email.html', context) send_email.delay(subject, message, settings.EMAIL_HOST_USER, user.email) return redirect('dashboard:users_list') return render(request, self.template, {'form': form}) … -
Django override the error message that Django shows for UniqueConstraint error?
I want to customize Meta class constraints default message. Here is my model that I have been working out. class BusRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) shift = models.ForeignKey( Shift, null=True, on_delete=models.PROTECT ) journey_length = models.TimeField(null=True) class Meta: default_permissions = () verbose_name = 'Bus Route' verbose_name_plural = 'Bus Routes' constraints = [ models.UniqueConstraint( fields=['route', 'shift'], name='unique_bus_company_route' ) ] The default constraint error message is as following Bus Route with this Shift already exists. Is there any way out I can customize this constraint message to something like, Bus Route and shift already in use please validate again