Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at 'list' object has no attribute 'objects'
i am learning django now and got this below error and i am not from software domain please explain this clearly if possible I am trying to run the following which is throwing an AttributeError at 'list' object has no attribute 'objects' Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class post(models.Model):` title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User,on_delete = models.CASCADE) def __str__(self): return self.title Views.py : from django.shortcuts import render from .models import post #lets add some dummy data post = [ { 'author':'raj kumar', 'title' :'blog title 1', 'date_posted':'27 August 2020 ', "content" :"fist post content" }, { 'author': "kathir", 'title': 'blog title 2', 'date_posted':"28 August 2020 ", "content" :"second post content" } ] def home(request): context = { "posts": post.objects.all() } return render(request,'blog/home.html',context) def blog(request): return render(request,'blog/blog.html') python prompt : i created some objects with database using Django ORM well i inserted some datas using post class lastly post.objects.all() ,,] -
Dynamically display selected column in dataframe with django
I am learning django, I would like to create a little app that dynamically plot pandas dataframe in django template html. I am looking for a tutorial or you if want to play ^^ in this periode of time In steps I would like if possible: -Charge my csv from STATICFILES_DIRS -read it with pandas in views.py of my app -create the path in urls.py of my app -send value to the html template -select columnns that I want to plot with html checkbox -display the selected column in chart (https://www.chartjs.org/,https://plotly.com/~plotlu,...) Thanks for your help -
Extending template using Django doesn't work
I'm having trouble displaying my content with Django in my ecommerce app. This is the base url with only the navigation bar: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style_store.css' %}"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Inicio</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Mi ecommerce</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Inicio<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> <ul class="navbar-nav mr-auto"> <form class="form-inline my-4"> <input class="form-control mr-sm-2" type="search" placeholder="Buscá productos" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </ul> <ul class="navbar-nav"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user }} </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Mi perfil</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Ventas</a> <a class="dropdown-item" href="#">Compras</a> </div> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Logueate</a> </li> {% endif %} </ul> </div> </nav> {% block content %} {% endblock content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> </body> </html> As you can see, I have the {% block content %} tag … -
how to use choices field in different way when creating model's object
i create a model with choises field class Workers(models.Model): city_choice=( ('1120','vegas'), ('1104','newyork'), ('1122','sandiego') ) BirthPlace=models.CharField(choices=city_choice,max_length=10) in django shell i want to create model's object with city_name instead of city_code obj=Workers(BirthPlace='vegas') obj.save() but it's not work how can i handel this program -
Django / Assigning a value to form.instance in views.py
Note that I am new in Django. I have been trying to give value for the 'post' instance of the form. What I want to do is link my comment to a specific post. I could link my comment to author with requesting a user that is currently logged in but cannot set the related post. I got two options for urls.py. First one is setting the path to , and second one is to set to . In the first option I get 'int' is not iterable error. In the second one I get 'Cannot resolve keyword '1' into field. Choices are: author, author_id, comments, content, date_posted, id, title' error. I need an experienced Django developer. my views.py class CommentCreateView(LoginRequiredMixin,CreateView): model = Comment fields = ['content'] def form_valid(self,form): form.instance.author = self.request.user form.instance.post = Post.objects.filter(self.kwargs['pk']).first() return super().form_valid(form) my models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.content def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) my urls.py path('post/<pk>/comment/', CommentCreateView.as_view(), name="comment-create") -
registering a model with the admin site, Once I try to define the entry Model system shows unproperly configured exception
File "C:\Users\Allen\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\conf__init__.py", line 176, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. But the secret_key is there with the information. I am using the python crash coursebook chapter 18, here I am stuck again...thanks -
How to fix Apps Aren't Loaded Yet Error Django
hoping someone can help. I'm trying to run a script.py to populate my Django webapp and I am getting the following error: Apps Aren't Loaded Yet I've included pictures of the script script and of my settingssettings. Anyone know how to fix this? Any help would be much appreciated -
What is the "instance" being passed to the to_representation function of my ListSerializer?
The goal of this project is to create an API that refreshes hourly with the most up to date betting odds for a list of games that I'll be scraping hourly from the internet. The goal structure for the JSON returned will be each game as the parent object and the nested children will be the top 1 record for each of linesmakers being scraped by updated date. My understanding is that the best way to accomplish this is to modify the to_representation function within the ListSerializer to return the appropriate queryset. Because I need the game_id of the parent element to grab the children of the appropriate game, I've attempted to pull the game_id out of the data that gets passed. The issue is that this line looks to be populated correctly when I see what it contains through an exception, but when I let the full code run, I get a list index is out of range exception. For ex. class OddsMakerListSerializer(serializers.ListSerializer): def to_representation(self, data): game = data.all()[0].game_id #if I put this here it evaluates to 1 which should run the raw sql below correctly raise Exception(game) data = OddsMaker.objects.filter(odds_id__in = RawSQL(''' SELECT o.odds_id FROM gamesbackend_oddsmaker o INNER … -
How to put static and media setting at the same time in Django
Hi i'm quite confuse on this, on how to put static and media in urlpatterns at the same time, I already understand that static is for css/javascript while media is for the user upload file, since then if I use the {% static '<pathname>' %} in html file but i'm referring on the media not on the css/javascript, is there a conflict or how django will understand that i'm targeting the media one? here is my urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from .views import ( login, signup, ) urlpatterns = [ path('', login, name = 'login'), path('signup/', signup, name = 'signup') ] urlpatterns += static(settings.STATIC_URL, document_root = settings.STATICFILES_DIRS) I already put the static and works perfectly but where I should but the media? -
django display five objects from database
So I just try to build an app in Python Django and I try to display a certain quantity of objects, for example I want to take from the database just first five objects and display it. Another next five objects display on another site and another five objects display on the next site and so on... .How can I do that? I now that I can do for example: mountains = peaks.objects.all() and then with for loop in template display all of objects. But I want just five per site. -
Is it possible to have TextInput fields on a model that uses ForeignKeys
I am trying to make a website that allows users to create and store recipes. I have a recipe model and am using a custom 'through table' to have numerous ingredients for each recipe (with each ingredient having its own attribute like quantity and unit of measurement). class recipe(models.Model): recipe_name = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=200, default='N/A') ingredients = models.ManyToManyField('ingredient', through='recipe_ingredient', related_name='recipes') def __str__(self): return self.recipe_name class recipe_ingredient(models.Model): recipe = models.ForeignKey('recipe', related_name='recipe_ingredients', on_delete=models.CASCADE) ingredient = models.ForeignKey('ingredient', related_name='recipe_ingredients', on_delete=models.CASCADE) unit = models.ForeignKey('unit', related_name='recipe_ingredients', on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return f'{self.quantity} {self.unit} {self.ingredient}' class unit(models.Model): measurement_desc = models.CharField(max_length=50, unique=True) def __str__(self): return self.measurement_desc class ingredient(models.Model): ingredient_name = models.CharField(max_length=100, unique=True) def __str__(self): return self.ingredient_name I'm then using a formset_factory, to allow the user to add multiple ingredients to a recipe dynamically. class RecipeForm(ModelForm): class Meta: model = recipe fields = ['recipe_name', 'description'] def __init__(self, *args, **kwargs): super(RecipeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('recipe_name'), Field('description'), Formset('ingredients'), HTML("<br>"), ButtonHolder(Submit('submit', 'save')), ) ) class IngredientForm(ModelForm): class Meta: model = recipe_ingredient fields = ['quantity', 'unit', 'ingredient'] IngredientFormset = inlineformset_factory(recipe, recipe_ingredient, form=IngredientForm, extra=1, can_delete=True) This works fine if I manually … -
Django Pytube on heroku doesn't download any videos
So i was building a video downloader on django with pytube and heroku for the host but the downloader doesn't download anything when i use it on heroku. #tools/views.py from django.shortcuts import render from pytube import YouTube import os.path from django.contrib import messages def index(request): return render(request,'tools/templates/index.html') def download(request): try: homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' if request.method == "POST": url = request.POST['kualitas'] yt = YouTube(request.POST.get('link')) if url == "rendah": try: a = yt.streams.filter(progressive=True).get_lowest_resolution() a.download(dirs) messages.success(request, 'Video berhasil diunduh! (Kualitas Rendah)') except: messages.error(request,'Maaf, video dengan resolusi itu tidak ditemukan') else: try: a=yt.streams.filter(progressive=True).get_highest_resolution() a.download(dirs) messages.success(request, 'Video berhasil diunduh!') except: messages.error(request,'Maaf Video gagal diunduh') except: messages.error(request, "Masukkan link dengan benar") return render(request, 'tools/templates/download.html') #tools/templates/download.html {% extends 'base.html' %}{% block content %}{% load static %} <head> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .btn-aqua { background: #0297FF; color: #fff; } .btn-aqua:hover { background: #10629b; color: #fff; } body{ background: url("{% static 'bg4.jpeg' %}") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .gambar { float: right; width: 29.5%; } </style> </head> <body> <img class="gambar" src="{% static 'fiona.png' %}" alt="fiona"> <div class="container"> <div class="col-md-8 card mb-5 mt-7 left top"> <div class="card-body"> <h2 … -
Set column value NULL when changing field to ForeignKey
I had a CharField in my model which i later decided to change to ForeignKey. So when i try to migrate, it will not go, because i already have char values assigned to my fields. I know i can delete this field in my model and create a new one, and change it everywhere in my code, or i can manually delete all the values in database. But is there a third option, where if the value in the field isn't related to the appropriate id in the parent model, it gets set to null. -
Python django image upload is not working
Python Django image upload is not working when I am adding data and click on submit button not give a any response and also not upload any data in the database. models.py fisrst of all i add model file. # Create your models here. from django.db import models class Car(models.Model): carname=models.CharField(max_length=50) carmodel = models.CharField(max_length=50) carimage = models.ImageField(upload_to='images/') price=models.CharField(max_length=15) average=models.CharField(max_length=20) gear=models.CharField(max_length=200) passengers = models.CharField(max_length=200) type=models.CharField(max_length=200) Insurance=models.CharField(max_length=200) class Meta: db_table="car" forms.py then i create a form.py. from django import forms from carapp.models import Car class CarForm(forms.ModelForm): class Meta: model=Car fields="__all__" also add this two line in settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py then i give a path of method. from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from carapp import carviews urlpatterns = [ path('admin/', admin.site.urls), #this is for admin user path('savecar',carviews.savecar), path('showcar', carviews.showcar) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) carviews.py then I created an API method. from django.shortcuts import render,redirect from carapp.forms import CarForm from carapp.models import Car from django.core.paginator import Paginator, EmptyPage, InvalidPage def savecar(request): if request.method == "POST": form= CarForm(request.POST) if form.is_valid(): try: form.save() return redirect("/showcar") except: pass else: … -
Django Forms ignoring USE_L10N configuration
It looks like my django application is not respecting the settings configuration USE_L10N=True In [1]: from django import forms In [2]: class SomeForm(forms.Form): ...: some_date = forms.DateField(required=False) ...: In [3]: form = SomeForm(data=dict(some_date='28/05/2020')); form.errors Out[3]: {'some_date': ['Enter a valid date.']} In [4]: from django.conf import settings In [5]: settings.USE_L10N Out[5]: True In [6]: import locale In [7]: locale.getlocale() Out[7]: ('pt_BR', 'UTF-8') In [8]: form = SomeForm(data=dict(some_date='05/28/2020')); form.errors Out[8]: {} If I use MM/DD/YYYY or YYYY/MM/DD it works. Shouldn't django be using this pt-BR format instead? What can be wrong? Thank you in advance! -
How to get form field value using jQuery, Ajax and Django
I have a html form which has four inputs. Two of them got through a form passed from Django view and two of them through previous page view through Django variable. This html form is as follow: <form method="POST" id="post_form" class="post_form" action="" enctype="multipart/form-data" formnovalidate > {% csrf_token %} <!-- category --> <div class="form-group"> <input type="hidden" id="category" name="category" value="{{category}}"> </div> <!-- subcategory --> <div class="form-group"> <input type="hidden" id="sub_category" name="sub_category" value=" {{sub_category}}"> </div> <!-- post form field --> {% for field in form %} {% if field.name == 'title' %} <div class="form-group"> <label>{{ field.label_tag }} </label> <input type="text" class="form-control" id="title" placeholder="title" name="title"> </div> {% endif %} {% if field.name == 'content' %} <div class="form-group"> <label>{{ field.label_tag }}</label> <textarea class="form-control" id="content" placeholder="description" name="content"></textarea> </div> {% endif %} <!-- end of form --> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> the jQuery code as follow: <!-- to submit the post and post images forms --> <script type="text/javascript"> // to submit the form and prevent the default submission $(document).on('submit', '#post_form', function(e) { e.preventDefault(); var formData = new FormData(this); formData.append("category",$("#category").val()); formData.append("sub_category",$("#sub_category").val()); formData.append("titel",$("#title").val()); formData.append("content",$("#content").val()); alert(formData['category']); $.ajax({ type:'POST', url: "{% url 'create_post' %}", data: formData, processData: false, cache:false, contentType: false, csrfmiddlewaretoken:'{{ csrf_token }}', success: function(data) { if … -
Extract the month from DateField in Django template
Want to extract the month and year from template template_1.html <form method = 'POST'> <input type ='month' name = 'searchmonth'> <input type = 'submit' value = 'Search'> </form> template_2.html {% for i in record %} {% if i.record_patient_number == number %} {{ month = i.record_date.getMonth() }} {% if month == searchrecordmonth %} *something* {% endif %} {% endif %} {% endfor %} All variable are include in views.py In this search month is not able to extract and record_date is save in models.py and as a record_date = models.DateField(blank = True , null = True) -
Django / Apache returns HTTP 500 Randomly
I have been dealing with a rather strange issue lately. My backend has httpd + mod wsgi + Django setup. I have a class-based view as follows: class ExtrasView(View): def get(self, request): path = settings.BASE_DIR + "/data.json" with open(path, encoding='utf-8') as f: data = json.loads(f.read()) return JsonResponse(data) The get request to the above view works perfectly 9 out of 10 times. However, randomly this view would give a response with status 500. Based on the apache log, it seems that the response body length is correct i.e. the length of data in the file. This is verified by apache access logs. Does anyone have an idea why this might be happening? I have checked the error logs and there's nothing in the errorlog. The error log does print tracebacks in case of exceptions or other syntax errors, just in this case it doesn't print anything so I'm clueless. Needless to say, the file being read is a static file that 100% exists. The data in the file is huge, it's length is about 30-40k characters. Would this cause an issue? If yes, then why does it work 9 out of 10 times? Any comments are welcome. -
Gunicorn not working on Amazon ec2 server
I am trying to deploy a django website on an aws ec2 instance (ubuntu 18.04) following this tutorial that is consistent with other online resources. Everything is working fine but there is some issue with gunicorn. The worker doesn't seem to boot. I figured there was something wrong with my installation and I tried uninstalling and installing with different commands- inisde my virtualenv with pip install gunicorn and sudo -H pip install gunicorn I even physically deleted all gunicorn files and reinstalled gunicorn but its always the same. Where have I gone wrong? p.s: I had initially done sudo apt-get -
Add Cash on Delivery Payment on Saleor Project
I'm totally new to django, but I've found this open source e-commerce app named Saleor so I've built a complete front-end depending on it, but the problem I'm having now is in the checkout level where I can't find a Cash on Delivery payment method and I can't complete the checkout without adding a payment method, the business need doesn't require a credit-card or any online payment method. after googling I found this plugin django-payments-code, tried to install it on the project but I got this error ModuleNotFoundError: No module named 'payments', I'm running out of time and I really appreciate any help might be provided. -
django xhtml2pdf not getting image
I am trying to render html to pdf, it really works great ! only there is an issue and that is the template getting image: I am using python xhtml2pdf library for pdf render this is my method for render pdf: def render_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('Unable to process the request, We had some errors<pre>%s</pre>' % escape(html)) and this is my views.py below: def test_view(request): context = { 'test': 'a test string' } return render_pdf('test.html', context) and this my test.html {% load static %} <p>hello test </p> <img src="{% static 'ok.jpg' %}"> It gets image if i render with django default render method But the image not getting when i render for pdf. I heard of this solution with link_callback method with this documatin: https://xhtml2pdf.readthedocs.io/en/latest/usage.html I am not getting where to include this or how can i achive this. Can anyone help me in this case? -
DJango read static file Json
I am learning django, I would like to read a json file but I do not kown where to put it cause I cannot display. Here is the structure of my project: src=>templates=> Main=> home.html src=>Myproject=> settings.py src=>Myproject=>urls.py here the html: {% load static %} <lottie-player src= src="{% static "./myfile.json" %}" background="transparent" speed="1" style="width: 700px; height: 700px;" loop autoplay > </lottie-player> </div> Hereis the main urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here is my setting : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static_project") ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root") #every time a user upload folder, it will be inside the static_cdn folder and the root "media root" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root") Thanks for your help -
Django specify which database to use for module
In my Django project I have a couple of applications, one of them is email_lists and this application does a lot of data handling reading data from the Model Customers. In my production environment I have two databases: default and read-replica. I would like all queries in a particular module to be made against the replica-set database. I can do that if I explicitly tell the query to do so: def get_customers(self): if settings.ENV == 'production': customers = Customer.objects.using('read-replica').filter() else: customers = Customer.objects.filter() but this module has more than 100 queries to the Customer and other models. I also have queries to relations like: def get_value(self, customer): target_sessions = customer.sessions.filter(status='open') carts = Cart.objects.filter(session__in=target_sessions) the idea is that I want to avoid writing: if settings.ENV == 'production': instance = Model.objects.using('read-replica').filter() else: instance = Model.objects.filter() for every query. There are other places in my project that do need to read from default database so it can't be a global setting. I just need this module or file to read using the replica. Is this possible in Django, are there any shortcuts ? Thanks -
django-using same route in url path
I was working on a project and I am a beginner in Django. I am passing user.id from template to URL for tow things i.e one for profile update and one for a password reset. But it is going to only one URL whether I am clicking on profile update or password reset. I think the issue is I can not use the same routes in two URL paths. here is my url.py: urlpatterns = [ path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('<int:user_id>/', views.chgprofile, name='chgprofile'), path('<int:user_id>/', views.chgpassword, name='chgpassword'), ] here is my template code which shows the two buttons: <a class="btn btn-sm btn-outline-primary" href="{% url 'chgpassword' user.id %}">change password</a> <a class="btn btn-sm btn-outline-primary" href="{% url 'chgprofile' user.id %}">update profile</a> -
Django setting models.DateField() with a datetime object
I'm debugging some failing test after we recently upgraded from django 1.11 to 2.2, and i've noticed a behaviour that i havent been aware before. consider the following code from datetime import date, datetime, timedelta class User(models.Model): birthday = DateField() user = User.objects.create(birthday=date.today()) # setting the DateField object with datetime yesterday_datetime = datetime.now() - timedelta(days=1) user.birthday = yesterday_datetime user.save() user.refresh_from_db() print(user.birthday) # returns date.today() I've always assumed that when a DateField object has been populated with a datetime object, that the date aspect of the datetime object is taken and saved. It seems like this is not the case, and the field isnt updated / saved to the db. Is this a django 2+ behaviour or has this been the default for quite some time? Can anyone share their experience with this edge case?