Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load/not load pagination depending if objects exists? Django
I am trying to make it so that my pagination only shows up if there are posts on the page and there can be only posts, if the admin has approved them. If there are no posts, there should be "No posts to show" shown on the template,if there are approved posts, then the posts should be shown and also the pagination options. What am I doing wrong here? models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse 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) approved = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post def market(request): context = { 'posts': Post.objects.all() } return render(request, 'userMarket/market.html', context) class PostListView(ListView): model = Post template_name = 'userMarket/market.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'userMarket/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class … -
Django - Generic FormView - Passing inputs, into template
Using, Django==2.1.7, and python3.7 - I am really struggling using FormView - see below script. How can I pass variable search_string submitted via the form and the value within context["new_context_entry"] added via get_context_data - to the success_url, so those values can be rendered in my template on form submission? class ConfigSearchTest(FormView): template_name = 'archiver_app/config_view.html' form_class = forms.DeviceSearchForm success_url = 'archiver/search_results/' def form_valid(self,form): search_string = form.cleaned_data['search_string'] return super(ConfigSearchTest,self).form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) new_context_entry = "adding additional" context["new_context_entry"] = new_context_entry return context -
Django: No Module named 'foo' issue in context with model import
Background information: I would like to run a script using atoms script plug-in. I first encountered a ImproperlyConfigured error which was solved as suggested here: First fix Then I run into RuntimeError: Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. error which was solved by using an absolute path for the model import as shown below. Current issue: Using the mentioned absolute import, I receive this error: ModuleNotFoundError: No module named 'Dashboard_app' I can even render the template for that app etc. so I am confused why he tells me that the module doesn't exist. When I remove the model import, everything works just fine. Is it maybe that the script instance doesn't recognize it properly? What I've tried: deleted + re-created __init__.py checked settings for app to be included in INSTALLED-APPS dic changed import path to DASHEX.Dashboard_app.models resulting in no module named DASHEX error changed import path to models resulting in Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS error feeder.py script: import django from django.conf import settings import zmq import time from time import sleep import uuid settings.configure() django.setup() import sys print(sys.path) from Dashboard_app.models … -
How to don't print django error in html file ir Frontend
I Want to print error with my html file but my script is printing text that in variable For Example! I Had This Form: if reg.is_valid(): if cap == True: user = reg.save(commit=False) user.set_password(User) user.save() reg = True else: reg = False If There is a error for example user already exist it need to set variable as false so we can add if statment in html and give alert there was a error But it's Also Set That False And Also Write in html False Here is the Screenshot! You Can See It's Also write False below sign in There I Don't need That i need to set that variable as False Not Also Write in html file You Can Take As I don't Want To Print Error in website! Here is my views if result['success']: cap = True if reg.is_valid(): if cap == True: user = reg.save(commit=False) user.set_password(User) user.save() reg = True else: reg = False else: cap = False else: reg = register() return render(requests,'signup.html',{'reg':reg,'cap':cap,}) You can see in my code: the variable set to be false but in the html it's also writing false -
How can i access images stored in my s3 bucket with url in html
i want to show uploaded images on my html page with returned/made url. but i am getting access denied on that url. I am new to aws s3 how can i fix it. I want ot access it in both(App and web with that url) -
Django multiple users store in a model by multiplechoicefield
i'am createing an application for different managing-services and run into a problem. I want to show the current logged user in an area-model, where other users of the company can work in this area. Areas: What i did is to get the users into a form, so i can choose them and there will be saved: And now comes the tricky-part: Not every user in the Database should be shown in the multiple-choice-filed, so i've added a query-set and a user-parameter in my view, to generate the choices dynamically: Result in my template: You can see, its not correct. Here are the problems: How can i show first_name and last_name in the choices field and still use the custom-form_valid-Functionaility of the model? If i try to add a user to my form, i can't valid the form by the model. How can i change the multipleinputfield to a Text-Field with available Choices and DropDown? I've tried different things (autocomplete, select2 etc.) but the documentation is not good. I ran into multiple errors. One of the biggest Problem is, that all tutorials use static choices or functions which creates the choices when the server is starting. The target is, that the … -
How to use order_by in Django queryset?
I apply order_by to a queryset and the results are mixed up. Is there any difference if I apply it to a queryset? The table has three columns: Name Age Description Here is the code: Query = table1.objects.filter(Name__iexact='Nico').order_by('Age').distinct() ages = Query.values_list('Age') descr= Query.values_list('Description') Here only Age is sorted correctly. The match between these Age and Description is distorted. What is wrong here? -
Django url embed link from youtube
i am building a movie review website application in Django. i want to create a video URL link section in Django administrator console that, when i enter copy the embedded link from YouTube and saving it at the correct movie, it shows the movies trailer. what do i need to write in the model.py to do so? much appreciate. -
django reference User model - You are trying to add a non-nullable field 'author' to question without a default [duplicate]
This question already has an answer here: You are trying to add a non-nullable field 'new_field' to userprofile without a default 14 answers Iam new to django and having an issue with integrating the Django auth model directly in apps' models by referring to it as question_text = models.CharField(max_length=200, blank=False) pup_date = models.DateField('date_published',auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) but when trying to run python manage.py makemigrations it gives the following error Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py so would you please help me in this, I don't need to create a custom User model. regards -
Django database query spanning across multiple relationships
Given the models below: class Assets(models.Model): assettag = models.CharField() ... pass class Employees(models.Model): loginname = models.CharField() pass class Item(models.Model): descr = models.CharField() asset = models.OneToOneField('Assets') ... class Assignments(models.Model): employeeid = models.ForeignKey('Employees') assetid = models.ForeignKey('Assets') ... I can make a query that returns all Item models which contain a certain descr or a certain assettag, using Q objects. Item.objects.filter(Q(asset__assettag__icontains = query) | Q(descr__icontains = query) #| ).order_by('asset__assettag') Would it be possible to also include employeeid__loginname somehow? I couldn't figure out a way to do so. I want to retrieve the Assets that are refereneced in the Item table and which belong to a certain Employee. -
Custom Django 1.4.5 management command not found
I am working on a legacy python application developed with Django 1.4.5 and trying to create a custom management command. My app is called george and here's the folder structure (I've omitted out other irrelevant files & folder): manage.py /george __init__.py /management __init__.py /commands __init__.py what_time_is_it.py And this is the content of what_time_is_it.py: from django.core.management.base import BaseCommand from django.utils import timezone class Command(BaseCommand): help = 'Displays current time' def handle(self, *args, **kwargs): time = timezone.now().strftime('%X') self.stdout.write("It's now %s" % time) and I made sure george is included in my settings.py under INSTALLED_APPS: INSTALLED_APPS = ( ... 'george', ... ) The app is running in a docker container, so after building and running the container, i shelled into it and ran this command: root@e1973c07ba61:/code# python manage.py what_time_is_it and I get this error: Unknown command: 'what_time_is_it' Type 'manage.py help' for usage. Any ideas what I might be doing wrong here? When I run python manage.py help I don't see my custom command listed there, as if it's not registering. -
Django URL start with special character "?"
I'm trying to acceed to this url: https://www.topmoonitor.com/?a=details&lid=19 The problem is django don't care of the "?" before a=details&lid=19 and redirect me to the home page on this URL: path('', views.index, name='index'), If i remove the "?" it's work properly. My current code : path('?a=details&lid=<slug:lid>/', views.button_img, name="button_img"), I tried this but still not working :/ re_path(r'?a=details&lid=(?P<lid>\d+)', views.button_img, name="button_img"), Do you have some idea please ? -
No command runs in Subprocess
I have used a subprocess to convert Docx file to Pdf file in Django. On the server when I run the project with python manage.py runserver command. All things working file but if I run the application with Gunicorn my subprocess not work. Simple "ls" command is also not working. My server has ubuntu 18.04. -
Web service inside django
I have built a basic webapp in Python Django (2.1) which manages all domains and subdomains (dns) purchased through Google and Godaddy. What I am trying to do is to make use of Google and Godaddy's REST API so that i can automate the process of adding/updating/deleting it from my webapp. E.g. When i add (purchase) a new domain, i should enter all the details in a webform, then it should query the REST API (using google-cloud/godaddypy modules) and according to the response, it should proceed: if it exists, throw an error, otherwise add it to the local database (mariadb). The problem is that i tried doing it in models.py (overriding save() function), forms.py and views.py but with no success, i keep on getting import errors and so on. Any ideas? I have gone through the documentation, nevertheless i could not find anything relevant. -
Disallowed Host at / , InValid HTTP_POST Header
I have deployed a Django project in VPS.The problem I am facing is when I browse the application using VPS IP then everything works fine but when I add the domain name and point the domain to the VPS IP then it says the following error (see screenshot) Steps I have done : 1. Point the domain to the VPS IP 2. Add domain name in ALLOWED_HOSTS in settings.py 3. Also if I put DEBUG = False, the same message shows as attached screenshot. Which may not be the usual case. Can anyone help? -
Making API robust and flexible
I have two models... Business and User. I want to find if an API can handle a flexible JSON request body. The API I want is to be intelligent enough to work with parameters, if enough are available. That's the design goal. About my specific API: A user might be a customer or business. If a user is a business he has business attributes too. This API should be able to handle changing a few or more attributes. Also, if the request throws him a user_id, it should find the business_id itself or vice versa... class User(models.Model): name = models.CharField(max_length = 40) mobile_number = models.CharField(max_length = 10) email_id = models.EmailField(null=True) prefered_language = models.CharField( max_length=15, choices=languages, default=ENGLISH, null =True, ) class Business(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) open_time = models.TimeField() close_time = models.TimeField() #open_days= minimumorder = models.SmallIntegerField(null=True, default =0) fee_below_minimumorder = models.SmallIntegerField(null=True, default = 0) distance = models.DecimalField(null=True, max_digits=5,decimal_places=2,default=1.00) class UserSettings(View): def post(self, request): if json.loads(request.body).get('user_id'): user_id = json.loads(request.body).get('user_id') if json.loads(request.body).get('business_id'): business_id = json.loads(request.body).get('business_id') if json.loads(request.body).get('prefered_language'): prefered_language = json.loads(request.body).get('prefered_language') if json.loads(request.body).get('minimumorder'): minimumorder = json.loads(request.body).get('minimumorder`') if json.loads(request.body).get('fee_below_minimumorder'): fee_below_minimumorder = json.loads(request.body).get('fee_below_minimumorder') if json.loads(request.body).get('distance'): distance = json.loads(request.body).get('distance') if json.loads(request.body).get('open_time'): open_time = json.loads(request.body).get('open_time') if json.loads(request.body).get('close_time'): close_time = json.loads(request.body).get('close_time') One solution which I have refuted is of … -
how can i do this joins and select from multi-table in django
plz can someone give me the exacte answer to this question? how can i perfome this query using django ? SELECT a.matr ,[nom] ,[prn] ,cast([dat_nais] as date) as dat_nais , (YEAR(getdate()) - YEAR(dat_nais)) as age ,cast([dat_deces] as date) as dat_deces ,cast([dat_imm] as date) as dat_imm ,cast([dat_aj] as date) as dat_j ,[cod_position] ,YEAR(dat_imm) as anne_imm ,YEAR(dat_encais) as ann_regl ,[annee] ,[cod_nat] ,cast([dat_enc] as date) as dat_regl ,[mt_encais] FROM users a left join enca e on e.matr = a.matr left join encr c on (c.cod_encais = e.cod_encais) where (YEAR(c.dat_enc) - c.annee > 3 ) and ((YEAR(getdate()) - YEAR(a.dat_nais)) between 54 and 70) and c.cod_nat = 'CN' order by a.nom_, a.prn, c.annee asc; my models are users, enca, encr. thank you very much -
django does not show value form db
I have problem. My template don't show my value from db. I think that I don't have defined model UserProduct in views.py in function product. wievs.py def index(request): context = { 'products': Product.objects.order_by('category').filter(is_published=True) } return render(request, 'offers/products.html', context) def userproduct(request): context = { 'userproduct': UserProduct.objects.filter(user_id=request.user.id), } return render(request, 'offers/userproducts.html', context) def product(request, product_id): product = get_object_or_404(Product, pk=product_id) context = { 'product': product, } return render(request, 'offers/product.html', context) models.py class Product(models.Model): product_name = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.product_name class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) if self.user.username else '' offers/product.html <div class="p-4"> <p class="lead"> {% if user.is_authenticated %} <span class="mr-1"> <p>Price</p></span> <p class="colores lead font-weight-bold">{{ product.price }} £</p> {% endif %} <p >Description</p> <p class="colores lead font-weight">{{ product.description }}</p> <p class="colores lead font-weight-bold">Weight: {{ product.weight }}kg</p> </p> {% if user.is_authenticated %} <form class="d-flex justify-content-left"> <!-- Default input --> <input type="number" value="1" aria-label="Search" class="form-control" style="width: 100px"> <button class="btn send-click btn-md my-0 p" type="submit">Add to cart <i class="fas fa-shopping-cart ml-1"></i> </button> </form> {% endif %} </div> Value … -
How to dynamically add column names to django queryset
I wanted to dynamically add the model field and search value to a Django queryset. for example if I have a field_name = "book_name" and search_value= "book name" I want to dynamically add field name and search value like below data = Books.objects.filter(book_name__icontains="some book name") I tried like this. data = Books.objects.filter("{}"__icontains="{}").format("book_name", "some book name") I was getting an error saying data = Books.objects.filter("{}"__icontains="{}").format("book_name", "some book name") ^ SyntaxError: invalid syntax Can anyone please correct me? -
Import CSV file into two separate django models
I'm having trouble parsing data from one csv file into two related tables in a django model. My view.py function. for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.objects.update_or_create( card_no=column[0], first_name=column[1], last_name=column[2], mobile=column[3], email=column[4], is_active=column[5] ) _, created = UserPayment.objects.get_or_create( paid_on=column[0], valid_until=column[1], payment_status=column[2] ) This is the CSV file. file image -
Setting href attribute with templatetag in AJAX in django template
I am trying to make money tracker app. There is a 'transactions' page, where user can see all of his transactions by month. By default template is rendered with current month and it looks like this: class TransactionsView(TemplateView): template_name = 'money_tracker/transactions.html' def get_context_data(self, *args, **kwargs): month, year, month_start, month_end = range_of_current_month() context = super().get_context_data(*args, **kwargs) income = sum(Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) & Q(category__expense_or_income_choices='INCOME', date__lte=month_end, date__gte=month_start)).values_list('amount', flat=True)) expense = sum(Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) & Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end, date__gte=month_start)).values_list('amount', flat=True)) income_transactions = Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) & Q(category__expense_or_income_choices='INCOME', date__lte=month_end, date__gte=month_start)) expense_transactions = Transaction.objects.filter((Q(user=self.request.user) | Q(user=None)) & Q(category__expense_or_income_choices='EXPENSE', date__lte=month_end, date__gte=month_start)) context['income'] = income context['expense'] = expense context['balance'] = income - expense context['month'] = month context['year'] = year context['income_transaction'] = income_transactions context['expense_transaction'] = expense_transactions return context But then I want to use AJAX if user wants to see transactions from different month, and my template looks like this (AJAX at the bottom): {% extends 'money_tracker/base.html' %} {% block body_block %} <section class="balance section"> <div class="balance__sheet"> <h3 class="header"><span class="arrow arrow_left">&#8678</span><span class="month">{{ month }}</span> <span class="year">{{year}}</span><span class="arrow arrow_right">&#8680</span></h3> <div> <h4 class="smaller__header">Balance: {{balance}}$</h4> </div> <div class="income_expense"> Income: {{income}}$ <div class="list_of_transactions"> <ul> {% for trans in income_transaction %} <li>{{trans.amount}}$, {{trans.date}}, {{trans.category}}, <a href="{% url 'update_expense' trans.pk %}">edit,</a><a href="{% url 'delete_transaction' trans.pk %}">delete</a></li> … -
Django ModelForm returns None instead of HttpResponse
I've been following the tutorial for 'File Upload With Model Forms' here: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html I'm pretty sure I followed it to the letter (except using my own project). However I'm getting the error The view project.views.InspectionReportForm_Create didn't return an HttpResponse object. It returned None instead. Here is my code: models.py: class Inspection(models.Model): InspectionID = models.AutoField(primary_key=True, unique=True) PartID = models.ForeignKey('Part', on_delete=models.CASCADE, null=True) @classmethod def create(cls, partid): inspection = cls(PartID = partid) return inspection class InspectionReport(models.Model): ReportID = models.AutoField(primary_key=True, unique=True) InspectionID = models.ForeignKey('Inspection', on_delete=models.CASCADE, null=True) Date = models.DateField(auto_now=False, auto_now_add=False, null=True) Comment = models.CharField(max_length=255, blank=True) FileName = models.CharField(max_length=255, blank=True) Report = models.FileField(upload_to='docs', null=True, blank=True) Signature = models.CharField(max_length=255, blank=True) @classmethod def create(cls, inspid, date, comment, rept, sig): inspreport = cls(InspectionID = inspid, Date = date, Comment = comment, Report = rept, Signature = sig) return inspreport forms.py: class InspectionReportForm(forms.ModelForm): class Meta: model = InspectionReport fields = ('InspectionID', 'Date', 'Comment', 'Report', 'Signature') views.py: def InspectionReportForm_Create(request): if request.method == 'POST': form = InspectionReportForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sites/1') else: form = InspectionReportForm() return render(request, 'moorings/uploadReport.html', {'form': form }) uploadReport.html (just the form. everything else is styling and titles etc): <div id="wrapper" class="dark"> <div id="loginwrapper" class="dark"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Create</button> … -
'user_form', expected 'endif'. Did you forget to register or load this tag?
Please go through the link to view my code -
TypeError: DisplayMarketingMessage() takes no arguments how to fix it
how to fix it TypeError: DisplayMarketing() takes no arguments -
How to perform exception handling (try-catch) inside Django template tag?
For a django requirement, i need to add exception handling inside the django template using django template tags. try: mem = e.memberOf except LDAPCursorError: mem = "" This is the requirement. I need to do this using Django template tag.