Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django/postgres error:'database XX does not exist'
I created a database using pgAdmin GUI tool to use with postgres for my django project. There are only two databases in pgAdmin, the default 'postgres' db you get out of the box with pgAdmin, and my new database, dbfunk. I'm using django and added postgres as my database and gave the necessary info in settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dbfunk', 'USER': 'postgres', 'PASSWORD': 'XXXXXX', 'HOST': 'localhost' } } But when I run python manage.py makemigrations it gives the error, the database 'dbfunk' does not exist, even though it's in both settings.py in Django and added in pgAdmin. The full text of the error is: django.db.utils.OperationalError: FATAL: database "dbfunk" does not exist I've installed the adaptor psycopg2. I also tried 'ENGINE': 'django.db.backends.postgresql_psycopg2', in Settings.py but this didn't make any difference. Is there something else I am missing? When I ran the command psql \u it is only showing the postgres database there also, and not this new database 'dbfunk'. -
Google App Engine deployment fails because of failing readiness check
A custom app engine environment fails to start up and it seems to be due to failing health checks. The app has a few custom dependencies (e.g. PostGIS, GDAL) so a few layers on top of the app engine image. It builds successfully and it runs locally in a Docker container. ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section. The Dockerfile looks as follows (Note: no CMD as entrypoint is defined in docker-compose.yml and app.yaml): FROM gcr.io/google-appengine/python ENV PYTHONUNBUFFERED 1 ENV DEBIAN_FRONTEND noninteractive RUN apt -y update && apt -y upgrade\ && apt-get install -y software-properties-common \ && add-apt-repository -y ppa:ubuntugis/ppa \ && apt -y update \ && apt-get -y install gdal-bin libgdal-dev python3-gdal \ && apt-get autoremove -y \ && apt-get autoclean -y \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* ADD requirements.txt /app/requirements.txt RUN python3 -m pip install -r /app/requirements.txt ADD . /app/ WORKDIR /app This unfortunately creates an image of a whopping 1.58GB, but the original gcr.io python image starts at 1.05GB, so I don't think the … -
Python skip importing submodules that aren't available
I have a Python module that runs on a server and has some server specific imports (and functions). I want to import and run it locally with a django command. However, on my local machine, the server specific modules are not available. I am currently using a try/except block in the server module but is there a better way to accomplish this? -
Can't pass a django variable into javascript
I cannot pass a django variable into a javascript file. The way I'm trying to pass it right now is through my base.html file through a script tag like this: <script type="text/javascript"> var user = '{{ request.user }}' var csrftoken = {% csrf_token %} var x = 5 </script> The script tag shown is near the top of the file (so the page loads), this information is supposed to be processed through this javascript function in a file called cart.js: var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log(x) //the variable from the base.html file console.log('productId:', productId, 'Action:', action) updateUserOrder(productId, action) }) } However in console the error reads: Uncaught ReferenceError: x is not defined at HTMLButtonElement.<anonymous> (cart.js:7) the view using base.html when this error occurs is a function based view. Thanks! -
Can´t load virtual enviroment in Apache, WSGI, Django and Windows
I'm trying to run a Django app in my development computer with windows. I have succesfully created a virtual enviroment with virtualenv (not virtualenvwrapper), installed Django and loaded it with the internal server running python manage.py runserver. I belive all things with PHP, path variable, etc, etc, are ok. I've also succesfully installed WSGI following the instructions of https://modwsgi.readthedocs.io/en/develop/, but just with the global Python. I've installed the mod_wsgi perfoming these steps outside the virtualenv: set "MOD_WSGI_APACHE_ROOTDIR=C:/wamp64/bin/apache/apache2.4.41" pip install --upgrade setuptools pip install mod_wsgi mod_wsgi-express module-config Then I copied the result lines to my httpd.conf: LoadFile "c:/program files/python35/python35.dll" LoadModule wsgi_module "c:/program files/python35/lib/site-packages/mod_wsgi/server/mod_wsgi.cp35-win_amd64.pyd" WSGIPythonHome "c:/program files/python35" Created an Alias in httpd.conf Alias /test/ "C:/wamp64/apps/wsgi_app/" <Location /test> SetHandler wsgi-script Options +ExecCGI </Location> <Directory "C:/wamp64/apps/wsgi_app"> Options Indexes FollowSymLinks Require local </Directory> and successfully served a wsgi file: import sys def application(environ, start_response): status = '200 OK' output = u'' output += u'sys.version = %s\n' % repr(sys.version) output += u'sys.prefix = %s\n' % repr(sys.prefix) response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output.encode('UTF-8')] It works like a charm, indicating I don't have problems with VC versions, Python versions and so on. When I try to do the same thing in a virtual environment, … -
What is the model attached to django UserCreationForm()
I have read the official documentation for UserCreationForm(). I am trying to access the users I have created within other models. What model do I call to access the users I created within the UserCreationForm()? In short is their a default authentication model I can call to access the user model? -
how to get a value from a input in django?
i'm trying to get a value from a input with django but dont work python: def add_entry(request): title = request.GET.get("title") content = request.GET.get("content") return render(request, "encyclopedia/add.html", { "title": title "content": content }) html: <form action="{% url 'add_entry' %}" method="POST"> <h1>Create new entry</h1> <h3>Title</h3> <textarea name="title" id="textarea-title"></textarea> <h3>content</h3> <textarea name="content" id="textarea-content"></textarea> <input type="submit" value="Create"> </form> -
Loading new data with AJAX if changes in Django model objects
View: def user_messages(request): time_now = datetime.datetime.now() user = request.user if request.method == "POST": if 'read' in request.POST: un = request.POST.get('read') Messages.objects.filter(id=un).update(is_read=True) else: sender = request.user receiver_name = request.POST.get('msg_receiver') receiver = User.objects.get(username=receiver_name) msg_content = request.POST.get('msg_content') Messages.objects.create(sender=sender, receiver=receiver, msg_content=msg_content) inbox = Messages.objects.filter(receiver=user).order_by('-timestamp') outbox = Messages.objects.filter(sender=user).order_by('-timestamp') context = {'inbox': inbox, 'outbox': outbox, 'time_now': time_now} return render(request, 'accounts/messages.html', context) Whenever there is a new message in inbox, I want AJAX to update the div with the new message <div id="inbox"> <h6>Inbox</h6> {% for message in inbox %} <ul> <li title="{{ message.sender.username }}"> {{ message.sender.first_name }}: {{ message.msg_content }} {% if message.is_read == False %} <form action="{% url 'messages' %}" method="POST"> {% csrf_token %} <button value="{{ message.id }}" name="read">mark as read</button> </form> {% endif %} {% if message.is_read == True %} <button onclick="reply()">Reply</button> {% endif %} </li> <small>-{{ message.timestamp }}</small> <hr> </ul> {% endfor %} </div> I loop through the inbox and print out the messages. But whenever there is a new message, the user has to refresh the page see the changes. I want Ajax to update only the div asynchronously. How I use Ajax to see if the inbox.count has increased and if increased, then add the new data to the list? I … -
Can you have 2 apps in one url.py?
I was following a Tutorial about Newsletters and the instructor started an app for the newsletter and inorder to manage it he created a new app called Control Panel and have pages to create newsletter and send them to users. After finalizing the tutorial I thought I could use the control panel as an admin to manage other pages such as a blog app but I didn't know how to proceed since the urls.py has already an app registered to it called Newsletters. So my question is can I add another app to the url.py? To clarify more what I am trying to say here is the urls.py from django.urls import include, path from newsletters.views import control_newsletter, control_newsletter_list, control_newsletter_detail, control_newsletter_edit, control_newsletter_delete app_name = 'newsletters' urlpatterns = [ path('newsletter/', control_newsletter, name="control_newsletter"), path('newsletter-list/', control_newsletter_list, name="control_newsletter_list"), path('newsletter-detail/<int:pk>', control_newsletter_detail, name="control_newsletter_detail"), path('newsletter-edit/<int:pk>', control_newsletter_edit, name="control_newsletter_edit"), path('newsletter-delete/<int:pk>', control_newsletter_delete, name="control_newsletter_delete"), ] Is it possible to add another app called blogs for example and add their paths and if not what are the best other options I have so that I can use the Control panel as an admin backend to manage different apps? -
How to unittest valid img src links in a template response
I have a view that renders a template with an image: <html> ... <img src="/static/img/mypic.jpg" /> ... </html> I want to write a unit test that asserts this img src is valid and does not return a 404 broken link. def test_myimage(self): response = self.client.get('/static/img/mypic.jpg') However, although I know this link is in fact valid, the test returns 404. Why does this occur and how can I test valid img src links? -
how i can create live server of my Django project
I have created a project on Django and I want to publish it on the live server with google hosting and domain. I use Postgres as a backend database for how I connect pgAdmin of the Postgres with google cloud hosting server. how I can use google domain in my project. I am working on windows 10 -
How to assert exception using django.test.TestCase?
I am using Django 3 (latest) and tried to assert exception using unittest assertRaises as in the documentation. My code is raising django.template.TemplateSyntaxError when it gets an IndexError: from django import template register = template.Library() @register.tag(name="autopaginate") def do_autopaginate(parser, token): split = token.split_contents() as_index = None context_var = None for i, bit in enumerate(split): if bit == "as": as_index = i break if as_index is not None: try: context_var = split[as_index + 1] except IndexError: raise template.TemplateSyntaxError( ( f"Context variable assignment " f"must take the form of {{% {split[0]} object.example_set.all ... as " f"context_var_name %}}" ) ) del split[as_index : as_index + 2] if len(split) == 2: return AutoPaginateNode(split[1]) if len(split) == 3: return AutoPaginateNode(split[1], paginate_by=split[2], context_var=context_var) if len(split) == 4: try: orphans = int(split[3]) except ValueError: raise template.TemplateSyntaxError(f"Got {split[3]}, but expected integer.") return AutoPaginateNode( split[1], paginate_by=split[2], orphans=orphans, context_var=context_var ) raise template.TemplateSyntaxError( f"{split[0]} tag takes one required argument and one optional argument" ) My test code following documentation is: from django import template from django.http import HttpRequest from django.test import TestCase class TestHttpRequest(HttpRequest): __test__ = False page = 1 class TestTemplatePaginateTags(TestCase): def test_render_range_by_var_as_index_error(self): t = template.Template( "{% load pagination_tags %}{% autopaginate var by as %}{{ foo }}" ) c = template.Context({"var": … -
DJANGO - Connect Allauth social user with custom models
So I have custom models to assign users, user type, user preferences etc., eg. user_type looks like this: accounts/models.py class user_type(models.Model): is_type_<some_type> = models.BooleanField(default=False) is_type_<some_type> = models.BooleanField(default=False) # many types after is_admin = models.BooleanField(default=False) user = models.OneToOneField(User_u, on_delete=models.CASCADE) def __str__(self): if self.is_admin: return User_u.get_email(self.user) + ' - is admin' # many types after if self.is_<some_type>: return User_u.get_email(self.user) + ' - is <some_type>' if self.is_<some_type>: return User_u.get_email(self.user) + ' - is <some_type>' and in views: account/views.py ... user_t = user_type(user=user, is_<some_type>=True) user_t.save() ... I am looking for an idea how to implement something like this, but for users who only use social login(eg. gmail or office365). Probably I will need adapters for that, right? -
Django form becomes invalid when position set to absolute or display set to none
I wanted my upload file button to look different so i tried these two CSS one sets display:none; when file is uploaded and other is just setting it position:absolute; My application works perfectly without CSS. How can i solve this ? Is there any other way to do it ? When the form is submitted function in my views.py form.is_valid() returns False My First CSS : input[type="file"] { opacity: 0; /* make transparent */ z-index: -1; /* move under anything else */ position: absolute; /* don't let it take up space */ } input[type="file"]:focus + label { outline: 2px solid; /* example focus style */ } My Second CSS: .image-upload > input { display: none; } .image-upload img { cursor: pointer; } My HTML: <div role="button" class="post-button image-upload" style="display: inline-block;border: none;border-radius: 20px; margin-right: 5px;margin-left:5px;padding: 8px;"> <label style="margin-bottom: 0;" for="id_picture"> <img src="{% static "User/ART/Album.png" %}" alt="ProfilePic"/> </label> {{ post.content }} {{ post.picture }} </div> forms.py class PostForm(forms.Form): content = forms.CharField() picture = forms.ImageField() -
Django template html tag encapsulation
A few years back i used some templatetag which encapsulated the HTML code. For instance I had this: <h4>Something and it added automatically the closing <H4> tag. What's the name of the templatetag? I'm unable to find it. -
Custom Fields in Django not displayed in admin panel
I am using UserCreationForm for registration of the user. Added one address filed as mandatory in the code. however whenever the user is registering on the html page the address input is present.In the admin panel for users the address is not present. form : class RegistrationForm(UserCreationForm): email=forms.EmailField(required=True) address=forms.CharField(max_length=250,required=True) class Meta: model=User fields=( 'username', 'first_name', 'last_name', 'email', 'address', 'password1', 'password2' ) def save(self,commit=True): user=super(RegistrationForm,self).save(commit=False) user.first_name=self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] user.email=self.cleaned_data['email'] if commit: user.save() return user views.py def register(request): print("inside views") if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('./login.html') else: form = RegistrationForm() args = {'form': form} return render(request,'./reg_form.html',args) else: form = RegistrationForm() args = {'form': form} return render(request,'./reg_form.html',args) In the user model all the fields are seen in the admin page,just address is not present. However while registering the user, address input is accepted. -
How to showing video with different resolutions in Django like
I want to have a Django site to show a video that can be played on videos with different resolutions. How can I do a site like YouTube? -
ForeignKey is null after POST in Django Rest (Nested Serializer)
I am a newbie in Django, and I had implemented a one-to-many relationship, however one fieled which is nested is null. When I post destinations is null in the response section. Below is my response section : { "id": 7, "name": "Germany tour", "description": "This is a fascinating tour to take", "price": "30.0", "destinations": null, "capacity": 10 } This is the way I am posting in the Body section in postman : { "name": "Germany tour", "description": "This is a fascinating tour to take", "price": 30.0, "destinations": [ { "location":"Germany", "tour_type":"Adventure", "danger_type":"Medium" } ], "capacity": 10 } Then, below is my models file : from django.db import models class Destinations(models.Model): location = models.CharField(max_length=20) tour_type = models.CharField(max_length=20) danger_type = models.CharField(max_length=20) class Meta: unique_together = ['location', 'tour_type'] class TourPackages(models.Model): name = models.CharField(max_length=50) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=1) destinations = models.ForeignKey(Destinations, related_name="destinations", on_delete=models.CASCADE) capacity = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Then, my serializers file : from rest_framework import serializers from .models import TourPackages, Destinations class DestinationSerializer(serializers.ModelSerializer): class Meta: model = Destinations fields = ['tour_type', 'danger_type'] class TourPackagesSerializer(serializers.ModelSerializer): destinations = DestinationSerializer(many=True) class Meta: model = TourPackages fields = ['id', 'name', 'description', 'price', 'destinations', 'capacity'] def create(self, … -
Django models RelatedObjectDoesNotExist
i am making an ecom app for Django but when i use a diffrent user i get this error. i think it has something to do with assigning a Customer to a User, as when i manually create a Customer with a User. Exception Type: RelatedObjectDoesNotExist Exception Value: User has no customer. Exception Location: L:\Django\Website\lib\site-packages\django\db\models\fields\related_descriptors.py in __get__, line 420 Python Executable: L:\Django\Website\Scripts\python.exe Python Version: 3.8.3 here is my views.py from django.shortcuts import render from .models import * from django.http import JsonResponse import json import datetime from django.contrib.auth.models import User def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total':0,'get_cart_items':0, 'shipping':False} artItems = order['get_cart_items'] search = request.GET.get('search') products = Product.objects.all() if search != '' and search is not None: products = products.filter(name__icontains=search) context= {'products': products, 'cartItems':cartItems} return render(request, 'store/store.html', context) ...unrelated... here is my models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name ...unrelated... -
Django forms: how do is_valid() and validation errors work together?
In the below snippet, I'm validating a basic email form. This seems to work just fine (when I type in emails that aren't valid, the correct errors are raised), but I'm a little confused by what's going on behind the scenes. Walking through the logic here: if the form is valid, then I know what happens. However, what happens if the form isn't valid? I guess I'm confused, since there is no else statement, and so I'm wondering if is_valid generates a list of validation errors that are used later in the return render(request, 'index.html', {'form': form})? If not, how exactly are the validation errors generated? I've tried digging through the Django documentation, but I don't see much besides is_valid returns a boolean... Is that what's going on? Could someone help verify, or if I'm off, help explain what happens when the form is not valid? Thanks! views.py def signup(request): if request.method == 'POST': form = SubscriberForm(request.POST) if form.is_valid(): sub = Subscriber(email=request.POST['email']) sub.save() return render(request, 'index.html', {'email': sub.email, 'action': 'added'}) else: form = SubscriberForm() return render(request, 'index.html', {'form': form}) In case it's needed for context, an excerpt from my forms.py: class SubscriberForm(forms.Form): email = forms.EmailField(label='Enter your email:', max_length=100, widget=forms.EmailInput(attrs={'class': 'form-control'})) … -
Django print invalid value from is_valid
I have a Django view that will save the value from a Post request form=MyForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.added_on = timezone.now() post.save() return redirect(index) How do I print the invalid value which makes the is_valid() test to fail? -
How to overwrite model update method
I can simply overwrite the save save method like so def save(self, *args, **kwargs): # Do something super(Goal, self).save(*args, **kwargs) # Do something else How come i can't overwrite the update method in the same way? It doesn't run any of my custom code when updating an object. def update(self, *args, **kwargs): # Do something super(Goal, self).update(*args, **kwargs) # Do something else -
Django Rest Framework CORS error with axios withCredentials set to true
I am using Django REST framework, and reacr, getting a post req and sending response to set cookies in browser, i am setting withCredentials to true in axios.post because it browser will ignore response headers cookies. The main problem is that i am getting CORS error withCredentials: true, but when i remove this parameter or set it to false i get no error and response is received howsoever cookie is not set. please help me, here is the code for axios axios.post(`http://localhost:8000/api/v1/backend1/test/`, {title: this.state.title, deltaData: JSON.stringify(this.state.deltaData)}, {withCredentials: true} ) .then(res=> { this.setState({ returnedDelta: JSON.parse(res.data.Data.deltaData) }) console.log(res) }) .catch(err=>{ console.log(err) }) here is my Django rest APIView class class TestView(APIView): def post(self, request): dic = {"Data": {"deltaData": "Response receibed"} } response = Response(dic, status=status.HTTP_201_CREATED) response.set_cookie('servercookie', "this is from server") return response I have added corsheaders and did almost everything in my settings.py file but nothing is working, please help me -
Pillow installed correctly but ImageField got error Pillow is not installed - Django
I install correctly Pillow using all these comments: Pip install Pillow - Pip Insall Pillow==6.2.0 - pip install Pillow Requirement already satisfied: Pillow in c:\program files (x86)\python38-32\lib\site-packages (7.2.0) python -m pip install --upgrade Pillow python -m pip install --upgrade Pillow Requirement already up-to-date: Pillow in c:\program files (x86)\python38-32\lib\site-packages (7.2.0) And update Pip as successfully, but when I want to add ImageField like this: image = models.ImageField(), I've got this error: ecommerce.Item.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". some people say this is for the version of your windows but I install pip for win64 please help, thankyou -
Django request.POST not parsing JSON
I am sending AJAX request to Django using XMLHttpRequest and FormData. When I send the following: form.append("myData", true) it comes in properly, but when I try printing the value of myData from my request.POST dictionary, it prints 'true' as a string and not as a python boolean (True). How can I fix this?