Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multi imagefield from one imagefield _ django restframework
the question is : is there any proper way for creating multi Imagefields beside making multi image fields in django models? my goal is create an post model that may has multi image field but not mean it should always has.maybe one post object contain one image or may has multi image. so its not a good idea to make multi rows on database that includes null imagefield values. I checked the stackoverflow for similar questions but need to know a proper way and the solution must work in django restframework easily.any reference or help would be greateful . the question two is how to convert the size of the uploaded image for saving storage? -
Python django test case - one test failing when all tests are ran - Class variable data remaining during test
I have a dictionary which is a class variable. One test will run methods which populates this dictionary in the course of the test. There is an if statement in the code(not the tests) which basically says if dict do this. Else do this. However when i run another test which does not populate this dict the dict is already populated with the old data,and hence the if code is executed. How can i wipe the old data from the class variables -
How to return data in JSON format in Django
I want to return some data in JSON format, I created serializers.py class LocationSerializers(serializers.EmbeddedDocumentSerializer): class Meta: model = location fields = '__all__' class ProductsSerializers(serializers.DocumentSerializer): location = LocationSerializers(many=True) class Meta: model = products fields = ('picture', 'name', 'email', 'city', 'location') Models.py class location(EmbeddedDocument): type = fields.StringField() coordinates = fields.ListField(FloatField()) class products(Document): picture = fields.StringField() name = fields.StringField() email = fields.StringField() city = fields.StringField() location = fields.EmbeddedDocumentField('location') and views.py def get(self, request): prd = products.objects.all() data = ProductsSerializers(prd,many=True) return Response(data.data) When i return one product it work but wehn i want to return all didn't work I don't understand error The fields "{'_ref'}" do not exist on the document "location" -
ModuleNotFoundError: No module named 'mysite'
I have setup Python, Django and MySQL on my Windows machine. I'm trying to verify my database connection by running the following from a directory named 'zibit': > myvenv\Scripts\activate > set DJANGO_SETTINGS_MODULE=mysite.settings > django-admin dbshell After running the last command I get this error: ModuleNotFoundError: No module named 'mysite' I tried updating my wsgi.py file to the following after seeing some related posts online: import os from django.core.wsgi import get_wsgi_application import sys path = 'C:\Users\abc123\Documents\zibit' sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() My folder structure looks like this: zibit | +--mysite | | | +--settings.py | +--myvenv I feel like I'm missing something very simple. Any ideas? -
Django - List of tuples field
I have a django model, which would need one field that contains a list of Tuples that can be filled in by the admin in the admin view as needed. Currently, I was able to find a ListField, which is only accessible by Postgres (I am using MySQL). How would I most elegantly solve this problem? (The number of tuples which need to be filled in varies per model, so I guess creating many fields would be the sloppiest approach). Thanks in Advance -
Django custom user model creating instance along with nested object instance
I have a model 'Reader' which extends the default 'User' model: class Wishlist(models.Model): wishlist_id = models.AutoField(primary_key=True) class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) address = models.CharField(max_length=80) dob = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) wishlist = models.OneToOneField(Wishlist, null=True, blank=True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.user) Question 1: Can I directly create a Reader instead of User (without having to associated a reader to an existing User, which I currently see in my admin interface), and in that case how should my POST call look like? For registering new user currently I need Username, password1, password2. Question 2: While creating a Reader I also want to create a Wishlist for that Reader. How to achieve that? So far I have a serializer: class ReaderSerializer(serializers.ModelSerializer): class Meta: model = Reader fields = '__all__' #depth = 1 def create(self, validated_data): wishlist_data = validated_data.pop('wishlist') reader = Reader.objects.create(**validated_data) Wishlist.objects.create(reader=reader, **wishlist_data) return reader And a view: # Get all readers in a specific library or create a new reader @api_view(['GET', 'POST']) def reader_list(request, library_id): """ List all readers in a specific library, or create a new reader for a … -
verbose_name get uppercased in Django model
All of my model fields are shown uppercased in the admin. How can I keep them camel-cased? Thank you (Django 1.11) -
Django registration with email confirmation (new django version)
There is new version of django and some options have changed but I couldn't figure out which exactly. And I have error for token check in: {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} Error is: Reverse for 'activate' with keyword arguments '{'uidb64': b'Mw', 'token': '4sg-dd1f81a3c683bc3cf0c9'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] https://docs.djangoproject.com/en/2.0/releases/2.0/ I tried everything, even downloaded program that does with in authentication with older products versions but in new Django it doesn't. Can anyone help to solve this? -
Django: How to pass data via lazy reverse, but not within url
I have the lazy reverse as a link on the page which leads to form and I wish to pass some values for a subset of the field? I don't want to include the value within the path of the URL, but would be happy be part of a query or session. Thank you for your time. -
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 …