Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'User' object is not subscriptable
I created a form to set let the user changes their password, but I got this message: 'User' object is not subscriptable. I'd like to know how to change it properly. here's the part of my code. view.py def alterar_senha(request, user_username): if request.method == 'GET': form = AlterarSenha() context = { 'form': form, } return render(request, 'usuarios/administrativo/alterar_senha.html', context) elif request.method == 'POST': usuario = User.objects.get(username=user_username) form = AlterarSenha(request.POST) context = { 'form': form, } senha = request.POST.get('password') senha1 = request.POST.get('new_password1') senha2 = request.POST.get('new_password2') print(senha1, senha2) if not usuario.check_password(senha): form.add_error('password', 'Senha inválida!') id = usuario.id if form.is_valid(): user = usuario[id] user.set_password('senha') user.save() return redirect('logout') else: print(form.errors) return render(request, 'usuarios/administrativo/alterar_senha.html', context) forms.py class AlterarSenha(forms.Form): password = forms.CharField(label='Senha atual', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite sua senha", 'name': 'senha1' } )) new_password1 = forms.CharField(label='Nova senha', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite sua senha", 'name': 'password1' } )) new_password2 = forms.CharField(label='Repita a Senha', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': "Digite novamente", 'name': 'password1' } )) def clean(self): new_password1 = self.cleaned_data.get('new_password1') new_password2 = self.cleaned_data.get('new_password2') lista_erros = {} checa_senha(new_password1, new_password2, lista_erros) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data def save(self, commit=True): user = User.objects.create_user( password=self.cleaned_data['new_password1'] ) return user … -
Apache2 Ubuntu Server Module not found 'django'
I have been trying to move a django project on my Linode server into production. After trying to use Apache and wsgi by following an online tutorial by Corey Schafer, I have encountered the following problem. I cannot for the life of my understand why this is happening, and have included error logs, my wsgi.py and my .conf file below. [Tue Sep 29 23:20:35.753537 2020] [wsgi:error] [pid 143850:tid 140318623627008] [remote 90.214.108.58:50288] from django.core.wsgi import get_wsgi_application [Tue Sep 29 23:20:35.753556 2020] [wsgi:error] [pid 143850:tid 140318623627008] [remote 90.214.108.58:50288] ModuleNotFoundError: No module named 'django' [Tue Sep 29 23:28:18.507904 2020] [mpm_event:notice] [pid 143849:tid 140318652456000] AH00491: caught SIGTERM, shutting down [Tue Sep 29 23:28:18.590367 2020] [mpm_event:notice] [pid 143989:tid 139664706964544] AH00489: Apache/2.4.41 (Ubuntu) mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Tue Sep 29 23:28:18.590439 2020] [core:notice] [pid 143989:tid 139664706964544] AH00094: Command line: '/usr/sbin/apache2' [Tue Sep 29 23:28:24.089588 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] mod_wsgi (pid=143990): Failed to exec Python script file '/home/myname/projects/uw5-backend/u> [Tue Sep 29 23:28:24.089643 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] mod_wsgi (pid=143990): Exception occurred processing WSGI script '/home/myname/projects/uw5-b> [Tue Sep 29 23:28:24.095135 2020] [wsgi:error] [pid 143990:tid 139664678135552] [remote 90.214.108.58:50411] Traceback (most recent call last): [Tue Sep 29 23:28:24.095172 2020] [wsgi:error] [pid 143990:tid … -
I tried to login an existing user in my webpage, but i'm getting 'AnonymousUser' object has no attribute '_meta'
` 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) return redirect('/') else: messages.info(request, 'Invalid Credentials!') return redirect('login') else: return render(request, 'login.html' ` -
Geoserver unavailable in Geonode instalation after restarting Tomcat
I have installed geonode in a production server and it was working correctly after i execute: systemctl restart tomcat.service After this geoserver stop working. If i open the url mydomain.org/geoserver appears a tomcat 404 status. Maybe after the restart the webapp is not linked correctly? Any idea why this is? Thanks -
Django as back-end with Flutter as front-end
I was wondering how to develop a Flutter front-end (iOS & Android) along with Django for the back-end. I partially have both done separately and want to know how to connect them together. I appreciate any tips and advice, as well as if you have any recommendations for server service (Google console, Firebase, or Heroku). Thank you -
How to solve Django ManyToMany relationship with 2 levels
I have a structure like this in Django 1.11: class Profile(models.Model): username = models.CharField() class Post(models.Model): profile = models.ForeignKey(Profile) hashtag = models.ManyToManyField(Hashtag) class Hashtag(models.Model): name = models.CharField() Now this creates intermediate table post_hashtag, but how can I access all hashtags using profile.hashtags.all()? -
i want send all parameters of contact form through email django
def sales_inquiry(request): if request.method=="POST": name = request.POST["name"] company = request.POST["company"] email = request.POST["email"] contact = request.POST["contact"] package = request.POST["package"] mode = request.POST["mode"] pieces = request.POST["pieces"] gross = request.POST["gross"] country_origin = 'country_origin' in request.POST country_destination = request.POST["country_destination"] port_origin = request.POST["port_origin"] port_destination = request.POST["port_destination"] commodity = request.POST["commodity"] container = request.POST["container"] length = request.POST["length"] height = request.POST["height"] width = request.POST["width"] send_mail('Inquiry form', name, settings.EMAIL_HOST_USER, ['17201073suchan@viva-technology.org'], fail_silently=False) return render(request,'laxmi/sales_inquiry.html') now i am able to send only name in my mail body but i want to send this all attributes of this inquiry form to my mail id how should i make dict or any other option to send this whole content -
TypeError at /add-to-cart/1/
my add to cart was working fine and when i retry few pages later it gaves me that error TypeError at /add-to-cart/1/ add_to_cart() missing 1 required positional argument: 'request' My view: def add_to_cart(LoginRequiredMixin, request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") my url: urlpatterns = [ path('add-to-cart/<slug>/', add_to_cart, name='add_to_cart'), ] Not sure what went wrong, help please. -
How can I assign a model to all users upon creation in Django?
I have this model: models.py class Upload_model(models.Model): content=models.CharField(max_length=200) user_name=models.ForiegnKey(User) forms.py class upload_form(ModelForm): class Meta: model=Upload_model fields=[“content”] views.py def upload_all_user_models(request): if request.method==”POST”: form=upload_form(request.POST, request.FILES) instance=form.save(commit=False) instance.user_name=User.objects.all() return redirect(“upload_all_user_models”) else: form=upload_form() return render(request,”uploadpage.html”,{“form”:form}) I want the Upload_model to be assigned to all users upon creation but I seem to be getting a ValueError. How can I solve this? -
Django Admin - Cannot change <h2> color
I am learning Django. I am customizing the Django Admin page. I have created a base_site.html file in my templates to overwrite the default admin html. Additionally, I have created a stylesheet that I've tied to it. Here's my problem: By default, there is a div on the right side of the content with an h2 header that states "Recent Actions." I want to change this texts color, but my CSS won't seem to work on these words... <div id="content-related"> <div class="module" id="recent-actions-module"> <h2>Recent actions</h2> <h3>My actions</h3> <p>None available</p> </div> </div> I have tried each of the following CSS: #content-related{ color: blue; } .module h2{ color: blue; } #recent-actions-module h2{ color: blue; } #content related h2{ color: blue; } Nothing works... Am I missing something? -
Cannot end "Invalid HTTP_HOST header:" emails [Django/Nginx]
I have been following the Stack Overflow responses about how to end the "Invalid HTTP_HOST header:" emails I receive through Django, but I have not had any luck. I have added the following to my Nginx sites-available configuration, but it hasn't had any effect. This is my current configuration: server { server_name ceemess.com www.ceemess.com; client_max_body_size 4g; location /static/ { alias /webapps/ceemess/cemess/frontend/; } if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } location / { proxy_set_header Host $host; proxy_pass http://0.0.0.0:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_http_version 1.1; proxy_set_header Connection ""; add_header P3P 'CP=ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/ceemess.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/ceemess.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.ceemess.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = ceemess.com) { return 301 https://$host$request_uri; } # managed by Certbot if ( $host !~* ^(ceemess.com|www.ceemess.com)$ ) { return 444; } server_name ceemess.com www.ceemess.com; listen 80; return 404; # managed by Certbot } As you can … -
Polymorphic relationships in Django
In Django, how can I create a model that belongs to several models without having to create a foreign key field for each model? Example: An Observation model that is related to any model that can be Observable (Request, Document, Quiz, etc). I've tried contenttypes and it works fine in the shell but I've had problems working with serializers in django rest framework and I'd like to know if there's another way to do it or some package that is useful. Thank you. -
How to connect two existing tables by selected field with django?
I want to make a relationship one to one between the tables by a selected field. I have parcel data with identification field and table with permission attributes containing other data, referencing to parcel identification ield. I am trying to connect these tables with one to one: class Parcels(models.Model): identification = models.CharField(max_length=100,unique=True) area = models.FloatField() class Permissions(models.Model): permission_number = models.Charfield(max_length=40) identification = models.CharField(max_length=50) parcels = models.One(Parcels, to_field='identification',null=True, blank=True, on_delete=models.CASCADE) then I am encapsulating the Parcel serializer in Permissions serializer to be sent to django REST_API. However this does not work. The idea here is that I am periodically adding Permission data to database and need to automatically join the parcel data by identification number. How can I do it in django? -
nginx + uwsgi Django REST response body missing only on some corporate networks
I have a React + Django application deployed using nginx and uwsgi on a single centOS7 VM. The React app is served by nginx on the domain, and when users log in on the javascript app, REST API requests are made to the same nginx on a sub domain (ie: backend.mydomain.com), for things like validate token and fetch data. This works on all recent version of Firefox, Chrome, Safari, and Edge. However, some users have complained that they could not log in from their work network. They can visit the site, so obviously the javascript application is served to them, but when they log in, all of the requests come back with status 200, except the response has an empty body. (and the log in requires few pieces of information to be sent back with the log in response to work). For example, when I log in from where I am, my browser's network tab looks like the screenshot below: You can see that the validateToken end point responds with status=200, and a json object with few parameters. But when one of the users showed me the same from their browser, they get Status=200 back, but the Response is empty. … -
Celery task in which need to update field after 1 month pass after creation
Idea is create celery task, in which after 1 month from creation (created_at field) update price field with 5% discount. Model: class Product(models.Model): price = models.DecimalField(max_digits=15, decimal_places=2, help_text="Current price of products") old_price = models.DecimalField(max_digits=15, decimal_places=2, help_text="Old price of products", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) -
Ruby to Django Conversion
I want to convert a backend written in Ruby to Django. I know Django, I already familiarize myself with Ruby syntax but I am sure it is not enough. I appreciate any tips and advice. Thank you -
No redirection occurs after form validation
Faced a problem that I can't solve, who knows, please help.I have 2 forms on the page, these forms are from two different models (User and Profile). The problem is that one form always fails validation, even if it is filled out correctly, because of this I cannot use success_url, and I really need to redirect the user to a new slug, how can I redirect the user differently? For some reason after the first check my object disappears, if I use the condition "if object.user == user", without this condition the object appears file views.py: class ProfilePage(FormView): template_name="market/profile.html" form_class=ProfileUpdateForm second_form_class= UserUpdateForm success_url="profile" def get(self, request, *args, **kwargs): context = self.get_context_data(object=get_object_or_404(Profile,slug=self.kwargs['slug'])) print(context) return self.render_to_response(context) def get_context_data(self, **kwargs): context = super(ProfilePage,self).get_context_data(**kwargs) context['UserUpdateForm'] = UserUpdateForm( prefix='UserUpdateForm', data = self.request.POST if bool(set(['UserUpdateForm-submit-counter-bid', 'UserUpdateForm-submit-approve-bid', 'UserUpdateForm-submit-decline-further-bids']).intersection( self.request.POST)) else None, instance=self.request.user, ) context['ProfileUpdateForm'] = ProfileUpdateForm( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) return context def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) if context['UserUpdateForm'].is_valid(): context['UserUpdateForm'].save() elif context['ProfileUpdateForm'].is_valid(): context['ProfileUpdateForm'].save() return self.render_to_response(context) file profile.html: <p>{{object}}</p> {% if object.user == user %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{ UserUpdateForm.as_p }} <input type="submit" name="{{ UserUpdateForm.prefix … -
DRF: How to prefetch a queryset for my properties?
I have a lot of properties on my model Author. Each of them uses self.book_set. class Author(models.Model): #.... @property def book_impressions(self): return self.book_set.aggregate(Sum("impressions").get("impressions__sum") or 0 @property def book_reach(self): return self.book_set.aggregate(Sum("reach").get("reach__sum") or 0 # more @property here... class Book(models.Model): author = models.ForeignKey(Author) reach = models.IntegerField() impressions = models.IntegerField() # .... I have a view responsible for retrieving a single Author. As you might imagine the database is hit very often. Where is the right point to insert my prefetch_related? -
Formatting checkboxes in django
i'm trying to add some checkboxes into my form and to make them look nice. The thing is that when I use {{form.checkBoxFilter}} the output is like: I would like to have them inline and readable, unfortunately using crispy forms renders them too close to each other. I found that looping through elements will place them inline but still they're close to each other (their labels are much longer than shown below). {% for x in filter.weights%} {{x}} {%endfor%} Where to put my css in this case? -
Best way to use simple asynchronous queues in django?
I need my django view function to trigger a task which will then run in the background, not blocking the response. def my_task(client_information, unique_id): # task #do something that takes a while def my_view(request): # django view client_information = request.GET.get('whatever') # get some information passed from the client unique_id = generate_unique_id() # generate a unique ID for this task start_task(client_information, unique_id) # the interesting part: start the task with client information and unique id, but non blocking return JsonResponse({'id': unique_id}) I read about celery, but the code I saw looked overkill as I don't need any further communication between the processes and I really want a as lightweight as possible solution. -
Django rest framework with dynamo db
I am new to django rest framework and has some knowledge about it .I did worked with sqlite and postgres Sql database connection,but currently I have given the task in which I need to use DynamoDb with Django rest framework. Are there any proper ways to connect the django rest framework to Dynamo db in settings.py file? because there is no official document about this, and I came across only few vedios where they have explained connecting with mangoDb(noSql) but not with dynamo Db. Any helps will be appreciated. Thanks in advance. -
Django render 2 html files separately on the same page
Background: I am using Django to build my website but am having problems extending some of my pages with a header because of conflicting packages. I am using TinyMCE to render some text and Materialize to make a navbar. The problem is that materialize uses li and some other properties for rendering some stuff so it alters them. This causes problems because now the same property is being called by 2 different packages to do 2 different things. Here is an example: This code will create a navbar using materialize: $(document).ready(function(){ $('.sidenav').sidenav(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <nav class="red" style="padding:0px 10px; position: fixed;"> <div class="nav-wrapper"> <a href="#" class="brand-logo">Web Zone</a> <a href="#" class="sidenav-trigger" data-target="mobile-nav"> <i class="material-icons">menu</i> </a> <ul class="right hide-on-med-and-down " > <li><a href="#">Home</a></li> <li><a href="#">Video</a></li> <li><a href="#">Service</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </div> </nav> <ul class="sidenav" id="mobile-nav"> <li><a href="#">Home</a></li> <li><a href="#">Video</a></li> <li><a href="#">Service</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> And this will create some bullet points: <ul> <li>Bullet 1</li> <li>Bullet 2</li> <li>Bullet 3</li> <ul> But if I try and render them together this is the result: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <nav class="red" style="padding:0px 10px; position: fixed;"> <div class="nav-wrapper"> <a … -
Django: Difficulties by uploading an image
return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type int) This is what I get by sending this API request to the server: I've added this code because without it raises errors as these: File "/home/dziugas/winteka/winteka/main/serializers.py", line 31, in create type=validated_data['type'], KeyError: 'type' I fixed it with this: if validated_data['user']: user = Users.objects.all().filter(pk=validated_data['user']) if not user: return JsonResponse({'error': 'user was not found'}, status=404) But as I said, I get errors when trying to create a new object. This is my serializer: class ReportSerializer(serializers.ModelSerializer): class Meta: model = Reports fields = ('status', 'type', 'user', 'attached_message', 'attached_photo', 'date_created') def create(self, validated_data): if validated_data['user']: user = Users.objects.all().filter(pk=validated_data['user']) if not user: return JsonResponse({'error': 'user was not found'}, status=404) report = Reports( status=validated_data['status'], type=validated_data['type'], user=user, attached_message=validated_data['attached_message'] or None, attached_photo=validated_data['attached_photo'], date_created=validated_data['date_created'], ) And this is my model: class Reports(models.Model): # Report fundamental stuff public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) status = models.IntegerField(choices=StatusTypes, blank=False, null=False, default=0) type = models.IntegerField(choices=ReportTypes, blank=False, null=False, default=10) # User Module user = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='+', null=False) # Post Required Stuff reports = models.IntegerField(blank=False, null=False, default=0) upvotes = models.IntegerField(blank=False, null=False, default=0) downvotes = models.IntegerField(blank=False, null=False, default=0) comments = models.ManyToManyField('main.ReportMessages', related_name='+') attached_message = models.CharField(max_length=300, null=True, blank=True) attached_photo = models.ImageField(null=False, blank=False, … -
Unable to create a new session key. It is likely that the cache is unavailable
I am running bitnami/redis helm chart in my kubernetes cluster. my django app is using it as a session cache. CACHES = { 'default': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis-service:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } heres how my session_engine variable looks like SESSION_ENGINE="django.contrib.sessions.backends.cache" This setup worked just fine when I was running redis as a single replica deployment. when I switched to bitnamis helm chart (with sentinel) I started getting this error intermittently. Unable to create a new session key. It is likely that the cache is unavailable. If I switch over to single pod Redis deployment it works fine. but using a bitnami helm chart seems to be causing this issue. I can confirm I can reach the Redis cluster from my Django pod. what's more confusing is it's causing intermittently. any help will be much appreciated. -
How to take a string as input in django?
I'm working on a Django project where I have to take a Product name from the search bar & pass the name through a python script where the script will scrape some data from a website & store it in a list. Then it will go to the result.html page & show the data. How should I take the product name from the search box & where should I place the python script? How can I loop over the list data & show it in the result.html ?