Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template set template variable within IF statement?
Im receiving the error Invalid block tag on line 15: 'set', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? this is right underneath the Showroom statement, when trying to set some variables within a template as per the below:- {% for type in live_sites %} {% if type.site_type == 'Showrooms' %} {% set ShowroomCount = type.total %} {% elif type.site_type == 'Major Site' %} {% set MajorCount = type.total %} {% elif type.site_type == 'Transport Office' %} {% set TransportCount = type.total %} {% endif %} {% endfor %} is this possible? I have a query as per the below class LiveSite(object): def __init__(self, site='', no='',): self.sender = site self.subject = no def __repr__(self): return '{} {}'.format(self.__class__.__name__, self.site) # Live site data live_site_count = SiteData.objects.values("site_type").filter(is_live=True).annotate(total=Count('site_type')).order_by('total') live_sites = [] for i in live_site_count: live_site = LiveSite() live_site.sender = i["site_type"] live_site.no = i["total"] live_sites.append(live_site) I need to do something different with each of the three values that this returns, so rather than running a loop three or more times and doing an if within each loop I thought it better to run the loop once and set variables I can use later, is this the best … -
How should I write view unittest in Django?
I want to write unittest for this methon in django. def activate(request): id = int(request.GET.get('id')) user = User.objects.get(id=id) user.is_active = True user.save() return render(request, 'user_authentication/activation.html') I wrote sth like this: def test_activate_view(self): response = self.client.get('/activation', follow=True) self.assertTemplateUsed(response, 'user_authentication/activation.html') It doesn't work because I get an error: id = int(request.GET.get('id')) TypeError: int() argument must be a string or a number, not 'NoneType': What should I change in my test? -
Django template is not showing the maximum value
I am having trouble displaying the maximum value on the html template from my mysql database. my view: from django.contrib.auth.decorators import login_required from django.db.models import Count, Min, Sum, Avg, Max from .models import Gwtable import datetime def index(request): maxiumum_value = Gwtable.objects.all().aggregate(Max('salesprice')) my html <div> <p> {{ maxiumum_value.values|floatformat:2 }}</p> </div> my shell test to prove the data is there -
Default django object to be used as a base
I'm trying to set up a site on which members of a team can create games which can have a variety of settings (things like the maximum number of players). The team will have a settings object which will contain default values for these settings but the users can change these values for each game if they like (without affecting the team's defaults). I'm wondering what the best way to set this up is. So, given the following model:- class GameSettings(models.Model): max_players = models.IntegerField(default=10) etc. should I a) add a one-to-one relationship to GameSettings to both the Team and the Game model, like this:- class Team(models.Model): gamesettings = models.OneToOneField(GameSettings) class Game(models.Model): gamesettings = models.OneToOneField(GameSettings) or b) add 2 one-to-one relationships to the GameSettings model, like this:- class GameSettings(models.Model): group = models.OneToOneField(Group, null=True) game = models.OneToOneField(Game, null=True) max_players = models.IntegerField(default=10) etc. The most sensible solution seems to be a) but if I go for that then I need to somehow copy the Team's gamesettings whenever a new Game is created. But how? Or does b) make more sense? -
Modifying Django settings in tests
From Django docs: You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view: from django.conf import settings settings.DEBUG = True # Don't do this! The only place you should assign to settings is in a settings file. I've noticed that Django testing code does alter settings. Why is it ok to do it there? -
Django Model serving Media Files
I have two models: Packages and Images. Images has many to one relation with Packages. Images table has a foreign key package_id. I have to display the attributes country, price of Packages with one image related to the package. There can be many images related to a single package however, I have to choose only one. The table looks like: Packages: id country price Images: id url package_id My code looks like: Views.py def index(request): featured = Package.objects.filter(featured=True).order_by('-pub_date')[:4] featured_packages = [] for item in featured: image = item.packageimages_set.all()[1] data = {'package': item, 'image': image} featured_packages.append(data) context = {'featured': featured_packages} return render(request, 'tours/index.html', context) Index.html {% for item in featured %} <p>Country: {{item.package.country}}</p> <p>Price: {{item.package.price}}</p> <p>Image: <img src="{{item.image.url}}"></p> {% endfor %} Everything seems fine I get the URL. However, I am not getting the output. The output looks like this: Where are my errors? I am not being able to display the image. And is there anything more efficient to do the above task? -
Mac/Django Error: Command "python setup.py egg_info" failed with error code 1
I'm on a Mac OSX v10.13.2 trying to install and get started on a Django Project. The error is a relatively common one, and I cannot get the pip install django command to work. I keep getting the following error codes. I have tried it before and after activating virtualenv. Collecting django Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 99kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-tG2yPn/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-tG2yPn/django/ pip install ez_setup <- works successfully pip3 install django <- works, and demonstrates the following (as I have used it to install): Requirement already satisfied: django in /usr/local/lib/python3.6/site-packages Requirement already satisfied: pytz in /usr/local/lib/python3.6/site-packages (from django) brew install python3 <- demonstrates python3 already installed easy_install -U setuptools <- works and successfully installed Despite all this, the failed with error code 1 keeps coming up, and I can't get to the next steps. -
How Django get the live_server_url?
I learned Django functional test from the TDD with Python and adjust to my project. My FT is really simple, check the title of url. I use live_server_url to test by selenium. But it goes to another port number(56458), not 8000. (When I follow the book, it wasn't) $ python manage.py runserver & ... Starting development server at http://127.0.0.1:8000/ ... $ cat functional_test/tests.py ... def test_render_a_list_of_candiates_in_home(self): print(self.live_server_url) self.browser.get(self.live_server_url) ... $ python manage.py test functional_test ... http://localhost:56458 E ====================================================================== ... Doc says: The live server listens on localhost and binds to port 0 which uses a free port assigned by the operating system. The server’s URL can be accessed with self.live_server_url during the tests. So I try to look listening ports(I think I'm immature for this part): $ netstat | grep LISTEN $ # nothing printed! -
Django Project/Site--CSS changes appear on Safari not on Chrome
I need some help. I prepare to change my site and working on a django project. The thing is the fact that all the changes i am doing in the static files go through correctly in Safari, but are not visible in Chrome. Do you know why this happens? Please see below the image from Chrome. What you see white in the image is in fact, the image not going through Chrome. Please see below the image from Safari Also can someone please share with me some resources where i can find a blog/site where they teach you how to find correctly the CSS locator, while doing Inspect Element in the browser, in order to change different CSS attributes for images etc? I will owe you a lot! Maybe i am doing something which is not ok. Please find below the part from the base.html {% extends "base.html" %} {% load staticfiles %} {#{% block head_title %} {% endblock %}#} {% block content %} <div class="container-fluid" id="primapagina" style="background-image: url('{% static "img/shutterstock_4.jpg"%}')"> <img id="our_logo" src={% static "/img/lastlogo.png" %}> <p id="banner-text"> Lore Ipsum etc </div> {% endblock %} Please find below my CSS code: .container-fluid { background-size: cover; height: 1000px; } textarea … -
Django - Select a valid choice. That choice is not one of the available choices
Here are my forms: class RoleForm(forms.ModelForm): class Meta: model = models.RoleModel fields = ['name'] class FeatureForm(forms.ModelForm): role = forms.ModelChoiceField(queryset=models.RoleModel.objects.values_list('name', flat=True).distinct()) class Meta: model = models.FeatureModel fields = ['role','feature'] In my bootstrap form, the choices display properly. I get a list of all roles. But if I fill the feature form and hit submit it says - "Select a valid choice. That choice is not one of the available choices." My models are: class RoleModel(models.Model): name = models.CharField(validators=[alphanumeric], max_length=50, unique=True, blank=False) class FeatureModel(models.Model): role = models.ForeignKey(RoleModel, on_delete=models.PROTECT) feature = models.CharField(validators=[alphanumeric], max_length=10, unique=True) my bootsrtap form is: <form action="{% url 'feature_form' %}" novalidate method="POST">{% csrf_token %} <div class="row"> <div class="col"> <label for="role">{{ fform.role.label }}</label> <p><select class="form-control id="role" name="role"> {% for item in fform.role %} {{ item }} {% endfor %} </select></p> {% for error in fform.role.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> <div class="col"> <label for="feature">{{ fform.feature.label }</label> <p><input type="text" class="form-control" id="feature" name="feature" {% if fform.feature.value is not None %} value="{{ fform.feature.value }}" {% endif %} ></p> {% for error in fform.feature.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> </div> <input class='btn btn-primary btn-sm' type='submit' value='Save'> </form> My need is simple. The second form (FeatureForm) has two … -
Adding multiple context in a try except situation
I am trying to import some data into my HTML using context right now my code is the following and is working great. I am using a Try/Except because a project is not always created and kwargs['pk1']) does not always exist: my working code: class ProjectDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = Project template_name = 'project_details.html' def get_object(self, queryset=None): return get_object_or_404(Project,id=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) try: team_name = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all() context['team_name'] = team_name except AttributeError: pass return context THe thing is I would like to add another key pair to that context and from there I always get an Reverse for 'team_select' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['website/project/(?P[0-9]+)/linkteam2/$'] I tried : def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) try: team_name = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all() team_score = get_team_cohesivenss_score(self) m_context = {'team_name':team_name, 'team_score':team_score } context = m_context except AttributeError: pass return context any idea ? thx you -
Django Model Design (Big model vs multiple)
I have a question about designing my models. Suppose I have a following model: class Comment(models.Model): who = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=1000) likes = models.IntegerField(default=0) parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments') Now I would like models for multiple topics (ShoppingList, Games,...). I came to two possible solutions and need help with deciding more suitable one. 1) Make Comment abstract and extend it for every new model wanted. class ShoppingListComment(Comment): shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE) I could then query this game comments with something like: ShoppingListComment.objects.all() 2) Add extra nullable Foreing keys directly to comment: class BigCommentModel(models.Model): who = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=1000) likes = models.IntegerField(default=0) parent_comment = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='child_comments') shopping_list = models.ForeignKey(ShoppingList, related_name='shopping_comments', on_delete=models.CASCADE, null=True), game = models.ForeignKey(Game, related_name='game_comments', on_delete=models.CASCADE, null=True) I could then query this game comments with something lile: BigCommentModel.objects.filter(game__isnull=False) -
Running Django on Heroku Local using Python 3.X on MacOSX
I want to run my django app on heroku local and i wish to run python 3.X. I have Python 3.6 installed from the python website. However the default version of python on the system in 2.7. How can I get heroku local to use python 3? Should I always use a virtual environment to do this? -
I have an internal server error when using Django app deployed to Heroku. The app works locally
I have made an instagram like django app that works perfectly fine locally, however after I deployed the app to heroku, whenever I try to upload and save a photo, I get an internal server error(500). I am using the Uploadcare API to upload and save photos. I am not sure how to fix this problem. the photos below are the heroku logs i get. this is my models.py from django.db import models class ValidationInfo(models.Model): val_school_id = models.CharField(max_length=5) val_school_pass = models.CharField(max_length=10) class User(models.Model): is_authenticated = True school_name = models.CharField(max_length=50,default="") school_id = models.CharField(max_length=50,default="") password = models.CharField(max_length=100) email = models.CharField(max_length=100) username = models.CharField(max_length=20) sign_up_date = models.DateTimeField(auto_now=True) last_login = models.DateTimeField(auto_now=True) profilepic = models.CharField(max_length=255, default="") class Photo(models.Model): baseurl = models.CharField(max_length=255) url = models.CharField(max_length=255) date_uploaded = models.DateTimeField(auto_now=True) owner = models.CharField(max_length=20) likes = models.IntegerField() caption = models.CharField(max_length=140, default="") tags = models.IntegerField(default=0) main_colour = models.CharField(max_length=15, default="") owner_school = models.CharField(max_length=30, default="") class PhotoLikes(models.Model): postid = models.IntegerField() liker = models.CharField(max_length=20) class Followers(models.Model): user = models.CharField(max_length=20, default="") follower = models.CharField(max_length=20, default="") class PhotoTag(models.Model): photoid = models.IntegerField() coords = models.CharField(max_length=40) tagged_user = models.CharField(max_length=20, default="") tagged_by = models.CharField(max_length=20, default="") this is my Ajax and AjaxSavePhoto class in forms.py class Ajax(forms.Form): args = [] user = [] def __init__(self, *args, **kwargs): self.args = … -
Coding mental block with specific Django task
I've been thinking of this for a LONG time the past few days and can't figure out with my current toolset how to implement this in Django. What I want is something that can be implemented trivially in Java for example, but how I'd do that on the web is much more difficult The problem I want to send data to a HTML template, specific example: "What is 5 + 50?" The data must be dynamically generated, so the 5 and 50 are actually randomly generated. I think I am comfortable doing this part, as I'd simply pass a random variable to a template using the views.py This is where I do not know how to proceed I want the user to be able to enter their answer, and have them notified if it correct. To do this, I'd need to pass the variables from the template back to another view function. I am not sure how to do that, if it is possible at all. This is how I'm deciding to pursue my projecti dea, and I'm not sure if this is the most efficient way tl;dr I just wanted data to be randomly generated and calculated using Django -
Images cannot be saved in db
Images cannot be saved in db.I wrote in views.py @csrf_exempt def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() return render(request, 'registration/photo.html') else: form = UserImageForm() return render(request, 'registration/profile.html', {'form': form}) in models.py class ImageAndUser(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin",on_delete=models.CASCADE) image1 = models.ImageField(upload_to='images', null=True, blank=True,) image2 = models.ImageField(upload_to='images/', null=True, blank=True, ) image3 = models.ImageField(upload_to='images/', null=True, blank=True, ) in forms.py class UserImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = ImageAndUser fields = ('image',) in profile.html <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <label class="input-group-btn"> <span class="file_select btn-lg"> File Select1 <input id="file1" type="file" name="image" accept="image/*" style="display: none"> </span> </label> <input type="text" class="form-control" readonly=""> <label class="input-group-btn"> <span class="btn-lg file_select"> File Select2 <input id="file2" type="file" name="image2" accept="image/*" style="display: none"> </span> </label> <input type="text" class="form-control" readonly=""> <label class="input-group-btn"> <span class="btn-lg file_select"> File Select3 <input id="file3" type="file" name="image3" accept="image/*" style="display: none"> </span> </label> <input type="text" class="form-control" readonly=""> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> <input id="send" type="submit" value="SEND" class="form-control"> </form> When I uploaded 3 images from html and SEND button, no image was not saved.But after sending SEND button,photo.html is shown, so program was successful.I cannot understand why 3 images cannot be saved.I wrote data.save().How should … -
Django-SessionId: Why i get same session id upon opening 2 tabs in chrome for same url (127.0.0.1:8000?
I am new to django (or web development). I see same session id for two instances for my test project, is there any way to get unique id every time user opens that url? I am not using any user login here. views.py: def index(request): print(request.session.session_key) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$', views.index,name='index'), ] Output on server: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. q4ynuuj7hbugoxcn7to0izr39nip4of6 <QueryDict: {}> [31/Dec/2017 13:29:49] "GET / HTTP/1.1" 200 8224 q4ynuuj7hbugoxcn7to0izr39nip4of6 <QueryDict: {}> [31/Dec/2017 13:29:54] "GET / HTTP/1.1" 200 8224 -
The submitted data was not a file. Check the encoding type on the form?
I have a serializer called ProjectSerializer. It has a file field. The view is: class ProjectCreate(CreateAPIView): serializer_class = ProjectSerializer When I post data from html form in django rest framework, it works the file gets uploaded. But when I use the raw data as json and send data by using url of the file content the error arises: { "project_question_content_url": [ "The submitted data was not a file. Check the encoding type on the form." ] } The problem is I am using jquery to provide the url ..But before sending the url from jquery I tested in the api. It gives the error while providing the url . -
How to do performance optimization while serializing lots of GeoDjango geometry fields?
I'm developing a GeoDjango app which use the provided WorldBorder model in the tutorial. I also created my own Region model which is tied to WorldBorder. So a WorldBorder/Country can have multiple Regions which has borders (MultiPolygon field) in it too. I made the API for it using DRF but it's so slow, it takes 16 seconds to load all WorldBorder and Regions in GeoJSON format. The returned JSON size is 10MB though. Is that reasonable? I even change the serializer to serpy which is way much faster than the DRF GIS serializer but only offers 10% performance improvement. Turns out after profiling, most of the time is spent in the GIS functions to convert data type in the database to list of coordinates instead of WKT. If I use WKT, the serialization is much faster (1.7s compared to 11.7s, the WKT is only for WorldBorder MultiPolygon, everything else is still in GeoJson) I also tried to compress the MultiPolygon using ST_SimplifyVW with low tolerance (0.005) to preserve the accuracies, which brings down the JSON size to 1.7 MB. This makes the total load to 3.5s. Of course I can still find which is the best tolerance to balance accuracy … -
Django authenticate method not working
I am trying to use the default Django from django.contrib.auth authenticate() method to authenticate if the user exists. I am doing this right after the user registers. The user registers and their username, email, and password is inputted into the database, but when I call authenticate(username=username, password=password) it is returning None for some reason. The password is being stored as a hash and it is worth to note that I am using my own custom User model, but inheriting from django.contrib.auth User model. Here's my view: class RegisterView(SuccessMessageMixin, View): form_class = RegisterForm template_name = 'oauth/auth_form.html' success_message = "You have successfully created an account!" # Display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # Do not save to table yet username = form.cleaned_data['username'] password = form.cleaned_data['password'] try: validate_password(password, user) except ValidationError as e: form.add_error('password', e) # to be displayed with the field's errors return render(request, self.template_name, {'form': form}) user.set_password(password) user.save() # Let's try to login the user user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('http://google.com') return render(request, self.template_name, {'form': form}) Why is it that the authenticate method is not … -
Django where is the many to one picker widget?
For each row of table A, I want to be able to add one or more rows from table B. The Django admin has an example, the user permissions picker -- I attach a screen shot. Each user can have any number of permissions. The permissions start on the left. When you add one, it moves to the right. You can move them back and forth. That is what I want for two of my own models. How do I get this widget? -
I deleted a css static file but my website still reads it?
I have a static css file called blog.css, and I load it in my base.html template like this: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/blog.css' %}"> But when I wanted to change something in that css, the changes doesn't appear. Due to my confusion, I tried to test some things. renaming blog.css to blog2.css The weird part is, when I make changes to blog2.css, and called it in the base.html, my changes work, such as changing the background color, and etc. but when I make changes to blog.css, nothing happens. So, I tried to DELETE blog.css, but still called it in the base.html. everything still works when I first made that file. I'm supposed to be expecting a broken designed HTML page and a 404 in the console because the blog.css in the static folder cannot be found. It's like the blog.css is a ghost or something that is still here in my folder somewhere.. or am I missing something? I also tried restarting the runserver command, refreshing the page countless times, and even restarting my computer. I'm quite new to Django and I'm trying my best to understand it, and any help given is appreciated. Thank … -
How to use JavaScript with Django?
I would like to pass data from a View to a javascript file. I tried the way I thought would work, I added: script src="{% static 'javascript.js' %}"> To the bottom of my HTML document, and loaded static files but when I went to write var a = {{ c }}; it did not work. How should I approach this? -
Django restrict data that can be given to model field
I have the following model in django: class Cast(TimeStampedModel): user = models.ForeignKey(User, unique=True) count = models.PositiveIntegerField(default=1) kind = models.CharField(max_length = 7) def __str__(self): return(f"{self.kind} || {self.count} || {self.modified.strftime('%x')}") But I want the 'kind' field to only take one of the following values: up, down, strange, charm, top, or bottom. How can I enforce this in the database or can this only be enforced in the views when taking in data? -
Django password validation not working
I am using my own custom User model, but I'm inheriting off of django.contrib.auth User model. I have a username, email, and password field. I don't explicitly add the password field because it gets added by default by the inheritance. When I try to create a superuser through the command line, the normal default Django password validation is working correctly. However, when I have a sign up form, it is not. Email and username validation are working properly when I click submit, but there is no password validation. I can enter whatever I want and it would accept the password. Here's my forms.py class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) Here's my view: class RegisterView(SuccessMessageMixin, View): form_class = RegisterForm template_name = 'oauth/auth_form.html' success_message = "You have successfully created an account!" # Display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # Do not save to table yet username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # Let's try to login the user user = …