Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 . -
Python django adding multiple database
How to create or add multiple databases in django. Where always my models are created in default database .how to change it -
Django form updating after adding data to database
I'm building a form for user's to run a query on a database. The model is called Sample and the user is selecting the names they want to include in the query results. In this case the name field is unique but other fields done the same way aren't. Form.py from django import forms from .models import Sample class SampleForm(forms.Form): samples = Sample.objects.all() names = [(s.id, s.name) for s in samples] initial = [c[0] for c in names] Rock_Names = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=names, initial=initial, label='Name') The problem I'm having is when a new sample has been added the form won't update with that sample name until I restart the server. I have a list view for all samples and it updates with the new sample fine. I've tried running Sample.objects.update() after the new sample is saved, but that didn't help. Is there a way to force this to update? Is there a better way to build a query form? -
Django Group Permissions in React
In Django I have added a group and can see it on my template by using: {{ perms.mygroup }} I have a React front end app which has a number of links to navigate around the front end but the 'Edit' link must only be visible if the user has the 'mygroup' permission stated above. How is it that I pass the server permission to the front end app? Am I missing something simple here as I can't find out how to do it. I've read about using React's new context API but the examples I've seen are setting the context on the front end, rather than bringing in a variable from the template. -
Making a dataframe from a queryset in django
This is a general question that might not quite fit the title. Basically I have queryset which I loop over like for q i queryset: q.new_var=... in order to produce new variabels. When I send queryset to the template I get these new variable values in the webbpage. So that works as expected. But now I also want to make a data frame from the queryset, using Pandas and django-pandas. So I write df = read_frame(queryset) I would have thought that if I do that after the loop I would get the new variables included in the data frame, but I do not. Instead it is the same as if I put it before the loop. Why, and how do I fix it? -
Passing objects to Detail View with filter (Django)
Hi I am trying to pass query of comments (Comment model) to a DetailView of Post model using filter to get in DetailView only comments, related to particlural post. Post model: class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Comment model: class Comment(models.Model): content = models.CharField(max_length=500, help_text='Не более 500 знаков') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(on_delete=models.CASCADE) post_id = models.ForeignKey(on_delete=models.CASCADE) Detail veiw: class PostDetailView(DetailView): context_object_name = 'post' model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(post_id = self.model.id) return context And it returns TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Could you please help with reccomendation regarding how correctly use a filter to get in DetailView only comments, related to this Post? Thanks! -
Django Choice list between objects created with model class
i have a following class in models.py class Project(models.Model): project_name = models.CharField(max_length=100,unique=True) project_headers = models.TextField(unique=True) projects_urls = models.TextField() project_timestamp = models.DateTimeField(auto_now_add=True) project_results = models.TextField(blank=True,null=True) def __str__(self): return self.project_name And let's suppose i have created a 2 Projects objects with above class with following project_name. google.com facebook.com I want to create a form where i can add Django Choices list as project_name objects to update their fields such as project_urlsetc, based on project_name selected by User. -
JSON:API with django-rest-framework-json-api and JWT
I thought it might be a good idea to use the standard JSON:API for my new project. Unfortunately I immediately failed to get the JWT authentication working. My setup: Django Django REST framework REST framework JWT Auth Django REST Framework JSON API If I get OPTIONS for my auth path: { "data": { "name": "Obtain Json Web Token", "description": "API View that receives a POST with a user's username and password.\n\nReturns a JSON Web Token that can be used for authenticated requests.", "renders": [ "application/vnd.api+json", "text/html" ], "parses": [ "application/vnd.api+json", "application/x-www-form-urlencoded", "multipart/form-data" ], "allowed_methods": [ "POST", "OPTIONS" ], "actions": { "POST": { "username": { "type": "String", "required": true, "read_only": false, "write_only": false, "label": "Username" }, "password": { "type": "String", "required": true, "read_only": false, "write_only": true, "label": "Password" } } } } } If I then try to POST naively with Content-Type: application/vnd.api+json: { "data": { "user": "user1", "password": "supersecretpw" } } I get 409 Conflict response: { "errors": [ { "detail": "The resource object's type (None) is not the type that constitute the collection represented by the endpoint (ObtainJSONWebToken).", "source": { "pointer": "/data" }, "status": "409" } ] } How can I either retrieve the token correctly or use the …