Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
I want that when I select grade year the specific subject for that grade year will appear
I want that when I select grade year the specific subject for that grade year will appear I want that when I select grade year the specific subject for that grade year will appear //test.html //here is my code in html <select id="id_of_select" name="subject"> <option>--</option>**strong text** {% for ylvl in edulevel %} <option value="{% for sub in subj %} {{sub.Description}}<br> {% endfor %}">{{ylvl.Description}} </option> {% endfor %} </select> <button id="btn">Show selected</button> <div id="display"> </div> <script> function show_selected() { var selector = document.getElementById('id_of_select'); var value = selector[selector.selectedIndex].value; document.getElementById('display').innerHTML = value; } document.getElementById('btn').addEventListener('click',show_selected);; </script> //views.py def test(request): edulevel = EducationLevel.objects.all() id=request.GET.get('id_of_select') print(id) subj = Subject.objects.all() context = { 'edulevel':edulevel, 'subj':subj } return render(request, 'accounts/test.html',context) I want that when I select grade year the specific subject for that grade year will appear -
can't access to django web site with nginx on specific port, connection timed out
I try, in vain, to set up a demonstration website running under django. On azure we have 2 virtual machines accessible from a public address. The website must be launched on a azure virtual machine. Both virtual machines deploy a nginx server, but when I launch a nginx server on the 2nd virtual machine on another port, it's time out. It seems to me that this is a configuration problem. The configuration I use is based on nginx, gunicorn , supervisor , django. This is the django /site_show/miss_site/miss_site/setting.py file : '''python ALLOWED_HOSTS = ['168.63.54.50', "*"] STATIC_ROOT = '/site_show/miss_site/static/' MEDIA_ROOT= os.path.join(BASE_DIR, 'media/') MEDIA_URL= "/site_show/miss_site/media/" TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader',) SITE_ID = 1 ''' some django file : /site_show/miss_site/manage.py /site_show/miss_site/media and /site_show/miss_site/static/ also /site_show/miss_site/templates/ where the index.html is config file for nginx ''' upstream sample_project_server { server unix:/site_show/miss_site/gunicorn.sock fail_timeout=0; } server { listen 8008; server_name 168.63.54.50; client_max_body_size 4G; access_log /site_show/miss_site/logs/nginx-access.log; error_log /site_show/miss_site/logs/nginx-error.log warn; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect http; if (!-f $request_filename) { proxy_pass http://sample_project_server; break; } } location /static/ { autoindex on; alias /site_show/miss_site/static/; } location /media/ { autoindex on; alias /site_show/miss_site/media/; } ''' launch script : ''' NAME="showcase" DJANGODIR=/site_show/miss_site SOCKFILE=/site_show/miss_site/gunicorn.sock USER=www-data … -
How to pass params dynamicaly from template to ListView in Django?
I want to pass params dynamically to ListView via URL: views.py: from django.shortcuts import render from django.views import generic from objects.models import Object class UserObjectsView(generic.ListView): template_name = 'user_objects.html' def get_queryset(self): return Object.objects.all() urls.py: from django.urls import path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects') ] template where I call this url: <h3><a href="{% url 'user-objects' %}{{ user.id }}">Objects</a></h3> I want to pass this user.id dynamically, but right now it appers error: Reverse for 'user-objects' with no arguments not found. 1 pattern(s) tried: ['objects/user/(?P[0-9]+)/$'] -
User Profile picture not displaying on the template but saved to media File
devs...mayday mayday... I want the user profile picture to be displayed on the user dashboard after login, the image saves into the media file, i can display every other details pertaining to the user, but the image is not displaying, the picture is been uploaded when the user wants to update profile details, and not at the point of signup, please any help is appreciated ..Thanks a lot . template <img class="profile-user-img img-responsive img-circle" src="{{ request.user.get_profile.picture.url }}" alt="User profile picture"> <h3 class="profile-username text-center">{{ user.full_name }} {% if user.is_verified %}<i class="fa fa-check btn-primary img-circle"></i>{% endif %} </h3> views.py def image_update(request): if request.method == 'POST': image = request.FILES['image'] # profiles = get_object_or_404(Profile,user=request.user) try: profile = get_object_or_404(Profile,user=request.user) except Profile.MultipleObjectsReturned: profile = Profile.objects.filter(user=request.user)[0] profile.picture = image profile.save() return redirect('app:preferences') else: raise Http404 models.py class Profile(models.Model): user = models.ForeignKey(CustomUser, related_name='profile', on_delete=models.CASCADE) picture = models.ImageField(blank=True, default='user.png', upload_to='images/') -
wifi control using django with billing so users can come subscribe and buy online with cards
is there a Django base application to control and tax my WiFi like the case with a cyber cafe . may be using online payments. also i want to be able to to create my own custom page . if you know of any u please recommend me -
Why does an error occur when saving the form?
There are two models models1 class Work(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='employee_projects') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_work') ... responsibility = models.TextField("employee work responsibility", blank=True) models2 class Project(models.Model): name = models.CharField("project name", max_length=64) description = models.TextField("project description") technologies = models.ManyToManyField( Technology, verbose_name="technologies used on the project") I use modeinlineformset to create new objects forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['name', 'description', 'technologies'] ProjectFormSet = inlineformset_factory(Project, Work, fields=['responsibility', 'start_year', 'start_month', 'end_year', 'end_month'], extra=1) and my views.py class WorkCreateView(AuthorizedMixin, CreateView): """ Create new course instances """ model = Project form_class = ProjectForm template_name = 'work_edit.html' def get(self, request, *args, **kwargs): .... def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) project_form = ProjectFormSet(self.request.POST) if form.is_valid() and project_form.is_valid(): return self.form_valid(form, project_form) else: return self.form_invalid(form, project_form) def form_valid(self, form, project_form): self.object = form.save() project_form.instance = self.object project_form.save(commit=False) project_form.instance.employee = Employee.objects.get(pk=self.kwargs['pk']) project_form.save() return redirect('{}#experience'.format(reverse('profile', kwargs={'pk': self.kwargs['pk']}))) def form_invalid(self, form, project_form): ... But get an error null value in column "employee_id" violates not-null constraint I know what this mistake means, but I don't understand why this happens if I assign a value of the current employee to instance.employee. -
Return json response instead of list of Django models
I am new to python and Django, this is my first project. I followed a tutorial which returned a list of objects. I want to return json instead. I have tried JsonResponse, json.dump but I don't think im implementing these right class ListVenuesView(generics.ListAPIView): serializer_class = VenueSerialiser def get_queryset(self): queryset = (Venue.objects.all()) location = self.request.query_params.get('location', None) latitude = location.split('S')[0] longitude = location.split('S')[1] venue_gaps = {} for venue in queryset.iterator(): locationArray = [y.strip() for y in venue.postcode.split(',')] distance = gmaps.distance_matrix([str(latitude) + " " + str(longitude)], [str(locationArray[0]) + " " + str(locationArray[1])], mode='driving')['rows'][0]['elements'][0] m = distance["distance"]["value"] venue_gaps[m] = model_to_dict(venue) sorted_venues = dict(sorted(venue_gaps.items())) #print(sorted_venues) jsonResponse = json.dumps(venue_gaps, sort_keys=True) print(jsonResponse) return JsonResponse({'data':jsonResponse}, safe=False) This currently throws Got AttributeError when attempting to get a value for field `name` on serializer `VenueSerialiser`. If I replace the return line with return Venue.objects.all() I get a 200 but I need it in json class VenueSerialiser(serializers.ModelSerializer): class Meta: model = Venue fields = ('name', 'location', 'capacity', 'photo_url', 'accomodation', 'cost', 'description', 'postcode', 'email', 'website')