Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Host Django site on windows on lan
I have a site that I want to expose to a bunch of colleagues that serves as an interface for some Machine learning tools. I’ve made the site in Django 2.0 and would like to serve it from a small windows PC under my desk, and then from a more dedicated server once it’s operational. I’ve had a look around and it looks like my options are using uWSGI or Django it self to serve the site. Obviously Django is mich slower, but on a PC with an i5 i recon it should be able to handle a couple of requests a minute, which is the peak traffic I’m expecting. FastCGI appears to be depreciated, so what other options, prioritizing ease of confit on my part are there? -
ImportError: No module named googleads
I have a django project and want to deploy it on Google App Engine(GAE). I followed all this link for the tutorial: https://cloud.google.com/python/django/appengine When I finished deploying, and go to my project URL, I got an error and when I look on the Error Reporting in Google Cloud Platform It says "ImportError: No module named googleads", but I already installed it on my local before I uploaded it. Please help! Thanks! -
how to install packages inside virtualenv
I have a virtualenv created for a Django project. Inside this project I have app folder with 'views.py'. I have installed beautiful soup and requests inside this virtualenv and they import correctly into the 'views.py'. However, for testing puroposes I have another script created inside the same folder as 'views.py' but when I try to import same modules there I get 'no module named...' error. Is that possible? -
How to update database in django without taking id of the object
When i am doing a post request without id of the object it is showing "subject": [ "This field is required." ] subject has a field called title , so can i update the database using the title. -
Why is Postgres query faster than Redis query?
I am learning about Redis, and how its blazing fast since its an in-memory database. In my Django application, I have a Postgres table with about 1500 rows in it. The model only has two fields 'name' and 'occurrence'. To test out how much faster it would be to query for objects out of memory, compared to from my local database, which I believe is stored on disc, I created two queries 1) Simple order by query using Django objects manager 2) ZRANGE command on Redis server, getting same items back from a Redis sorted set. After making both queries, I found that getting the same number of items from a Redis sorted set took 250 times longer than it took to make the Postgres Query. Why is this ? Script def get_word_results(request): now = datetime.datetime.now() words = Word.objects.all().order_by('-occurrence') after = datetime.datetime.now() diff = (after - now).total_seconds() * 1000 print(diff) rnow = datetime.datetime.now() words_redis = redis_server.zrange(name='myzset', start=0, end=-1, withscores=True) rafter = datetime.datetime.now() diff2 = (rafter - rnow).total_seconds() * 1000 print(diff2) Results 0.199 48.048 -
django heroku server error
i have a django project which was uploaded to heroku. In my django project I used redis also to store some data. the application works on heroku but It happens that when ever I click a link, I get the error Server Error (500) I do not know the cause of the error but here is my redis setting that I use on local and development server. #REDIS FOR VIEWS REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 3 further codes would be provided on request -
How to execute Django project commands from Visual Studio
I can't find a way to run Django commands within a Visual Studio Project. I need to run the following command to fix my recent migration issue: python manage.py makemigrations --merge I found 2 options to open a command window, but none of them is suitable for this type of action (Open Interactive Window & Open in PowerShell). existing VS options Django Management Console Please advise. -
django db routing incorrect migrations
I've got a setup where my django instance is using 4 different databases. I've written a router per db to ensure I am writing to the correct db: class AppRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp': return conf['db_name'] return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp': return conf['db_name'] return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'myapp' or \ obj2._meta.app_label == 'myapp': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'myapp': return db == conf['db_name'] return None This router is supposed to write/read/migrate some specific models to the db in question. This db should not contain the default tables. However when migrating, both my default db and this db will receive all models from auth and other packages. settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DEFAULT_DB_NAME'), 'USER': config('DEFAULT_DB_USER'), 'PASSWORD': config('DEFAULT_DB_PASSWORD'), 'HOST': config('DEFAULT_DB_HOST'), 'PORT': config('DEFAULT_DB_PORT', cast=int), 'COMMAND_TIMEOUT': 5, 'ATOMIC_REQUESTS': True, }, 'myapp': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('MYAPP_DB_NAME'), 'USER': config('MYAPP_DB_USER'), 'PASSWORD': config('MYAPP_DB_PASSWORD'), 'HOST': config('MYAPP_DB_HOST'), 'PORT': config('MYAPP_DB_PORT', cast=int), 'COMMAND_TIMEOUT': 5, ......... }, DATABASE_ROUTERS = [ 'myapp.db_router.AppRouter', 'myapp2.db_router.AppRouter', 'myapp3.db_router.AppRouter', 'myapp4.router.Router', ] Thoughts? :) -
Enums in Django and Graphene always result in null
I am having some issues trying to use enums with Django and Graphene. Even though the values of the enum are persisted in the SQLite and are retrieved properly, it keeps resulting in an error. Below is a sample of the error. { "message": "Cannot return null for non-nullable field DjangoObject.vanillaEnum.", "locations": [ { "line": 10, "column": 5 } ] }, I'm using Django 2.0.3 and Graphene 2.0.1 with Anaconda3 5.0.0 and Python 3.6.4. I managed to reproduce the error using a trivial example, which is available on my GitHub account. In the models.py, I defined a Python Enum and a Django model that uses that enum. The models here work as intended (AFAIK) without involving any Graphene dependencies. The default SQLite database also appears to have the correct values. models.py import enum from django.db import models @enum.unique class VanillaEnum(enum.Enum): RED = enum.auto() BLUE = enum.auto() GREEN = enum.auto() @classmethod def choices(cls): return tuple((x, x) for x in cls) class DjangoModel(models.Model): name = models.CharField(max_length=20) vanilla_enum = models.CharField(choices=VanillaEnum.choices(), default=VanillaEnum.GREEN, max_length=20) def __str__(self): return f'name={self.name}, vanilla_enun={self.vanilla_enum}' Next, in the schema.py, I defined the two enums. One uses the graphene.Enum.from_enum to convert the VanillaEnum into one that supposedly Graphene can use. The second … -
Fail to return context and var to the html in django
I want to render context_dic and the current time to my html file(inherit form another html) But it doesn't work. Could anybody help me fix this problem? Thanks a lot! This is my python file def homepage(request): now=datetime.datetime.now() list_list = List.objects.order_by('author') context_dict = {'Lists': list_list} return render(request, ('index.html',context_dict), {'current_date':now}) And here is my base.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>This is my base page.</title> </head> <body> <p>Hello.</p> {% block content %}{% endblock %} </body> {% block footer%} <p>It is now {{current_date}}.</p> {% endblock %} </html> And index.html {% extends "about.html"%} {% block content %} {% if lists %} <ul> {% for list in lists %} <li><a href="/List/{{ list.slug }}">{{list.title }}</a> </li> {% endfor %} </ul> {% else %} <strong>There are no lists present.</strong> {% endif %} {% endblock %} My url is like this url(r'^home',homepage), -
Django rest framework Custom User model with token error
I've tried to use custom user model instead of default user. My Django project structure is below. Project name : project_rest App name : app_rest To make it happen, I refer https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model [settings.py] AUTH_USER_MODEL = 'app_rest.User' [models.py] from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from django.contrib.auth.models import AbstractUser @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class User(AbstractUser): username = models.CharField(unique=True, null=False, max_length=254) password = models.CharField(max_length=200) [serializers.py] from app_rest.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') [views.py] from django.shortcuts import render from app_rest.serializers import UserSerializer from app_rest.models import User from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer [urls.py] from django.conf.urls import url, include from app_rest import views from rest_framework import routers from django.contrib import admin from rest_framework.authtoken import views as rest_views router = routers.DefaultRouter() router.register(r'user', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^token-auth/', rest_views.obtain_auth_token), url(r'^admin/', admin.site.urls), ] I seems work properly, But when I delete user, It throws error. IntegrityError at /admin/app_rest/user/1/delete/ (1452, 'Cannot add or update a child row: a foreign key constraint fails ('rest'.'django_admin_log', CONSTRAINT 'django_admin_log_user_id_c564eba6_fk_auth_user_id' FOREIGN KEY ('user_id') REFERENCES … -
How can I set/provide a default value while django migration?
Scenario: I have a model, Customer class Customer(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() company = models.CharField(max_length=100) and now I updated the company attribute witha ForeignKey relationship as below, class Company(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=100) class Customer(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() company = models.ForeignKey(Company) What I need is, when the new migrations applied to the DB,corresponding Company instance must automatically generate and map to the company attribute of Customer instance.Is that possible? How can I achieve this ? -
How to disable IE11 cache in django REST
I have some Internet Explorer problems with my Angular 5 app, because in the IE 11 my get-requests to a django-REST backend are cached by the browser. I found a question suggesting to add special cache-control-headers to the response, but I didn't find a working answer how to do it with Django REST. All other browsers I have tested seem to work without problems. -
Django won't start tests, complaining on fixtures
I'm trying to test an app after making a dump, but Django raises the following error: django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'auth_permission' with primary key '65' has an invalid foreign key: auth_permission.content_type_id contains a value '17' that does not have a corresponding value in django_content_type.id. The problem is that there's no row with primary key 65 in auth_permission table. I've tried --natural-primary/--natural-foreign, but this won't help. Please help. -
Django templating: extend a block in same template?
So here is the set up (simplified for here): In my template file I have two sections I would like to add content too by looping of a list of dictionaries, e.g.: <div class="stuff-a"></div> <div class="stuff-b"></div> {% for thing in list %} <!-- goes into div a --> <!-- goes into div b --> {% endfor %} I thought this would work: <div class="stuff-a"> {% block diva %}{% endblock %} </div> <div class="stuff-b"> {% block divb %}{% endblock %} </div> {% for thing in list %} {% block diva %} thing.stuff_for_div_a {% endblock %} {% block divb %} thing.stuff_for_div_b {% endblock %} {% endfor %} and then django complains about me using each block more than once - shame on me. Now the solution to this (keeping the same schema) is to make an intermediate template file and then extend it. My question is, is there a way to append to different specific areas in a django template without having to loop through a list twice or an intermediate template file? This matters if the loop is somewhat complicated and you dont want to have to update two loops whenever you make a change. When might this occur in practice … -
PIL - saving image as .jpg not working
I'm trying to overwrite save() method of the model to resize images. Every format works, except when saving a .jpg image. It's not saving images with .jpg extension. I read the Pillow documentation and there's no JPG format. class Business(models.Model): photo = models.ImageField(_('photo'), storage=OverwriteStorage(), upload_to=image_upload_to, blank=True, null=True) def save(self, **kwargs): """ Changing dimensions of images if they are to big. Set max height or width to 800px depending on the image is portrait or landscape. """ # Opening the uploaded image im = Image.open(self.photo) print(im) output = BytesIO() # set the max width or height im.thumbnail((800, 800)) # find the ext of the file ext = self.photo.name.split('.')[1].upper() if ext in {'JPEG', 'PNG', 'GIF', 'TIFF'}: # after modifications, save it to the output im.save(output, format=ext, quality=100) output.seek(0) # change the imagefield value to be the newley modifed image value self.photo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.photo.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(User, self).save() I don't know what I am missing here. And what's the best way to do this on a custom User model. Using a signal, overwriting ImageField or ... Any help is appreciated :) -
django haysteck FacetedSearchView returning empty results?
I'm using Django haystack FacetedSearchView my views.py: from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView class FacetedSearchView(BaseFacetedSearchView): template_name = 'test.html' facet_fields = ['source'] and in urls.py: url(r'^search', FacetedSearchView.as_view(), name='haystack_search') and in test.html I'm printing the facets. when I issue request as follow: 127.0.0.1:8000:/search the content of the factes context object is empty dict. but I think it should return all the I specified facets in facets_fields, and when I append q parameter to the request's querystring (with any value) it returns result but with zero document. is it neccessary to provide the q parameter? and with which value? -
Django Get None After User Authentication
def login_page(request): form = LoginForm(request.POST or None) context = { "form" : form } print("User logged in") print(request.user.is_authenticated()) if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username = 'username', password = 'password') print(user) if user is not None: print(request.user.is_authenticated()) login(request, user) # Recirect to a success page. # context['form'] = LoginForm() return redirect("/contact") else: # Return an 'invalid login' error message. print("Error") return render(request, "auth/login.html", context) I try to create a login page but I get value of 'user' None so I took error everytime. I use Django 1.11. -
Django - Raise form error without cleaning data
Is there any way in django to raise a form validation error without cleaning the data? I am fetching the data through form['field'].value(), and I want to show the error in the template if it is beyond a certain value. -
how to display information entered by a user into a django model in the User profile
i'm kinda new to django, i'm working on a project currently. its a website where people can look for houses to rent. users will be able to create accounts, search for houses to rent and create listings about the houses they want to rent out. i created a model to save all the information about houses that users want to rent out. i need to filter this information and display each users listing on their profile. ive searched online but no solution yet. Really need help. models.py from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField() availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') def __str__(self): return self.name_of_accomodation view.py class ListingByUser(LoginRequiredMixin, generic.ListView): def get( self): model = Myhouses template_name ='houses/ListingByUser.html' paginate_by = 10 def get_queryset(self): return Myhouses.objects.filter(author=self.request.user) urls.py from django.conf.urls import url, include from . import views from django.contrib.auth.models import User urlpatterns = [ url(r'^addlisting/$', views.addlisting, name='addlisting'), url(r'^mylisting/', views.ListingByUser.as_view(), name='ListingByUser') ] template {% for houses in myhouses_list %} {{ houses.name_of_accomodation … -
Django: how to display ProductImage from Product model
class Product(models.Model): company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True) class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) image_path = models.ImageField(max_length=255,null=True,blank=True,upload_to='images/%Y/%m/%d') in my views.py class HomeView(ListView): template_name = "catalog/product_list.html" context_object_name = 'product_list' model = Product in product_list.html {% if product_list %} {% for product in product_list %} <!-- the problem is here --> if there is an image show <img src="default" /> else <img src="product.ProductImage.image_path here" /> {% endfor %} {% endif %} the problem is in the iteration of the product_list i tried, productImage = product.[productImage or product_image or is it productimage].first() but it doesn't work i also tried {% img = '' try: productImage = product.productimage_set.first() img = productImage.image_path except ProductImage.DoesNotExist: img = '' %} <img class="card-img-top" style="height: 225px; width: 100%; display: block;" src="{{product_image.image_path}}" data-holder-rendered="true"> {% %} but it just outputs the code block -
Can't display database data in Django
I am working on library website in which I want to display data from database which is Book name and description. But i'm not ale to do that here is my code views.py from django.shortcuts import render from .models import * def index(request): book_list = Book.objects.all() return render(request,template_name='index.html', context={'book_list':book_list}) index.html {% extends "base_generic.html" %} {% block new_books %} {% for b in book_list %} <div class="card"> <img class="card-img-top" src=".." alt="Image"> <div class="card-body"> <h5 class="card-title">{{ book_list }} </h5> <p class="card-text">Hello this is card text</p> <a class="btn btn-primary">View this book</a> </div> </div> {% endfor %} {% endblock %} -
Django: How do I return data from db along with the foreign key entities to the user as JSON?
I have two models as such, class Foo(models.Model): name = models.CharField(max_length=100, unique=True) city = models.CharField(max_length= 50) .... and class Bar(models.Model): Foo = models.ManyToManyField(Foo) name = models.CharField(max_length=20, unique=True) I have a view that returns Foo objects as JSON, def list_by_city(request, city): foo_list = Foo.objects.filter(city=city).values() return JsonResponse({"Foo": list(foo_list)}) But this returns only the attributes from Foo. I want to add the attributes from Bar as well, which are related to Foo. How do I do that? -
Saving model Formset
This is a quicky. I have a formset based on a model. I am trying to save it on a POST request as follows: . . . if request.method=='POST': FormsetItem=ItemFormSet(request.POST,queryset=Item.objects.filter(budgetcatagory__user_id=U.id)) FormsetCat=CatFormset(request.POST) if FormsetItem.is_valid(): FormsetItem.save() . . . Since this isn't working, i.e. my database remains unchanged after save, I'm assuming this is not the way to go about it. Do I have to individually save each form in the set? Thanks -
Takes very long for an image/video to be uploaded to my Amazon S3 media directory
So I'm using Amazon S3 storage to store user-uploaded files. When a user makes a post on my Django website, it comes with some text and an image/video - that image/video gets uploaded to the media directory on my S3 bucket. However this takes very long, e.g. including a 6mb image in the post will take the post over a minute to submit. If the image is small e.g. 150kb it will only take about 3 seconds for the post to submit. How can I improve this performance? The Post is simply a form with the following fields (image is either an image or a video): class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=95) date = models.DateTimeField(auto_now_add=True) content = models.TextField(null=True, blank=True) image = models.FileField(null=True, blank=True) and the views: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/home/') else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") Any idea?