Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my Django loading raw css into my html files?
I have a Django project which has been set us using django-pipeline and django-compress. The code on github is pretty standard ex: {% extends "base.html" %} {% load static from staticfiles %} {% block extra_head %} <meta name="description" content="Company Desc"> <meta name="keywords" content="kw1, kw2, kw3, kw4"> <meta property='og:title' content='Company title'/> <meta property='og:image' content="{% static 'images/image.png' %}"/> <meta property='og:description' content='our motto'/> <meta property='og:url' content='https://www.company.com' /> {% endblock extra_head %} But when I clone the code from github and open it in sublime or pycharm style is injected into my html head for some reason and I cant figure out why. We are using Django 1.4, django-pipeline, django-compressor. {% extends "base.html" %} {% load static from staticfiles %} {% block extra_head %} <meta name="description" content="Company Desc"> <meta name="keywords" content="kw1, kw2, kw3, kw4"> <meta property='og:title' content='Company title'/> <meta property='og:image' content="{% static 'images/image.png' %}"/> <meta property='og:description' content='our motto'/> <meta property='og:url' content='https://www.company.com' /> <style> //30 lines of compressed css. </style> {% endblock extra_head %} Anyone know the cause of css being injected into the .html text file? -
Django2 not connecting to Local Host
I'm new to Django/Python. I'm currently taking a beginners course and I'm having difficulty setting up my URLs and connecting to a local server. I'm using Python version: 3.7.0 and Django v.2 The command line does not give any errors (0), it tells me to go here: Starting development server at http://127.0.0.1:8000/ Which I believe is the local host, however the site says This site can’t be reached 127.0.0.1 refused to connect. Can anyone let me know what I'm missing I would greatly appreciate it so that I can continue on with my studying. I'm using tutorials on YT Django Tutorial and the guy is using an older Django so I think that may be why I'm having trouble. He says we should still be okay to follow through even on the new version of Django. urls.py from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('', views.homepage), path('admin/', admin.site.urls), path('about/', views.about), ] views.py from django.http import HttpResponse def homepage(request): return HttpResponse('homepage') def about(request): return HttpResponse('about') -
Wagtail: Get siblings attributes
I'm creating portfolio app. And on the inner page I'd like to give a link to the next portfolio record with it's thumbnail. Wagtail: Get previous or next sibling — Here is an answer on how to get the url. But it doesn't work for getting other attributes. If i change 'url' in this method: def next_portfolio(self): if self.get_next_sibling(): return self.get_next_sibling().url else: return self.get_siblings().first().url All I get is an error "'Page' object has no attribute 'thumbnail'". but it have. That's how my model looks like: class PortfolioItem(Page): thumbnail = models.ImageField(upload_to = '', default = None) is_feautered = models.BooleanField(default=False) def next_portfolio_thumb(self): if self.get_next_sibling(): return self.get_next_sibling().thumbnail else: return self.get_siblings().first() -
Pass extra information to serializer fields in Django rest framework
I am trying to calculate average ratings for restaurant given by each user. I have separate model for restaurants and ratings given by user to each restaurant. in my ReviewSerializer I want to add extra field for average ratings. I did calculate average ratings. according to docs I can pass extra data to serializer using get_serializer_context method.i tried passing hardcoded string and it works fine but I don't know how to pass response returned from get_avg_rating method to context Views.py class ReviewsView(generics.ListCreateAPIView): queryset = Reviews.objects.all() serializer_class = ReviewSerializer def perform_create(self,serializer): serializer.save() def get_avg_rating(request): avg = [] for place in Places.objects.all(): avg_rating = Reviews.objects.filter(place__id=place.id).aggregate(Avg('rating')) avg_value = round(avg_rating['rating__avg'],2) avg.extend([place , avg_value]) return HttpResponse(avg,content_type="json") def get_serializer_context(self): context = super(ReviewsView, self).get_serializer_context() context.update({ "test": {'test':'test'} }) return context Serializers.py class ReviewSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.user.username') test_object = serializers.SerializerMethodField() def get_test_object(self,obj): test_value = self.context.get('test') return avg_value class Meta: model = Reviews fields = ('id','user','review','test_object') -
How to print foreign key of this model in django?
Model File class Report_item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity') item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet') location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item') city = models.CharField(max_length=60, help_text='*Enter the city name') date = models.DateTimeField(default=timezone.now) Description = models.TextField(help_text='*Enter full description about item') publish = models.BooleanField(default=False) image = models.FileField(default="add Item image", help_text='*Please uplocad a item image to identify by the owner') def __str__(self): return self.title + " " + str(self.publish) def get_absolute_url(self): return reverse('feed:detail', kwargs={'pk': self.pk}) class Meta: ordering = ["-date"] I print my title in the shell.enter image description here But I got an error when I tried to print(qs[0].owner) -
Stuck in setuping CSS static file in Django
I had tried to setup static files in Django but failed. I have the following directory structure app | |- manage.py |- requirements.txt |- static | | | |- css | | | |- snapweb.css | | }- templates |- web | |- __init__.py |- settings.py |- urls.py |- wsgi.py /app/web/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings import logging urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() /app/web/settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Take note that, I didn't run python manage.py collectstatic. As, if I want to run, I will get the following warning, which I have no idea how to solve it. /app # python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /app/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: So, my problem is, I feel confused on my app behavior. The following URL works. I didn't expect it to work, … -
Django: Join multiple models on a field value for use in a Django template
I'm working in Django 2.0. I have multiple models which share a common field, and am trying to find the related objects. Schematically, given models Model1 and Model2, for each Model1 in a QuerySet, we want to find the corresponding Model2 object such that Model1.property == Model2.property. In this application, there will be at most one, but possibly no, Model2s that meet this condition. This QuerySet will be used in a Django template for displaying results. Now, I have several ideas as to how to solve this, but I was wondering if there was a standard solution. Consideration: I know that Django template language does not have a builtin way to find an object with a particular property value Ideas: 1) For loop in template. Iterate through the Model2s, evaluating Model2.property and testing Model2.property == Model1.property. Storing the Model2 if True. Seems very clunky, and against the philosophy of the Django template language. 2) Deal with it in python. Perhaps attach a new property to Model1 Model1.property.model2 = Model2.objects.filter(property=property) or use a try/expect block with "get" 3) Deal with it in the query. Perhaps Annotate the results of retrieving the queryset for Model1 with the related Model2s 4) Maybe a … -
Django NoReverseMatch Reverse for 'comment' with arguments '('',)' not found
I have posts and comments type of structure. I have the below issue accessing one post. Remaining posts work fine. I've got Server Error (500) while accessing a post with id 24. Error in error log is: django.urls.exceptions.NoReverseMatch: Reverse for 'comment' with arguments '('',)' not found. 1 pattern(s) tried: ['app/comment/(?P[\d]+)/$'] The line where I got the error is: <a target="_blank" href="{% url 'app:comment' row_item.pk %}"; > All the comments of that particular post have good data, I mean there is no loss of data. Another thing which I want to mention here is that recently I have made some changes to comment model and deployed those changes. Django version: 1.11.7 Any idea on how to resolve this ? Please let me know if need further information. -
Django, How To Allow Multiple Image Upload, Class Based View, 2 Forms
My current issue is that no form shows and if I add {{ form.as_p }} to the create.html page than only the TradeForm shows and without any images. I have used this question for reference: how to upload multiple images to a blog post in django views.py class TradeCreateView(CreateView): template_name = "tj/cp/trade/create.html" form_class = TradeForm form_class_image = ImageForm queryset = Trade.objects.all() def post(self, request, *args, **kwargs): ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3) formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none()) if TradeForm.is_valid() and formset.is_valid(): trade_form = TradeForm.save(commit=False) trade_form.user = request.user trade_form.save() for form in formset.cleaned_data: image = form['address'] photo = Image(trade=trade_form, image=image) photo.save() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) forms.py class TradeForm(forms.ModelForm): class Meta: model = Trade fields = [ 'user', 'target_size', 'target_entry', ... ] # exclude = ['user',] class ImageForm(forms.ModelForm): address = forms.ImageField(label='Image') class Meta: model = Image fields = ('address',) models.py class Trade(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) comments = models.TextField(max_length=10000, blank=True, null=True) def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "uploads/%s-%s" % (slug, filename) class Image(models.Model): trade = models.ForeignKey(Trade, blank=True, null=True, default=None, on_delete=models.CASCADE) address = models.ImageField(upload_to='uploads', blank=True, null=True, verbose_name='Image') title = models.CharField(max_length=100, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __unicode__(self): return self.title create.html <form id="TradeCreateView" method="post" action="." enctype="multipart/form-data"> … -
Django navigation url doesn't work
I am new to Django. I am trying to add Navigation bar to each page, so when I go to one of page (say about) and then from there when I go to another (say contact) path error occurs. Here in navigation.html <nav> <ul> <li> <a href="{% url 'reports:index' %}">Reports</a> </li> <li> <a href="about">About us</a> </li> <li> <a href="contact">Contact us</a> </li> </ul> </nav> So I want, how should I clear my route and go to any nav pages from any current page. -
Template doesn't receive full context dictionary
I'm trying to pass a context dictionary to my template but troubles arise. If i pass the following context, it works and i can loop through it: subjects_list = Subject.objects.all() context = {'subjects': subjects_list} return render(request, 'main_page/subjects.html', context) And i loop it with the following code: {% if subjects %} <ul> {% for subject in subjects %} <li>{{ subject.name }}</li> {% endfor %} </ul> {% else %} <p> No subjects available </p> {% endif %} When i try to add 1 more key item to the context, i always get no value back. e.g subjects_list = Subject.objects.all() context = {'subjects': subjects_list, 'temp_list': [1, 2, 3]} return render(request, 'main_page/subjects.html', context) If i try to access the temp_list with: {{ temp_list }} The temp_list is always blank, whatever i add to it but the subjects still do work. (i used a list of numbers for the sake of the post. What i firstly tried to add was a list of object from a different model i have.) -
Cannot import model into my validators.py
I am trying to create a custom validation for a model field. My app is named 'Vocabulary' and in there I have a model defined in models.py as below:- from Vocabulary.validators import word_exists class Vocab(models.Model): id = models.UUIDField(unique=True, primary_key=True) word = models.CharField(max_length=33, validators=[word_exists]) meaning = models.TextField() def save(self, *args, **kwargs): self.id = uuid.uuid4() super(Vocab, self).save(*args, **kwargs) def __str__(self): return self.word And inside the validators.py file I have defined custom validator 'word_exists' as follows:- from Vocabulary.models import Vocab from django.core.exceptions import ValidationError def word_exists(value): if Vocab.objects.filter(word=value).exists(): raise ValidationError("The word already exists!") In this file [validators.py] I keep getting the error that I cannot import the model Vocab. I have done migrations as well but I am not sure what's causing this error. I am using Django Version 2.0 This code used to work in 1.8. Any help is much appreciated. -
Where to put custom error page templates for django-oscar?
Normally, custom templates are placed in templates/[oscar's app]/ to replace oscar's version. It mirrors the folder structure of oscar templates. It works well for the oscar's apps. However, when I put my custom error page (500.html) in respective location templates/ (oscar error template is at template root), it doesn't load my custom page. I have tried to put it in templates/oscar/ but it doesn't load either. Where should I put the error templates to replace that of Oscar? -
How can I get the django updateview to only render the actor instance that was created and not adding an extra actor form?
I have an inlineformset as part of my forms.py forms.py ActorForm(ModelForm): Class Meta: model=Actor MyFormSet=inlineformset_factory(UseCase, Actor,form=ActorForm, extra=1) I set the keyword (extra=1) since I want only one instance of the actor form to be shown when I rendered a createview in my template. However, when my updateview is rendered in another template, I am getting an extra inline actor form being rendered along with the actor instance that was created. I would love to set extra=0 in my updateview so that there is no extra inline actor form showing. I tried adding extra=0 in the ActorFormset instance in the views.py, but I got an error. views.py Class UseCaseUpdateView(UpdateView): ... def get_context_data(self, **kwargs): context = super(UseCaseUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['actor_form'] = MyFormSet(self.request.POST, instance=self.object,prefix='actor', extra=0) else: context['actor_form'] = MyFormSet(instance=self.object,prefix='actor', extra=0) return context ... How can I get the updateview to only render the actor instance that was created and not adding an extra actor form? -
loading template tags in an included template
I am using django markdown deux to render some markdown for a project I'm working on. Specifically I'm using markdown in some comment system. I had previously made a separate template for a comment and then simply included it in some parent template where I needed the comments, i.e. {% for comment in comments %} {% include 'snippets/comment.html' %} {% endfor %} the comment.html template contains something like {{ comment.content|markdown }} The markdown filter however needs to be loaded using {% load markdown_deux_tags %} This does not work when I include in the parent template only, but does work when I include it into comment.html. I'm worried this means the tags are loaded for every comment which might slow things down, does that make sense? And if so is there some way to just load it once in the parent and then use it throughout in the included bits, like the super method for extends? -
Upload csv into database using django rest framework
I want to upload the csv to database using Django rest framework. Please let me know how to do this. -
Effective use of ThreadPoolExecutor in Django views
My goal is to offload some long running tasks to asynchronous threads using ThreadPoolExecutor. The task is triggered as part of a Django view, but the work doesn't seem to be happening asynchronously (the response hangs). Do I actually have to put the ThreadPoolExecutor code in the view? Why? Shouldn't I be able to do this (my current approach): class SomeDjangoView(TemplateView): template_name = 'template_and_that.html' def get(self, request): clever_async_function() return render(request, self.template_name) # Some other file def clever_async_function(): with ThreadPoolExecutor(max_workers=4) as executor: executor.map(long_running_task, iterable_models_or_similar) I'm aware that if it's really complicated I should setup something like Celery, but I'm trying to keep things lightweight for the moment. -
How do i push uploaded image file in my template input for update in django 2.0
I want to open a particular record in html template in update mode for which i want every value which was inserted before for this record be in those field, i got every required value in field for text field but in file field which contains image ,it shows no file selected where as i want the image file name(url) in there. I havent used django form rather i used normal bootstrap forms. # models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to='images/') # i m facing problem for this field icon = models.ImageField(upload_to='images/') # i m facing problem for this field as well url = models.TextField() votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def short_pub_date(self): return self.pub_date.strftime('%b %e %Y') # views.py def myproducts_update(request,product_id): product = get_object_or_404(Product,pk=product_id) print(product.image) # this prints the name of the file (images/37003.jpeg) return render(request,'products/myproducts_update.html',{'product':product}) # templates(myproducts_update.html) {% extends 'base.html' %} {% block content %} {% if error %} {{error}} {% endif %} <br> <br> <div class="container"> <div class="jumbotron"> <h2>Update Product</h2> <form action="{% url 'create' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="title">Title:</label> … -
Migrating Discourse user to Django user
I have exported database from Discourse. it does contain password_hash and salt. I have done my research and found out that Django uses PBKDF2 by default and even Discours use that with hashing algorithm sha256 and number of iterations 64000. I want to migrate those password so that Django will be able to authenticate a user with the same password. -
nginx encoding of the URL
I'm creating a django app with nginx in a production environment. When I navigate to different pages on my wite, I get 400 - Bad Request errors. This is what the URL will look like in the browser. http://54.158.154.23:8000/%7B$%%20url%20'members:member_signup'%20%%7D But when I manually go into the browser address bar and take away all the needless characters.... http://54.158.154.23:8000/url'members:member_signup' Then the page renders perfectly! Here is my app's nginx config file: # the upstream component nginx needs to connect to upstream django { server unix:/tmp/uwsgi.sock; # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 54.172.211.18 172.31.38.120 unclique.io 54.158.154.23; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /path/to/your/mysite/media; # your Django project's media files - amend as required } location /static/ { alias /home/ec2-user/UnClique/UnClique/static/; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass unix://tmp/uwsgi.sock; include /home/ec2-user/UnClique/config/uwsgi_params; … -
How to take id of model X from DetailView and add it to the CreateView of model Y?
Let's say I have an app with two models, model Car and model Tire, each one has a form and Car is associated with Tire via ForeignKey. #models.py class Car(models.Model): car_name = models.CharField(max_length=500, verbose_name="Car") car_make = models.CharField(max_length=500, verbose_name="Make") class Tire(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, default="", related_name="Car") tire_name = models.CharField(max_length=500, verbose_name="Car") tire_make = models.CharField(max_length=500, verbose_name="Make") When user creates Car with an example form below, they are redirected to a DetailView of a Car. #forms.py class CarCreateForm(forms.ModelForm): class Meta: model = Car fields = ( 'car_name', 'car_make' ) On the DetailView page there is a button "Add Tire", by clicking on it users are transferred to the TireCreateView (which has a form). #forms.py class TireCreateForm(forms.ModelForm): class Meta: model = Tire fields = ( 'car', 'tire_name', 'tire_make' ) But problem is that in this view user has to choose from many Cars (which are already in DB) and after that enter Tire details. I want to achieve following process: User visits CarDetailView User clicks "Add Tire" button Form shows only tire_name and tire_make fields User fills those fields and submits the form Tire details are added to the Car from Step 1 How can I define the car part in a TireCreateForm and … -
Django CMS - Contact form redirects to error page when submitted
I am using Django CMS 3.5.2. I have built a contact form that submits data successfully (I can view the form submissions as admin). The page is supposed to refresh (redirect to my contact form CMS page) when the user submits the form. However, I get an error page instead: I tried deleting line 2, but I then get an error at line 0. My contact form structure is the following: Do you know what is the problem and how should i solve it? Thanks! -
IntegrityError for AutoField after a bulk_create()
after doing a bulk_create, I'm trying to add some elements to my table but I got an IntegrityError as the sequence still starts with 1 when using save() Is there any way to update the sequence within Django after the bulk_create ? Or should I generate the id myself using a max filter ? I'm using a postgre database. -
I'm keep getting 502 gateway error (django)
Would you please check my codes and tell me where does this error come form? gunicorn.sevice file: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=nginx WorkingDirectory=/root/parsiproject ExecStart=/root/parsiproject/parsiEnv/bin/gunicorn --workers 3 --bind unix:/root/parsiproject/myproject.sock myproject.wsgi:applicat$ [Install] WantedBy=multi-user.target nginx.conf file: ... server { listen 80; server_name 64.34.135.108; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/parsiproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/root/parsiproject/myproject.sock; } ... nginx error.log: 2018/08/12 11:57:37 [crit] 3792#0: *35 connect() to unix:/home/user/myproject/myproject.sock failed (2: No such file or directory) w$ I've already inserted my server ip in setting.py allowed host. -
Access Django "context" in template javascript (to create markers on a Map)
i am trying to iterate over a list of dictionares in a javascript. The list is coming from render context, and is called "spots". If I print "spots" this is what I see: [{u'rider_ability': u'Intermediate, Expert', u'spot_distance': 0, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6775, u'lng': 14.7587, u'spot_name': u'Salerno'}, {u'rider_ability': u'Expert', u'spot_distance': 7, u'water_type': u'Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6436, u'lng': 14.6984, u'spot_name': u'Cetara'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 16, u'water_type': u'Chop, Small wave', u'water_quality': u'Crystal clear', u'lat': 40.6262, u'lng': 14.5883, u'spot_name': u'Spiaggia Duoglie'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 33, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4271, u'lng': 14.9818, u'spot_name': u'Ponte di Ferro'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 36, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4026, u'lng': 14.9949, u'spot_name': u'Paestum'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 41, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.343, u'lng': 14.9717, u'spot_name': u'Agropoli'}] And this is the code I am trying to use (without any result, I see an empty map). <script> const options = { key: 'MYKEY', verbose: true, } windyInit(options, windyAPI => { const { map } = windyAPI {% for spot in spots %} L.marker([spot.lat, spot.lng]).bindPopup(spot.spot_name).addTo(map) {% endfor %} }) </script> Any …