Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display a line of html code base on if/else statement in view.py
I'm new to this and using Django. Depend on the if/else statement in view.py, I want the html to display a certain text. I'm not sure to use HttpResponse() or render(). I have been trying, but none of them work. I would also like to do it without reloading the page homepage.css .answer {display:none;} home.html ... <label class="answer" style="display:{{ correct}}">Correct!!</label> <label class="answer" style="display:{{ wrong }}">Wrong!!</label> view.py def create_request (request): .... if correct_answer = request.POST.get("answer"): correct = "block" return HttpResponse(correct) else: wrong = "block" return HttpResponse(wrong) -
Using decorators on Class Based Views causes AttributeError
I have a Class Based View called ChannelAuth that for testing purposes we have decorated with @csrf_exempt. This isn't final, but nonetheless I'd like an answer for the sake of learning. @csrf_exempt class ChannelAuth(views.APIView): def post(self, request, *args, **kwargs): if not request.data: return JsonResponse({'Error': 'Data is malformed.'}, status=400) .... When using a decorator, though, we are "wrapping" the class so to speak in a function. This means when we use ChannelAuth.as_view() we aren't actually accessing the as_view() attribute as expected, because it doesn't exist on the "wrapper function" thus throwing an AttributeError. urlpatterns = [ path('admin/', admin.site.urls), path('api/auth/channels/', ChannelAuth.as_view(), name="channel_auth") ] So my question is how would I still utilize a decorator like @csrf_exempt on a Class Based View properly? -
How do you implement a Form in a ListView
I'm new to Django, I basically have a homepage which has a search bar that is being implement using a Django Form. Additionally, in the homepage I have bootstrap card whichis being used to display data from my model. I'm using the def_get to render the form (since it's being used to query the DB). The form is very basic, it's just a CharField. However, when I use the def_get to render the Form in my class based view it now doesn't retrieve any of the data that goes into the bootstrap card which is causing the card to not display. I've tried to render both the form and data in the card by using ModelFormMixin but it seems like this hasn't solved my issue yet, not sure whether this is the way to achieve this? Forms.py from django import forms class SearchBarForm(forms.Form): q = forms.CharField(label="", max_length=150, required=True) Views.py from django.views.generic import TemplateView from django.views.generic.list import ListView from property.models import Property from pages.forms import SearchBarForm from django.shortcuts import render class HomePageView(ListView): model = Property template_name = 'home.html' def get(self, request): form = SearchBarForm() return render(request, self.template_name, {'form': form}) Home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% … -
Reverse Proxy don't complete 'POST' request and refreshes page
I'm sending a form via django with a submit component, this form execute a query on background and return a new page with some data. On POST request the page is refreshed, the fields cleaned and I'm not redirected to the result page. The thing is: it works locally with runserver and on a EC2 Windows instance (also wit runserver), but when I set up the project to run on a Linux machine using reverse proxy (apache2), I face this issue. Here are some details of my settings: myproject.conf located at etc/apache2/sites-available/ <VirtualHost *:80> ServerName 127.0.0.1 ServerAlias localhost Alias /static /home/project/myproject/static <Directory /home/project/myproject/> Order deny,allow Allow from all </Directory> <Directory /home/project/myproject/mysite/> <Files wsgi.py> Require all granted </Files> WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> DocumentRoot /home/project/myproject ErrorLog /var/log/apache2/error.log CustomLog /var/log/apache2/custom.log combined </VirtualHost> WSGIScriptAlias / /home/project/myproject/mysite/wsgi.py WSGIPythonHome /home/project/env WSGIPythonPath /home/project/myproject My django wsgi.py file location: home |_project |_myproject |_mysite | |_wsgi.py |_manage.py . . . Apache custom.log: (env) ubuntu@ip-10-0-0-231:/home$ sudo tail /var/log/apache2/custom.log 54.207.33.42 - - [22/Aug/2019:19:23:40 +0000] "GET /product/fast_appraisal/result/ HTTP/1.1" 302 304 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0" 54.207.33.42 - - [22/Aug/2019:19:23:40 +0000] "GET /login?next=/product/fast_appraisal/result/ HTTP/1.1" 301 274 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) … -
Convert SQL to Django orm with Inner Join
I'm trying to pass this SQL query to django ORM, but I have a problem with the inner join, could you please help me, thank you I tried using a query within another query, but I have no way to compare an annotate of a GT filter Model.objects.filter( status=Model.FAILED, ).filter( created__gt=Model.objects.filter( status=Model.APPROVED, is_active=True, ).annotate( approved_created=F('created') ).values_list('approved_created') ).select_related('invoice').values_list('pk') This is the SQL that I want to convert SELECT * FROM model IA1 INNER JOIN model IA2 ON IA1.invoice_id=IA2.invoice_id WHERE IA1.status = 'FAILED' AND IA2.status = 'APPROVED' AND IA2.is_active = True AND IA1.created > IA2.created; -
Can the Foreign key field be blank?
I want a solution to this problem. Could it be that the foreign key field is empty, where I want to include the images and the list is empty? So far, I couldn't do that until I later modified the image list field. I want the list to be empty at first when I add images class Photo(models.Model): image = models.ImageField(default="default.png", blank=True, null=True,upload_to=user_directory_path) listing = models.ForeignKey(Listing, related_name='Photos',blank=True, null=True, on_delete=models.CASCADE) the error: django.db.utils.OperationalError: table listings_photo has no column named listing_id [22/Aug/2019 22:28:42] "POST /For_Sale_Post HTTP/1.1" 500 19478 [22/Aug/2019 22:38:19] "GET /admin/listings/ HTTP/1.1" 200 2901 -
django custom reverse manager for one relation
Let's say I have these models: class Question(Model): allow_user_defined_options = BooleanField() ... class UserAnswer(Model): question = ForeignKey(Question, related_name='answers') ... class Answer(Model): question = ForeignKey(Question, related_name='options') user_defined = BooleanField() ... I want the reverse relation between Question and Answer (options) to only include non user defined answers. So I made this manager: class StandardAnswerManager(Manager): def get_queryset(self): return super().get_queryset().filter(user_defined=False) I know I can set the base_manager_name to point to this manager but I since it filters objects within get_queryset and I only want to filter these out on the options reverse relation between Answer and Question its not a good idea. What's the best way to approach this? -
including ssh.invoke_shell in django web application
I need to include my code in a dynamic web application. it consists of ssh connection to Linux machine then enter command in input , execute a function and return the result until the user enter '0' value (while loop for example). (just like console in the web application) Sorry for my English #this is my python code import paramiko import time import getpass import re ip = '192.168.43.10' username = 'osboxes' password = 'osboxes.org' test = "config" shver = "show version" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False) print('Successfully connected to %s' % ip) remote_conn = ssh.invoke_shell() time.sleep(.005) output = remote_conn.recv(65535) print (output) def escape_ansi(line): ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]') return ansi_escape.sub('', str(line)) x=input('>>') while (x!='0'): time.sleep(1) remote_conn.send(x+'\n') time.sleep(0.1) if remote_conn.recv_ready(): output = remote_conn.recv(5000) op=output.decode() oo=escape_ansi(op) print(oo+'>>') x=input() # this is my html code {% extends 'base.html' %} {% block content %} <div class="mb-3 card text-white card-body" style="background-color: rgb(51, 51, 51); border-color: rgb(51, 51, 51);"> <h5 class="text-white card-title">Console log to the gateway</h5> <div class="position-relative form-group" > <input rows="15" style="color: #FFFFFF; background-color: rgb(51, 51, 51)" name="{{x}}" id="xx" class="form-control"> </div> <h3>Result</h3> </div> {% endblock %} -
Manually add image to ImageField outside Django
I have a Django form which has an ImageField. I am connecting the to the database manually from a separate Python script. The image field has the path to the image file itself. I don't understand how I would add an image to Django from outside Django. I am using mysql-connector to connect to the database. I populate some fields manually, outside Django and an ImageField is one of them. I don't know how I would upload an image. -
Using two different frameworks on a single domain (Oracle Weblogic / Django)
Suppose my company has a site at https://example.com, and it is powered by an older version of Oracle Weblogic. The company wants to eventually transition the site to a Django framework, but wants to do it piecemeal. Specifically, it wants to maintain the original site on the old framework, but wants set up a subfolder like https://example.com/newurl/ (or, alternatively, a subdomain like https://newurl.example.com) which will contain a Django project with new features etc., and any subdirectories within this new url will likewise consist of Django apps only. My question is, is it possible to contain both frameworks on the same domain in this manner, and if so how one would go about it using Apache? Thanks. -
AssertIsNotNone Odd Behavior
In django I am writing a test that is checking whether or not a value is null. This seems to be a pretty standard procedure, but for some reason when i pass a value to the method assert self.assertIsNotNone(foo) even when the value is most certainly not None, the assertion still fails. Another odd thing is that the following if block passes even though its the same intended behavior as the assertIsNotNone function. foo = Load.objects.all().first() if foo is not None: print("Passed") For context, the foo variable in the first example is an instance of a django model. And I repeat, the object is most definitively not None. Does anybody have any idea what would be causing something like this? And if my understanding of the function is incorrect please let me know. Full code: foo = Load.objects.all().first() if foo is not None: # passes print("Passed") assert self.assertIsNotNone(foo) # fails -
Django form cannot be unpacked with ".is_valid()"
I'm writing a django web app that uses forms. I followed the documentation and have created my form class as so: class LRMYearMonthForm(forms.Form): month = forms.ChoiceField(choices=MONTHS, label="Months") year = forms.ChoiceField(choices=YEARS, label="Years") I am calling it like this in my view: def lrm_reporting(request): if request.method == "POST": year = int(request.POST['year']) month = int(request.POST['month']) print([year, month]) make_lrm_reporting_table(year, month) form = LRMYearMonthForm(request.POST) if form.is_valid(): return redirect('lrm_recon_report') I am getting the error message: cannot unpack non-iterable int object which points to the line: if form.is_valid(): What am I doing wrong? -
How to use "other" as a wildcard language in django translations
I am building a website in django-cms which will support mainly 2 languages (en, es). However, "guest" articles will appear at times in many more languages (like 15 or more potentially). I do not want to add all of these separately. I would rather use something like (en, es, "other") as a wildcard to hold all languages other than the 2 main ones. The reason is to keep the CMS as simple as possible as these entries will be quite rare. Any ideas on how to achieve this? -
Not able to pass the method as POST from django template to django view
I am making a Django form but not able to pass the form as a "POST" method. When I press the submit button, the form information is sent as "GET" which I can see by printing on the terminal. Hence the if condition in the code remains false. Please help me figure out what is going wrong here. Below is the code for the rendering the template. # Code for the /template.py# {% block content %} <div class="container"> <div class="row"> <div class="col-sm-8"> <h1>Please answer the question</h1> <form method="post"> {% crispy user_form user_form.helper %} <p><input type="submit" class='btn btn-primary' value="Submit" method = "post"></p> {% csrf_token %} </form> </div> </div> </div> {% endblock %} Below is the code in the views.py file. # /*Code for the /views.py*/ def launch_survey(request, pagelink): pagelink_html = pagelink+".html" user_form = FormQuestionaire() print(request.method) if (request.method == 'post'): print("We are not here") user_form = FormQuestionaire(request.POST) if user_form.is_valid(): print('Validation Success') print("NAME: "+user_form.cleaned_data['First_name']) return render(request, "modern_business/"+pagelink_html, {'user_form':user_form}) Below is the code in the forms.py file. # /*FORMS.PY*/ from django import forms from firstapp.models import Questionaire from crispy_forms.helper import FormHelper from django.core import validators class FormQuestionaire(forms.ModelForm): helper = FormHelper() helper.form_show_labels = True helper.form_class = 'form-group row' helper._form_method = "post" CHOICES = [('1', 'First'), … -
Django render different form based on user data
I have 3 form in 1 template form email form verification form new password a def get(self, request): user = request.user verif = None verification_form = None password_form = None reset_form = None if verif == 'verif': verification_form = VerificationCode() elif verif == 'change': password_form = SetPasswordForm(user) else: reset_form = ResetPasswordForm() return self.render_to_response({ 'base_url': settings.BASE_URL, 'reset_form': reset_form, 'verification_form': verification_form, 'password_form': password_form, 'verif': verif }) def post(self, request): user = request.user verif = None verification_form = None password_form = None reset_form = None if verif == None: reset_form = ResetPasswordForm(request.POST) if reset_form.is_valid(): messages.success( request, _('Your reset password request has been processed, please check your email.')) verif = "verif" else: print(reset_form.errors) elif verif == 'verif': verification_form = VerificationCode(request.POST) if verification_form.is_valid(): messages.success( request, _('Your Account has verified.')) verif = "change" else: print(verification_form.errors) else: password_form = SetPasswordForm(user, request.POST) if password_form.is_valid(): else: messages.error(request, password_form.errors) return self.render_to_response({ 'base_url': settings.BASE_URL, 'reset_form': reset_form, 'verification_form': verification_form, 'password_form': password_form, 'verif': verif }) I want at the first time the page appears, it will render form email, after user submit, it will render form verification, after user submit again it will render form new password. how did I achieve this without params in url? -
Is there a more efficient way to write this custom SQL in Django based on a conditional number of arguments?
I'm fairly new to SQL and Django and am trying to use custom SQL statements for an app I'm building in Django. The reason I am opting to not use the ORM is to compare performance and to see if I can get it working before taking the time to translate and switch over. Anyways, the application takes a bunch of user defined "filters" such as date range (2 weeks, 1 month, custom range), and a checklist of job types, and spits out the results from the search. So for instance, I made a simplified query along the lines of something I am doing below. Looking at the statement below as an example, I would need to replace each string ('office', 'teacher', '2019-07-01', etc.) with an %s and then pass in parameters. I am planning to build a conditional parameter list to just pass in for the various arguments in python. Query from MySQL SELECT * FROM joblist WHERE (job = 'office' OR job = 'teacher' OR job = 'student') AND date > '2019-07-01' AND date < '2019-07-15'; Becomes this in Django sql_statement = '''SELECT * FROM joblist WHERE (job = %s OR job = %s OR job = %s) … -
How to convert an ImageField of model to its thumbnail and store it to drive using django signals?
I am currently reading the 'practical django 2 and channels 2' book by 'Federico Marani'. He is generating thumbnails for every image uploaded by user to the ProductImage model. Below is the code he used but i don't really understand it. I tried searching about these functions individually and have basic idea of what they do, but i don't understand why he needs most of these functions. So here are the questions i want to ask. What does the line temp_thumb = BytesIO() do? And why is this needed? Why does he then save the image in the next line? Please explain the whole `instance.thumbnail.save` function. Since we are calling the `generate_thumbnail` function BEFORE the 'save' command is executed on the model, since this is a pre_save signal how do we have access to instance.image? Also, if you have a better or easier way to do this, please post it, i will appreciate that. -
Django Increment Counter on Click of Anchor/HREF
I have 2 anchors with hrefs. When clicked, I just want a function to be called that increments a counter in a database to keep track of the number of times the button was pressed (number of shares). Here is the anchors/hrefs: <ul class="mb-30 list-a-bg-grey list-a-hw-radial-35 list-a-hvr-primary list-li-ml-5"> <li class="mr-10 ml-0">Share</li> <li><a href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}"><i class="ion-social-facebook"></i></a></li> <li><a href="http://twitter.com/share?url={{ request.build_absolute_uri }}"><i class="ion-social-twitter"></i></a></li> </ul> I am new to Django. I tried using a url to call a view function, but I do not want to go to a different URL at all. I have a Post model with a share_count variable that represents the counter, but I cannot figure out how to link the click of the anchor to a function that increments and saves share_count in the database. I feel like this should be super easy, but maybe not for a beginner. I would appreciate any help! -
How to filter a query set
I'd like to filter the queryset obtained by filtering once, but I don't know how. Currently, we are getting data from below. And I want to get the data from the table separately on the condition . I just don't know how. #view context_data = super(members,self).get_context_data(**kwargs) group = belong.objects.get(user=self.request.user).group belong_queryset = belong.objects.filter(group=group) #I want to apply belong_queryset to profile filter. profile_queryset = profile.objects.filter(belong_queryset) Sorry for the poor English and explanation. -
how to create trigger which execute specific function at 12:00 AM in Django
I want to create a Trigger or schedule to execute a specific function at 12:01 AM(midnight) in Django. I expect like : def job: print("hello") // run this function every 12:01 AM on specific interval(start_date,end_date) -
Apache reverse proxy for django app running in singularity container
I'm trying to set up an Apache reverse proxy for a django app that is running in a singularity container. I've tried the following in my apache conf.d/app.conf: ProxyPreserveHost On RequestHeader set X-Forwarded-Proto 'https' env=HTTPS ProxyPass "/app_prefix/" "http://localhost:8101/" ProxyPassReverse "/app_prefix/" "http://localhost:8101/" I've tried using the following in the mysite/sittings (django): SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True FORCE_SCRIPT_NAME = '/app_prefix/' None of these seem to work. Here's how I'm starting the django app: /software/singularity/bin/singularity exec -B /basedir:/mnt /basedir/container.simg /mnt/bin/run_in_singularity.sh The 'run_in_singularity.sh' is as follows: cd /mnt/simple-adjax-crud/ python manage.py runserver 0.0.0.0:8101 The app loads, but the app isn't creating relative URLs, so includes are referenced under /static (which can't be found b/c it doesn't match the proxy/reverse proxy). If I work around '/static' by adding additional reverse proxies, then I run into other URLs in the app with the same problem. So I need to figure out how to inform the app to create the correct URLs. Thanks, Brian -
How do I can make a serializer return like a tree
I'm trying to make my serializer models to return thier values like a tree, but I'm not having the correct result. I have tried many forms but, still not working like I want. MODELS from django.db import models from utils.models import DatedAbstractModel ... class Content(DatedAbstractModel): card = models.ForeignKey(Card, on_delete=models.PROTECT, related_name='content_cards') tag = models.ForeignKey(Tags, related_name='content_tags', on_delete=models.CASCADE) text = models.TextField() deletedon = models.BooleanField(default=False) class Meta: verbose_name = 'Content' verbose_name_plural = 'Contents' ordering = ("-created_at", ) def __str__(self): return self.text SERIALIZERS from rest_framework import serializers from .models import Card, Attributes, Tags, AttributeValues, Content ... class ContentSerializer(serializers.ModelSerializer): card = CardSerializer() tag = TagsSerializer() class Meta: model = Content fields = ('card', 'tag', 'text') And I would like to get a return like the exemplo bellow { node: 'root', child: [ { node: 'element', tag: 'div', attr: { id: '1', class: 'foo' }, child: [ { node: 'element', tag: 'h2', child: [ { node: 'text', text: 'sample text with ' }, { node: 'element', tag: 'code', child: [{ node: 'text', text: 'inline tag' }] } ] } ] } ] } -
Generic detail view PostDetailView must be called with either an object pk or a slug in the URLconf
I used get_absolute_url in my model but when I am browsed my post link I got this type error AttributeError at /blog/details/Hello-World1/ Generic detail view PostDetailView must be called with either an object pk or a slug in the URLconf. Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, null=True, blank=True,) title = models.CharField(max_length=200) content = models.TextField() tags = models.ManyToManyField(Tag) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def get_absolute_url(self): title = self.title.replace(" ", "-") return reverse('blog:post_details', args=[title+str(self.id)]) views.py class PostDetailView(DetailView): model = Post template_name = 'blogs/blog_details.html' urls.py path('details/<str:new_str>/', PostDetailView.as_view(), name="post_details"), -
Date format in Django settings for Celery logging
I have Django with Celery and in settings.py I set up logging format: CELERY_WORKER_LOG_FORMAT = '%(asctime)s %(levelname)s %(name)s -- %(message)s' How do I change date format (datefmt) in Django settings.py? If I use LOGGING variable it works for evertything but Celery loggers. I looked at Is it possible to control the datefmt of the Celery task logs? but I don't think I can use it in settings.py -
'ProgrammingError: function avg(character varying) does not exist' - Django project
I have recently deployed a Django project to Heroku. While testing out the functionality in the browser, I've come across a new error when attempting to render a particular template: ProgrammingError at /accelerators/6/ function avg(character varying) does not exist LINE 1: SELECT AVG("reviews_review"."mentorship") AS "avg_mentorship... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. This issue never arose in the development server, but I think I know what the problem is. I use Avg in my Accelerator model to determine the decimal value of a field (avg_mentorship) by determining the mean average of inputs (mentorship) into another model (review). My mentorship field is a charfield where the choices are numbers as strings. I've included the relevant code from either model below: class Accelerator(models.Model): avg_mentorship = models.DecimalField(decimal_places=2, max_digits=3) @property def avg_mentorship(self): quantity = Review.objects.filter(subject=self) if len(quantity) > 0: mentorship_result = Review.objects.filter(subject=self).aggregate(avg_mentorship=Avg('mentorship'))['avg_mentorship'] else: mentorship_result = 0 return mentorship_result class Review(models.Model): RATINGS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) mentorship = models.CharField(choices=RATINGS, blank=False, max_length=1, default='1') def save(self, *args, **kwargs): self.mentorship = int(self.mentorship) super(Review, self).save(*args, **kwargs) It seemed like a pretty simple fix, so I added the bit …