Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The imageField doesnt upload images django
I am trying to upload pictures from a imageField, but it doesnt upload anything when i try. I did it before but i dont know what is causing this, everything seems to be fine, so i hope you can help me: here is my models.py: def upload_location(instance, filename): return "uploads/%s/img/%s/" % (instance.id, filename) class CustomUser(AbstractBaseUser, PermissionsMixin): ...... width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) photo = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field" ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() Here is my form: class UserConfigurationForm(UserChangeForm): class Meta: model=CustomUser fields = ( 'first_name', 'last_name', 'email', 'phone_number', 'direction', 'password', 'photo', ) Dont pay attention to the other fields apart from ´photo´,those fields works fine. just have the problem with the image My view: def configuration(request): categoria = Clasificacion.objects.filter(existencia=True) templates = Templates.objects.get(isSelected=True) if request.method == 'GET': form = UserConfigurationForm(instance=request.user) else: form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user) if form.is_valid(): form.save() return redirect('myuser:myuser') return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates}) And finally my template (I will include the entire form soyou can see it).. <form method="post" action='' enctype="multipart/form-data"> {%csrf_token%} <div class="col-sm-8 "> <strong>{{form.photo}}</strong></div> <!--FIRST NAME--> <label for="first_name">Nombre</label> <div class="form-group"> <input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required> </div> <label for="last_name">Apellidos</label> … -
Display data from a database in a HTML page using django views
I have a problem with creating a view with data from the database. I created a view that should download data from videos (var films) and display them, unstable I only have a blank page. views.py from django.shortcuts import render from django.http import HttpResponse from .models import Films # Create your views here. def index(request): filmy = Films.objects return render(request, 'films/index.html',{'filmy':filmy}) index.html <h1>Films</h1> {% for film in films.all %} {{filmy.summary}} <br> {% endfor %} models.py from django.db import models # Create your models here. class Films(models.Model): image = models.ImageField(upload_to='images/') summary = models.CharField(max_length=200) def __str__(self): return self.summary -
Python dictionary syntax error at the colon
I'm trying to make a dictionary and it gives me syntax at the colon. (Django with visual studio code) Code: def count(request): savetext = request.GET['savetext'] wordlist = savetext.split() return render(request, 'count.html',{'savetext':savetext}, 'count':len(wordlist)}) Error: 'count':len(wordlist)}) ^ SyntaxError: invalid syntax -
How can I ensure Django CMS initializes app urls?
I'm trying to boot up a Django CMS app. All the app hooks are properly set up and registered. For an example take the NewsHook: class NewsHook(CMSApp): """ A class to hook the News into the django cms """ name = _("News") urls = ["apps.news.urls"] apphook_pool.register(NewsHook) The urls.py of this hook includes the following: urlpatterns = [ # /feed/ url(r'^feed/$', ArticlesFeed(), name='news_feed'), ] And the urls.py of the project (under the settings folder) includes the following relevant lines: admin.autodiscover() urlpatterns = patterns( '', ... # / -> Django CMS url(r'^', include('cms.urls')), ) All this looks normal, right? But when I visit the home page, I get NoReverseMatch error: Not sure what I am doing wrong... Is there a side of this that I'm not seeing? Btw, this app runs well on production, so it doesn't have any bugs as far as I can see. My Specs Django version: 1.8.13 Django CMS version: 3.3.0 Python version: 2.7. -
Accessing property of model instance from list and add them together?
Say I have a model: class Mymodel(models.Model) property = models.IntegerField() Say I have a function: def func(): instance = Mymodel.objects.order_by('?')[0] instance2 = Mymodel.objects.order_by('?')[0] plan = [instance, instance2] return plan I want to use a for loop to add together the integers in the 'property' of the model instance and then output the sum into one of my templates? I have tried the add filter but the problem is the amount of instances it will be adding together are dynamic so I can't simply do myModel.0.property|add:myModel.1.property Thanks in advance. -
Getting live server fixture with Django test not working
I would like to use pytest, pytest-django, and pytest-selenium together to test my Django application functionality. If I start the server manually with python manage.py runserver, and manually input the URL, it works fine. The live_server fixture from pytest-django is supposed to start a server process in the background that I could use, but it's not working. Instead of a passing test, I get "The requested resource was not found on this server." Here are the relevant sections of my files: pytest.ini [pytest] DJANGO_SETTINGS_MODULE = chatsite_api.settings.test addopts = --liveserver localhost:8080 --cov=. --cov-report=html --driver Firefox test_pages.py import pytest def test_homepage(selenium, live_server): selenium.get(live_server.url) assert "Django: the Web framework" in selenium.title And chatsite_api.settings.test.py from .dev import * # NOQA DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} DEBUG = True As I said, the tests run fine when I start the server myself, but the live_server fixture doesn't seem to be doing what it's supposed to. I have verified that the live_server.url is being set according to the addopts line in pytest.ini, but that is as far as I've gotten. -
How to add a DialogFlow chatbot with audio to a Django website?
I'm using Django to develop a website and would like to integrate it with a DialogFlow chatbot. I want to display the conversation and play the speech response. How should I go about implementing that? I have understood that this problem is not trivial. So far I have created a DialogFlow agent and tested it with the Python client library using https://cloud.google.com/dialogflow/docs/detect-intent-tts#detect-intent-tts-python. I researched Django Channels but came to the conclusion that it can't handle the speech part. Tips on the structure and approach to solve this problem and handle the communication would be appreciated. A link to a tutorial or code would be great. I'm quite new to web development and don't have a clear picture of all the available tools yet. -
Python Django Queryset only get month and year from date
I currently use the following code to create the queryset for my Fusioncharts bar chart: dataSourceBar['data'] = [] objects_with_category_id_2 = dashboard_input.objects.filter(service_service_id=3,category_category_id=2) for obj in objects_with_category_id_2: data = {'label': obj.session_start.strftime("%m.%Y"), 'value': obj.input_input_value} dataSourceBar['data'].append(data) I tried to only get the month and year from the session_start, but now it only shows each month and year per date something is filled in. Is there a way in which I can design the queryset that it sums the different values per month (in descending order)? So that the graph only shows three bars: 04.2019, 05.2019 and 06.2019? -
Django Elastic Search: AttributeError: type object 'PostDocument' has no attribute 'Django'
I am very new in elasetic search in django... When i run this command, python3 manage.py search_index --rebuild it fires me this error: I am not getting whats wrong with it File "/home/pyking/.local/lib/python3.6/site-packages/django_elasticsearch_dsl/registries.py", line 39, in register_document django_meta = getattr(document, 'Django') AttributeError: type object 'PostDocument' has no attribute 'Django' This is my documents.py from django_elasticsearch_dsl import DocType, Index from blog2.models import Article posts = Index('articles') @posts.doc_type class PostDocument(DocType): class Meta: model = Article fields = [ 'alias', 'author', 'title', 'body', 'category', ] and this is my models: class Article(models.Model): alias = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) I am not getting whats wrong with my code, even it is not firing me my code problem, it is firing me some odd error.. -
How to build a list of GMT time zone offsets in Django?
I want to allow users to choose a time zone, like in the screenshot I tried using pytz.all_timezones list, but it is very long and inconvenient to scroll and use. Any ideas how to implement similar list of timezones in Django? Thanks. -
How do I get some (custom) user data in my api.py?
I'm not sure how to pass data from two 'nested' models to an endpoint. I want to set up some data related to the user in my Django application. After some googling I found the best way to 'extend' the default user model is to create another model with a OneToOneField pointing to the user. This is how the model looks like: # models.py from django.db import models from django.contrib.auth.models import User class UserData(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) currency = models.CharField(max_length=10, default="USD") budget = models.IntegerField(default=500) showCategories = models.BooleanField(default=True) showLocations = models.BooleanField(default=True) showSources = models.BooleanField(default=True) def __str__(self): return self.user After writing the model, I wrote a new serializer for it: # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'username') class UserDataSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserData fields = ('currency', 'budget', 'showCategories', 'showLocations', 'showSources', 'user') All good so far (I hope). Finally, I've changed my UserAPI to have a serializer_class of UserDataSerializer. This is how it looks right now: # api.py class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserDataSerializer def get_object(self): # I suppose I need to return something else here but I'm not sure what. return self.request When accessing my endpoint … -
django-rest without model post request test from browser
I'm working to have a viewset in django-rest framework that user can post a json to me and I give them back a csv file for downloading. Thus I don't have any model or serializer for that. The endpoint will be like 127.0.0.1:8000/download/ and I registered that endpoint through url(r'^download/$', views.DownloadViewSet.as_view(), {'post': 'download'}, name="CSVDownload"), My question is how can I test the post request through the browser? I don't have any boxes for the post request and can't actually see my api-request through web since it's not registered through router. -
my question is about django in admin.py part
I have this code: def make_published(ModelAdmin, request, queryset): result = queryset.update(status = 'published') if result == 1: message_bit = "1 post was" else: message_bit = "{} posts were".format(result) ModelAdmin.message_user(request, "{} successfully marked as published.".format(message_bit)) but when i run the server. Error: Watching for file changes with StatReloader Exception in thread django-main-thread: -
Need help on django framework connectivity
We installed Python and then installed django with the help of pip command on Windows 10 OS .. when we are giving command after going in the folder c:\users\users_name\AppData\Local\Programs\python37-32\scripts Command - Python -m django runserver It's not working.. where I am doing wrong input ? Please help -
Why Taggit (Django-Tag) won't work once I used Tag.models.all()
I have implemented django-taggit successfully until I was trying to use the mixin to render the tags on a ListView of "PropertyListing" in this example: The console keep telling me: NameError: name 'Tag' is not defined **The PROBLEM comes from the views.py line 4 apparently. I cannot import "Tag" from the model like "PropertyListing" since its a third party library. I have tried to import from taggit.managers import TaggableManager in views.py but same error. I am using django 2.1 and django-taggit 1.1.0 below is the code: models.py from taggit.managers import TaggableManager class City(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) tags = TaggableManager() class Meta: verbose_name_plural = 'Cities' def __str__(self): return self.name class PropertyListing(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) price = models.DecimalField(max_digits=10, decimal_places=2) description = models.TextField(max_length=1000) address = models.CharField(max_length=1000) is_active = models.BooleanField(default=False) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='property_listings') class Meta: verbose_name_plural = 'Properties Listings' def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(PropertyListing, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('core:property_detail', kwargs={'pk': self.pk}) views.py class TagMixin(object): def get_context_data(self, **kwargs): context = super(TagMixin, self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class PropertyListingView(TagMixin, ListView): model = City model_type = PropertyImage queryset = PropertyListing.objects.all() context_object_name = 'properties' template_name = 'core/property-listing.html' def get_context_data(self, … -
When submitting empty integer value, error generate invalid literal for int() with base 10: ''
when i submit add invoice form then i leave invoice paid amount value empty then error shown "invalid literal for int() with base 10: '', > models.IntegerField(null=True, blank=True) > models.IntegerField(default=0) class Invoice(models.Model): customer_id = models.ForeignKey( Customer, default=1, verbose_name='customer', on_delete=models.CASCADE) id = models.AutoField(db_column='ID', primary_key=True) i_sr = models.CharField(max_length=40, default="") i_date = models.DateTimeField(blank=True, null=True) i_month = models.CharField(max_length=40, default="") i_amount = models.CharField(max_length=40, default="") i_status = models.CharField(max_length=40, default="") i_paid = models.IntegerField(null=True, blank=True) i_description = models.CharField(max_length=40, default="") class Meta: verbose_name_plural = 'invoice' def __str__(self): return self.i_sr -
New item checks for the missing ID and creaet it
IS there a method to make Django check for missing id number and create a new item in this slot, instead of making it with a new id. Here is what am trying to do I have the model : class BuyInvoice(models.Model): date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=PROTECT) branch = models.ForeignKey(Branch, on_delete=PROTECT) supplier = models.ForeignKey(Supplier, on_delete=PROTECT) total = models.PositiveIntegerField(default=0) is_done = models.BooleanField(default=False) is_canceled = models.BooleanField(default=False) def __str__(self): return 'فاتورة بيع رقم ' + str(self.pk) whenever I add a new item to it it takes the auto-generated id as 1, 2, 3, 4, 5 now if I deleted the item with the id 3, then I try to create new item I want it to be added to the id of 3 instead of 6 -
Run Django Application in Apache Server (Ubantu) with the SSL connection
The Apache Server is by default locating the www/html folder with port:8080 (default was: 80). Now Django files are kept in html/django are running with port:80 It is running http://example.com now after adding SSL the www/html/django is showing all the file structure. when running https://example.com Nowt getting any Solution how to work with same http://example.com https://example.com Already changed in /etc/apache2/sites-enabled/django.conf <VirtualHost *:443> #My site Name ServerName example.com SSLEngine on SSLCertificateFile /etc/ssl/certs/ssl-c.pem SSLCertificateKeyFile /etc/ssl/private/ssl-c.key #Demon process for multiple virtual hosts WSGIDaemonProcess example.com threads=5 #Pointing wsgi script to config file WSGIScriptAlias / /var/www/html/django/django.wsgi WSGIProcessGroup example.com #Your static files location Alias /static/ "/var/www/html/django/template/" <Location "/media"> SetHandler None </Location> <LocationMatch "\.(jpg|gif|png|js|css)$"> SetHandler None </LocationMatch> <Directory /var/www/html/django> WSGIProcessGroup example.com WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost> -
Display an image in a post's details corresponding to the first letter of the user's name?
In my blog app I want to display an image in the post's details. But the tricky part is that I want to display the image corresponding to the first letter of the user's first name. For example if the user's name is "Sam" I want to display the letter 'S' image. I tried to add all letters avatars in static folder.And i tried <!--code for displaying image from database---> {% if post.author.profile.image.url is None %} <img src="{% static 'images/{{letter}}.png' %}" class='logo3'/> {% else %} <img src="{{ post.author.profile.image.url }}" class='logo3'/> {% endif %} views.py def homepage(request): l=[] post= Post.objects.all().order_by('-date') ctr= post.count() print(ctr) for i in range(0,ctr): letter = post[i].author_id[0].lower() l.append(letter) return render(request,'layout.html',{'posts':post,'letter':l}) In my browser if i click on inspect in img tag the src displaying is /media/None -
Attaching the logged-in User to object after object creation
I am trying to have a logged in User fill out a form to create a Group. On Group creation, I need the User to automatically be added to the Group. For this problem, we are working with two models - User and Group. User is the default model provided by Django. Group is defined like so: class Group(models.Model): name = models.CharField(max_length=255, unique=True) admins = models.ManyToManyField(User, default=1, related_name='user_username') all_users = models.ManyToManyField(User, default=1) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') def get_admins(self): return ", ".join([u.username for u in self.admins.all()]) def add_admin(self, user): self.admins.add(user) def get_all_users(self): return ", ".join([u.username for u in self.all_users.all()]) def add_user(self, user): self.all_users.add(user) self.save() def is_admin(self, user): if user in self.admins.all(): return True else: return False And the view I'm trying to refactor is: @login_required def user_generated_group(request): if request.method == 'POST': form = GroupForm(request.POST) user = request.user if form.is_valid(): group = Group.objects.create(name=form.cleaned_data['name']) group.add_admin(user) group.add_user(user) group.save() return HttpResponseRedirect(reverse('home')) else: form = GroupForm() context = { 'form': form, 'type': 'group', 'sidebar': Sidebar(request), } return render(request, 'form.html', context) The goal is to utilize Django's built-in CreateView. The refactored view so far looks like: class CreateGroup(LoginRequiredMixin, CreateView): model = Group form_class = GroupForm template_name = 'form.html' I have yet to implement … -
Creating a python package with a Django app as a CLI
I have a test Django app with a command. I can run that command the normal way: python manage.py mycommand I'm willing to create a Python package that will expose mycommand as a normal command that can be ran from the terminal. The structure of my project looks like this: ├── codedeploy/ │ ├── __init__.py │ ├── cloud/ │ ├── entrypoint.py │ ├── examples/ │ ├── main/ │ ├── manage.py │ ├── requirements.txt │ ├── scripts/ │ ├── strategies/ │ └── tools/ ├── setup.py The __init__.py is empty. The entrypoint.py looks like this: #!/usr/bin/env python3 import os def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') from django.core.management import execute_from_command_line execute_from_command_line(["manage.py", "codedeploy"]) The entry_point of my setup.py looks like this: entry_points={ "console_scripts": ["codedeploy=codedeploy.entrypoint:main"], } When I package my project and install it in a venv, and then run codedeploy, I get the following error: Traceback (most recent call last): File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'codedeploy' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/private/tmp/venv/bin/codedeploy", line 10, in <module> sys.exit(main()) File "/private/tmp/venv/lib/python3.7/site-packages/codedeploy/entrypoint.py", line 14, in main execute_from_command_line(["manage.py", "codedeploy"]) File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/private/tmp/venv/lib/python3.7/site-packages/django/core/management/__init__.py", … -
How to get the .env file into the remote host server
Quick question how to get the .env conf file into the server. I have three settings file in my project base, development, production. I think testing and staging is an overkill It is encouraged to put .env in .gitignore file. so it won't be included in version control. in Heroku, it is easy to set the environment variable in the settings tab. what about other hosting services without such a feature? since I push to my repository and pull from the server, How I am I suppose to get the API keys stored in the .env since it will ignore it (it's in gitignore) file? should I create in the server? or is there a way it is done? Newbie question I know. -
Django TypeError in ModelForm
I am just trying to render a ModelForm and I keep getting the following error: "TypeError: EditManifestSelect.Meta.fields cannot be a string. Did you mean to type: ('reference',)?" I did indeed try to type it as suggested above, but just continue to receive the same error. Any Ideas? FORMS.PY class EditManifestSelect(forms.ModelForm): class Meta: model = Manifests fields = ('reference') VIEWS.PY def edit_manifest(request): if request.method == "POST": form = EditManifestSelect(request.POST) if form.is_valid(): form.save() return redirect('display_orders') else: form = EditManifestSelect() return render(request, 'edit_manifest.html', {'form': form}) MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.cases -
Sending multiple checkbox answers within form by ajax
I am trying to send form data to my Django application using ajax. I am using this JQuery which works fine (to a point) $ (function () { $('#filtersForm :checkbox').change(function() { $.ajax({ url : "/ajax-search/", data: $("#filtersForm").serialize(), type : "GET", success : function(html) { console.log("success"); replaceJobs(html); }.bind(this), error : function(xhr,errmsg,err) { console.log("error"); }.bind(this) }); }) }) There are a number of checkboxes in the form using a forms.ModelMultipleChoiceField. My django form looks like: class FilterSearchForm(forms.Form): job_location = forms.ModelChoiceField( queryset=OfficeBase.objects.filter(name="Remote"), widget = FilterCheckboxSelectMultiple, required=False) job_type = forms.ModelMultipleChoiceField( queryset=Employment.objects.filter(active=True), widget = FilterCheckboxSelectMultiple, required=False) job_category = forms.ModelMultipleChoiceField( queryset=Category.objects.filter(active=True), widget = FilterCheckboxSelectMultiple, required=False) Which produces html like: <ul class="list-unstyled list-increase-spacing"> <span class="form-checkbox"> <li> <input id="id_job_category_0" type="checkbox" name="job_category" value="1"/> <label id="label-id_job_category_0" for="id_job_category_0"> Category 1</label> </li> </span> <span class="form-checkbox"> <li> <input id="id_job_category_1" type="checkbox" name="job_category" value="2"/> <label id="label-id_job_category_1" for="id_job_category_1"> Category 2</label> </li> </span> </ul> When multiple boxes are checked, I am only getting the last one in my view. I am getting the items usingfor key, value in self.request.GET.items(): How do I ensure I get all checked items? -
Best way to implement depending fields dynamically in Django admin
Hello I have an idea about shop on Django. I want something about class Category with name and jsonfield which storing attribute names ("size", "color") for category. And I have a model Product with fk to Category and field attributes, also json {"size":"M", "Color":"red"}. Now I have 2 questions. 1) Is it idea acceptable? 2) i have admin for Product and I want this behavior: then user select category for product, the field "attributes" automatically render the template with attribute names for this Category, something like this: {"size": "", "color":""} Thank you.