Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check if matching query does not exist return empty string
when i try to check if an object exist return it to in excel file if not return to me an empty 'string' but i have error in the if sentence price_date_all = PackagePricesAndDates.objects.filter(package=pkg) if price_date_all.get(territory=ter.pk).sales: list.append(str(price_date_all.get(territory=ter.pk).sales)) -
Django Models - Field Syntax
Quick question regarding some syntax when creating django models. If you take a look at the example models.py file below, you'll see that each of the four fields contain a repeat of the field name as a string in parentheses preceded my an underscore. I assume this is some kind of visual representation for when this is encountered in a form, but that seems to happen automatically in admin with out the _('field name'). class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) -
Display purchase history from Django Admin
I am trying to show the purchase history per user on the each users dashboard. I have made some dummy orders in Stripe which are working but I am having difficulty displaying the orders in the order history section of the page. I am also not sure the order is linking correctly to the registered user in the first place as I seem to be confusing myself with this method Can somebody help me or point me in the right direction please? <div class="container"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12"> <table class="table table-striped"> <h3>Your order history</h3> <hr> <tr> <th>Date</th> <th>Invoice ID</th> <th>Description</th> <th>Total</th> </tr> {% for orders in orders %} <tr> <td scope="row">{{ order.quantity }}</td> <td>xxx</td> <td>xxx</td> <td>xxx</td> </tr> {% endfor %} </table> </div> My checkout views.py from django.contrib import messages, auth from django.contrib.auth.decorators import login_required from checkout.forms import MakePaymentForm from django.shortcuts import render, get_object_or_404, redirect, reverse from django.template.context_processors import csrf from django.conf import settings from babysitters.models import Babysitter import stripe # stripe.api_key = settings.STRIPE_SECRET @login_required(login_url="/accounts/login") def buy_now(request, id): if request.method == 'POST': form = MakePaymentForm(request.POST) if form.is_valid(): try: babysitter = get_object_or_404(Babysitter, pk=id) customer = stripe.Charge.create( amount= int(babysitter.price * 100), currency="EUR", description=babysitter.firstName, card=form.cleaned_data['stripe_id'], ) except (stripe.error.CardError): messages.error(request, "Your card was … -
Django AttributeError: 'int' object has no attribute 'save'
I have 2 models Profiles and Events. I want to save the number of events created by the user to the users profile, such that even if the events are deleted the record stays in the users profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_events = models.IntegerField(default=0) class Event(models.Model): user = models.ForeignKey(User, related_name='seller') ... Below are my views class CreateEvent(IsVerifiedMixin, CreateView): model = Event form_class = EventForm template_name = 'event/event_form.html' def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.user = self.request.user print(self.object.user.profile.total_events) #This prints 0 self.object.user.profile.total_events += 1 print(self.object.user.profile.total_events) # This prints 1 self.object.user.profile.total_events.save() # If I don't use this statement it does not save to database. But It gives me the above error self.object.save() return super().form_valid(form) This line self.object.user.profile.total_events.save() gives me the error How do I fix this error. I tried adding a variable and saving the variable but I still get the same error -
django restframework how to count object and get since(timestamp)?
guys. Im trying to make a notifications system through django restframework, my problem is that i don't know how to get a count of notifications unread and either make a format of the timestamp to since(timestamp) through django restframework because in a normal view i know perfectly how to do that. Well this is my model: class Notificaciones(models.Model): user_a_notificar = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) komentario = models.OneToOneField(Post,on_delete=models.CASCADE, blank=True, related_name="komentario") estado = models.ManyToManyField('Evento', blank=True) def __str__(self): return self.user_a_notificar.username class Evento(models.Model): creadores = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="generadores") status = models.CharField(default="Unread", max_length=10) mensaje = models.CharField(max_length=200) event = models.CharField(max_length=15) noti_de_evento = models.ForeignKey(Notificaciones, on_delete=models.CASCADE) timestampe = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.mensaje my view: class Notifi(APIView): serializer = notizerializer def get(self, request, format=None): noti = Notificaciones.objects.filter(user_a_notificar=request.user.id) lista_noti = Evento.objects.filter(noti_de_evento__in=noti) lista_noticount = Evento.objects.filter(noti_de_evento__in=noti, status="Unread").count() response = self.serializer(lista_noti, many=True) return HttpResponse(json.dumps(response.data)) and finally my serializer: class notizerializer(ModelSerializer): class Meta: model = Evento fields = ('status', 'mensaje', 'event', 'timestampe', 'id') -
Django auth model: combine multiple fields into one username_field
I have multiple fields users have to specify on signup: date_of_birth, first_name, last_name. What I now want is to combine these fields to one for USERNAME_FIELD, like so: John_Doe_01011988 The following obviously doesn't work: USERNAME_FIELD='%s-%s' % ('first_name', 'last_name') -
Django Serializer Nested Creation: How to avoid N+1 queries on relations
There are dozens of posts about n+1 queries in nested relations in Django, but I can't seem to find the answer to my question. Here's the context: The Models class Book(models.Model): title = models.CharField(max_length=255) class Tag(models.Model): book = models.ForeignKey('app.Book', on_delete=models.CASCADE, related_name='tags') category = models.ForeignKey('app.TagCategory', on_delete=models.PROTECT) page = models.PositiveIntegerField() class TagCategory(models.Model): title = models.CharField(max_length=255) key = models.CharField(max_length=255) A book has many tags, each tag belongs to a tag category. The Serializers class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag exclude = ['id', 'book'] class BookSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) class Meta: model = Book fields = ['title', 'tags'] def create(self, validated_data): with transaction.atomic(): tags = validated_data.pop('tags') book = Book.objects.create(**validated_data) Tag.objects.bulk_create([Tag(book=book, **tag) for tag in tags]) return book The Problem I am trying to POST to the BookViewSet with the following example data: { "title": "The Jungle Book" "tags": [ { "page": 1, "category": 36 }, // plot intro { "page": 2, "category": 37 }, // character intro { "page": 4, "category": 37 }, // character intro // ... up to 1000 tags ] } This all works, however during the post, the serializer proceeds to make a call for each tag to check if the category_id is a valid one. See the … -
PostGreSQL- PostGis - How to determine if postgis is enabled on a database?
I wanted to know if there was a way to determine if PostGis was enabled on a database. I am trying to replicate my production server with my dev. machine and I am not sure if my dev machine had either postgis or postgis_topology enabled. I tried looking around for a solution but could not come up with anything. Any suggestions in this regard would be helpful. -
Can't redirect any page after successful registration
I want to redirect login page after successful registration. But, the problem occurs when I submit the registration form. Actually, I tried in multiple ways to redirect, but didn't find any suitable way and got errors. Here is my code: views.py: from django.http import HttpResponse from django.views import generic from django.views.generic import CreateView,TemplateView from .forms import UserForm from django.core.urlresolvers import reverse_lazy from django.shortcuts import redirect class UserFormView(CreateView): form_class = UserForm template_name = 'templates/registration_form.html' def index(request): return HttpResponse('<p>Home Page!</p>') forms.py from django.contrib.auth.models import User from django.forms import ModelForm from django import forms from .models import Profile from django.contrib.auth import authenticate,login class UserForm(forms.ModelForm): password = forms.CharField(widget= forms.PasswordInput) full_name = forms.CharField() codeforces_id = forms.CharField() Uva_Id = forms.CharField() class Meta: model = User fields = ('username','email','password', 'full_name', 'codeforces_id', 'Uva_Id') def save(self, commit=True): user = super(UserForm, self).save(commit=False) password = self.cleaned_data.get('password') username = self.cleaned_data.get('username') user.set_password(password) user.save() Profile.objects.create( user=user, full_name=self.cleaned_data.get('full_name'), codeforces_id = self.cleaned_data.get('codeforces_id'), Uva_Id = self.cleaned_data.get('Uva_Id') ) authenticate(username=username, password=password) return user register.html <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> -
Python3 Try with multiple Except not working (Django)
I've got the following function question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) When I do an empty POST, I get a yellow error page saying name 'Choice' is not defined. Exception Type: NameError" I changed the except to the following: except KeyError: Now it works, but I would still like to have the Choice.DoesNotExist exception beeing cought. I'd like to keep it in one line as well. What's the problem here? -
Make FileType a unique entry in the Database
whilst overwriting files in s3 comes easy, every upload adds a new entry to the model table. This leads to multiple entries with the same filename, which I'd like to avoid. Any hints how to change this behavior so instead of adding a new entry, django would update the fields of the old one? protected_storage = storages.backends.s3boto3.S3Boto3Storage( acl='private', querystring_auth=True, querystring_expire=120, # 2 minutes, try to ensure people won't/can't share ) class DrawerFile(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField( null=False, blank=False, storage=protected_storage, upload_to=file_location ) Thanks! -
Django admin-like foreign key widget
I'd like to re-use or mimic Django admin's foreign key popup widget (see below) on the front end of my site on generic CreateView and UpdateView views. I found this: https://github.com/DarkSector/django-foreignkeypopup but it looks like it isn't actively maintained (last commit was in 2015). -
Changes take place only after Apache's restart
I'm using Apache 2.4 and mod_wsgi to host my Django2 app. My problem is that when I make some changes to templates or .py files (when I change static files everything is ok), these changes take place only after I restart apache. What am I missing? Apache config: <VirtualHost *:80> ServerName expample-domen.com ServerAdmin webmaster@localhost Alias /static /var/www/example/static Alias /media /var/www/example/media <Directory /var/www/example/static> Require all granted </Directory> <Directory /var/www/example/media> Order deny,allow Require all granted </Directory> <Directory /var/www/example/example> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess example python-home=/path/to/virtualEnv python-path=/var/www/example WSGIProcessGroup example WSGIScriptAlias / /var/www/example/example/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> -
Send message using Django Channels from outside Websocket class
I am building an online game, which uses Django channels 2.1.5 for websockets. I am able to build the connection between the client and the server, and also able to send data between them only inside the consumer class: from channels.generic.websocket import WebsocketConsumer import json from . import controller class GameConsumer(WebsocketConsumer): def connect(self): self.accept() print("Wohooo .. Connected to client!") self.render() controller.startTurn() def render(self, type="render", message=None): self.send(controller.renderMap(type, message)) def disconnect(self, close_code): print("WebSocket connection is lost...") def receive(self, text_data): text_data_json = json.loads(text_data) controller.handleRecieved(text_data) ... Now, What I wish to do, is to call the function render, -which is inside the consumer class-, from another module I tried this: from .. import consumer def sendDeployments(owner, armies): type = "renderDeployments" message = owner + " has " + str(armies) + " to deploy" dummyConsumer = consumer.GameConsumer() consumer.GameConsumer.render(type, message) But failed because I can't use the "self" parameter from outside the class. Can anybody think of a way to achieve my goal? Ps: I don't care about synchronization at this occasion. Thanks in advanced. -
Understanding model in djangorestframwork unit tests
I was reading unit test for filters in django-rest-framework. I tried to mock the unit test locally in another project by adding a model as above but my tests fail with: django.db.utils.ProgrammingError: relation "blog_postmodel" does not exist. tests.py from django.test import TestCase from django.db import models from rest_framework import filters, serializers class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField(max_length=255) class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' class TestPostFilter(TestCase): def setUp(self): Post.objects.create(title="A post title",content="some post content") def test_search(self): assert True I understand that to create a corresponding db table for a model we have to run ./manage.py makemigrations blog and ./manage.py migrate blog, but the example above is adding a dummy model only for testing purpose. I dont see how for that model migrations are executed. Probably lots of going on in the background. My question is how this model is being created in test database ? -
Test login_view by passing a request with queryset
I'm new to Django and I have some difficulties starting testing my code. I want to test that the login function I wrote can refuse connection if the form is invalid and log in if it valid. Here is the code I want to test : def login_view(request): title = "Login" form = UserLoginForm(request.POST or None) context = {"form":form, "title":title} if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username,password=password) login(request,user) return redirect('/production') return render(request, "registration/form.html", context) All tutorials I saw only test that posting a valid form to the correct url works or that an invalid form don't. Something like : def test_login_with_no_username(self): form = UserLoginForm({'username': "JohnDoe",'password': "DoeJohn",}) self.assertFalse(form.is_valid()) response = self.client.post("login", form) self.assertEqual(response.status_code, 302) I trying to pass in argument of login_view a HttpRequestwith a QuerySet but I can't find a way to make it works. Is is at least possible ? Is the test that I've described is enough ? -
Change url in Django
I am trying to load a pdf file in django which is already present in the database. I can access the pdf file using the url, "localhost:8000/documents/file.pdf" but when I perform the query and return the response containing this file, url it redirects to "localhost:8000/ans/documents/file.pdf" which doesn't exist. The html code is: <form id="signup-form" method="POST" action="ans/"> {% csrf_token %} <input type="text" name="id" id="id" placeholder="Report id" /> <input type="submit" value="Check" /> </form> The path in urls.py is path('ans/',views.func), The view is: def func(request): if request.method=="POST": id=request.POST.get("id") ans = query.objects.get(id=id) response=ans.repo if ans is None: return render(request,"index.html",{}) else: return redirect(response) The bottomline is, I wan't to get rid of the "/ans/" in the url. -
Retrieve Date & Temperature - World Wide Weather API
I thought I understood how to do this, but I am working on a project for class and I can't get the api to return the values. I have check in Postman and the API is working fine. my code: w, h = 3, i final_list = [[0 for x in range(w)] for y in range(h)] while z < i: date = (json_data["data"][z]["weather"]["date"]) max_temp = (json_data["data"][z]["weather"]["max_temp"]) final_list[z][0] = date final_list[z][1] = max_temp final_list[z][2] = z z = z + 1 HttpResponse(final_list) I have played with different formats trying to figure out the list and dicts. "data": { "request": { "type": "IATA", "query": "oma, Eppley Airfield, United States of America" }, "weather": { "date": "2018-11-24", "astronomy": { "sunrise": "07:23 AM", "sunset": "04:58 PM", "moonrise": "06:35 PM", "moonset": "08:42 AM", "moon_phase": "Waning Gibbous", "moon_illumination": "97" }, "maxtempC": "8", "maxtempF": "47", "mintempC": "-1", "mintempF": "31", "totalSnow_cm": "0.0", "sunHour": "8.7", "uvIndex": "2", "hourly": [ { Thank you for any help. Brent -
Make User email unique django
How do I make a Django User email unique when a user is signing up please? forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user Im using the from django.contrib.auth.models User. Do I need to override the User in the model. Currently the model doesnt make a reference to User. views.py class SignUp(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy('login') template_name = 'signup.html' Thanks for your thoughts. -
Creating Solr scheme file haystack "<stdin> is a directory" error
My problem is quite simple but i have no clue how to fix it. I'm getting started with haystack following their tutorial but I ocuured problem when creating solr cheme through linux terminal. I used command ./manage.py build_solr_schema --configure-directory=<../solr/server/solr/tester/conf> --reload-core And I've got followin error Python error: <stdin> is a directory, cannot continue I'm working on Ubuntu, solr 6.5.0, python 3.X Django 2.X Django-Haystack 2.5.X I was looking for solution but I didn't found such case. I would be very grateful for help. -
Django2.0.7 TypeError: Model instances without primary key value are unhashable
I am trying to migrate the models that were generated for me via python manage.py inspectdb. I tried python manage.py makemigrations and got this error: SystemCheckError: System check identified some issues: ERRORS: Users.DjangoContentType: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'. So I went into my file and changed this model: To this: and when I run python manage.py makemigrations and python manage.py migrate and I get this error: Any idea what I should do/what this means? This is my pip freeze output: certifi==2018.10.15 Django==2.0.7 mysqlclient==1.3.13 pytz==2018.7 -
Need assistance in fixing SuspiciousFileOperation error in django2.0
Traceback: File "D:\Program\Anaconda3\envs\myshop\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Program\Anaconda3\envs\myshop\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "D:\Program\Anaconda3\envs\myshop\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Program\Anaconda3\envs\myshop\lib\site-packages\django\views\static.py" in serve 36. fullpath = Path(safe_join(document_root, path)) File "D:\Program\Anaconda3\envs\myshop\lib\site-packages\django\utils\_os.py" in safe_join 49. 'component ({})'.format(final_path, base_path)) Exception Type: SuspiciousFileOperation at /media/products/2018/11/24/vol.3.png{% else %}/static/img/no_image.png Exception Value: The joined path (D:\myshop\media\products\2018\11\24\vol.3.png{% else %}\static\img\no_image.png) is located outside of the base path component (D:\myshop\media\) list.html <div id="sidebar"> <h3>Categories</h3> <ul> <li {% if not category %}class="selected"{% endif %}> <a href="{% url "shop:product_list" %}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected"{% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} </ul> </div> <div id="main" class="product-list"> <h1>{% if category %}{{ category.name }}{% else %}Products {% endif %}</h1> {% for product in products %} <div class="item"> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/no_image.png' %}{% endif %}"> </a> <a href="{{ product.get_absolute_url }}">{{ product.name }}</a> <br> R{{ product.price }} </div> {% endfor %} </div> views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category … -
Django failed to lookup for key 'is_popup'
Here is my errorlog, I am using django 2.1.3, python 3.6 with pipenv django.template.base.VariableDoesNotExist: Failed lookup for key [is_popup] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7f99c8459400>>, 'request': <WSGIRequest: GET '/admin/login/?next=/admin/'>, 'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f99ca379748>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7f99ca37e748>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f99ca379710>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': <AdminAuthenticationForm bound=False, valid=Unknown, fields=(username;password)>, 'view': <django.contrib.auth.views.LoginView object at 0x7f99ca379160>, 'site_title': 'XXD', 'site_header': 'XXD', 'site_url': '/', 'has_permission': False, 'available_apps': [], 'title': 'Log in', 'app_path': '/admin/login/?next=/admin/', 'username': '', 'next': '/admin/', 'site': <django.contrib.sites.requests.RequestSite object at 0x7f99ca379208>, 'site_name': 'localhost:8081', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] INFO 2018-11-24 17:45:28,796 basehttp 5201 140298476877568 "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1828 ('GET /admin/login/?next=/admin/ HTTP/1.1', '200', '1828') null I am receiving this on open of django admin panel. Because of this it is not redirecting to next page even after successfully login. -
Django - How to update a field for a model on another model's creation?
I have two models, a Product model and a Rating model. What I want to accomplish is, every time a "Rating" is created, via an API POST to an endpoint created using DRF, I want to compute and update the average_rating field in the associated Product. class Product(models.Model): name = models.CharField(max_length=100) ... average_rating = models.DecimalField(max_digits=3, decimal_places=2) def __str__(self): return self.name class Rating(models.Model): rating = models.IntegerField() product = models.ForeignKey('Product', related_name='ratings') def __str__(self): return "{}".format(self.rating) What is the best way to do this? Do I use a post_save (Post create?) signal? -
pdfkit footer-html and footer-right is not working together
I am trying to use footer-html and footer-right together in my python app while generating the pdf using pdfkit. I have used jinja templates for rendering it. I have main file whose pdf I want named as 'main.html' and one header and footer file named as 'header.html' and 'footer.html' and I am adding header and footer in my all pdf pages which is rendered dynamically. But when I try to use {'footer-right':'[page]/[topage]} its not working and if I remove footer-html and header-html while generating the pdf then its working. Can somebody tell me how to use both means my dynamically header and footer and page count on each page .