Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating page for individual product
I have a "Category", "Subcategory" and "Product" model. I want to be able to click on a category and have it load a page of subcategories then click on a subcategory and have it load page of products and finally load a page for an individual product when clicked on. Rather than having a view for each category, subcategory and product. models.py class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() category_slug = models.SlugField(max_length=200, default=1) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.category_title class Subcategory(models.Model): subcategory_title = models.CharField(max_length=200) subcategory_image = models.ImageField() subcategory_category = models.ForeignKey( Category, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) class Meta: verbose_name_plural = "Subcategories" def __str__(self): return self.subcategory_title class Product(models.Model): product_title = models.CharField(max_length=200) product_image = models.ImageField() product_base_price = models.DecimalField(max_digits=12, decimal_places=2) product_addons = models.CharField(max_length=200, blank=True) product_description = models.TextField() product_date_added = models.DateTimeField(default=datetime.now, blank=True) product_slug = models.SlugField(max_length=200, default=1) product_subcategory = models.ForeignKey( Subcategory, default=1, verbose_name="Subcategories", on_delete=models.SET_DEFAULT) product_available = models.BooleanField(default=True) -
Don't update avatar image in Django
I would like to update a profile image as if it were not saved in the project. What could be wrong? views.py @login_required def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST,request.FILES,instance=request.user) if form.is_valid(): form.save() return redirect('/perfil') else: form = EditProfileForm(instance=request.user.usuario) context = {'form': form} return render(request, 'polls/edit_profile.html', context) forms.py class EditProfileForm(forms.ModelForm): avatar = forms.ImageField(label='Foto de perfil') class Meta: model = User fields = ['username','first_name', 'last_name','matricula','email','avatar','tipoUsuario'] models.py class Usuario(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('Foto de perfil',upload_to='static/img/uploads/profile_photo',default="static/img/user.jpg") -
How do I save Korean in the database when I use wagtail?
If I create a form in Korean while using wagtail form, how do I solve the problem of storing data in English? I can solve this problem by changing dependencies, but I want to solve this by changing the code in app model. return str(slugify(str(unidecode(self) in site-packages/wagtail/contrib/forms/models.label)) This part is returned str(self).label) This change is saved, but I don't want to change the code of the Dependency. class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') class FormPage(AbstractEmailForm, Page): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), ] def get_context(self, request, *args, **kwargs): context = super(FormPage, self).get_context(request, *args, **kwargs) results = dict() data_fields = [ (field.label, field.label) for field in self.get_form_fields() ] user = int(request.user.id) data_list = [] submissions = self.get_submission_class().objects.filter(page=self, user_id=user) for submission in submissions: data = submission.get_data() data_list.append(data) data_list.reverse() for name, label in data_fields: answer = data.get(label) if answer is None: continue if type(answer) is list: answer = u', '.join(answer) question_stats = results.get(label, {}) question_stats[answer] = question_stats.get(answer, 0) + 1 results[label] = question_stats context.update({ 'results': results, 'data_list': data_list, }) return context def get_data_fields(self): data_fields = [ ('username', 'Username'), ] data_fields += super().get_data_fields() def get_submission_class(self): return CustomFormSubmission def process_form_submission(self, form): self.get_submission_class().objects.create( form_data=json.dumps(form.cleaned_data, ensure_ascii=False), … -
add line number on django-summernote
I want to use summernote on django framework. and I will use summernote by codeview only. than, I want to add line count at the left side of textarea. what shoud I do? $(document).ready(function() { $('#summernote').summernote('codeview.toggle'); $('.note-toolbar').remove(); $('.note-toolbar-wrapper').remove(); $('.note-resizebar').remove(); $('.note-statusbar').remove(); $('textarea').css("height", "100%"); $('#summernote').summernote({ codeviewFilter: true, codeviewIframeFilter: true }); $('#summernote').summernote({ focus: true, // set focus to editable area after initializing summernote callbacks: { onImageUpload: function(files, editor, welEditable) { for (var i = files.length - 1; i >= 0; i--) { sendFile(files[i], this); } } /* onMediaDelete : function($target, editor, $editable) { alert($target.context.dataset.filename); } */ }, lang: 'ko-KR', placeholder: '이제 게시글에 사진을 업로드할 수 있습니다.', codemirror: { // codemirror options theme: 'monokai' } }); }); -
Reverse for 'communication-detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['communication/communication/(?P<pk>[0-9]+)/$']
I wanted to create a new app (communication) in my project that shared very similar properties to my original app (surveys). I essentially copy and pasted the same code into the new app and renamed everything. Unfortunately, now the details page of Communication is broken. The correct pk is showing up in the URL of the page and the views is being accessed correctly. However, the Django debug page is claiming that the pk that has passed through is nothing (''). When I print item.id, it all is correctly displayed. I've tried changing the view referenced in the urls.py to be a different view that I know works and it is successful. My theory is that somehow my specific view doesn't work? views.py class CommunicationView(LoginRequiredMixin, View): model = Communication fields = ('name', 'language', 'prompt_type') def get_success_url(self, **kwargs): return self.object.get_prompt_url() return reverse_lazy('communication-prompts', args = (self.object.id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.GET.get('project'): context['project'] = Project.objects.get(id=self.request.GET.get('project')) return context def get_initial(self): initial = super().get_initial() # context = self.get_context_data(**kwargs) if self.request.GET.get('project'): initial['project'] = Project.objects.get(id=self.request.GET.get('project')) return initial.copy() class CommunicationDetail(CommunicationView, DetailView): template_name='communication/communication_detail.html' def get_context_data(self, **kwargs): self.object = self.get_object() context = super().get_context_data(**kwargs) context['project'] = self.object.project print(context) return context urls.py app_name = 'communication' urlpatterns = [ path('', … -
How to Pass a Value From Class Based View to a Function Based View Using JS in Django
I have a class based UpdateView which has a form value 'reference' that needs to be passed on to a function based view. This updateview is in a bootstrap modal and is being submitted using JS. I need to know how I can amend the code I have to grab the 'reference' value in this form, and pass it on to the function based view 'manifest' forms.py class UpdateManifestForm(BSModalForm): class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') #something like Reference_Nos = form.cleaned_data.get('reference') def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() reference_id = form.cleaned_data.get('reference') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) #return redirect('manifest') #else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) jquery.bootstrap.modal.forms.js (function ($) { // Place the form at formURL to modalContent element of modal … -
what is the best django app for executinng realtime notification?
I am new to Django & building my own application. I want to add notification system to my projects. Now I want to create real time notifications when some commented someone else's post or replayed or liked. So what is the best notification app or the best way to do that? -
Extending field permission - Django
I have this field, on my models, which is an alteration of the localflavors one: class MYField(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 34) self.default_validators = [MyValidator()] super().__init__(*args, **kwargs) def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return self.empty_value return value.upper().replace(' ', '').replace('-', '') def prepare_value(self, value): if value is None: return value grouping = 4 value = value.upper().replace(' ', '').replace('-', '') return ' '.join(value[i:i + grouping] for i in range(0, len(value), grouping)) What I want, is for this field, to show it's value in case current user is_superuser() otherwise, show a string, ie: <mystring> Do You think is a good idea to do this on the field itself, or maybe it is better on a form or something. Also, in any case, could You provide an example of this? Thank You very much -
Django: ImportError "doesn't look like a module path
I just started to learn Django and I tried to add a middleware to my application. Under ProjectFolder/app I have the following files: an empty init.py file settings.py file - the content of this file is default except for: MIDDLEWARE = ( 'SimpleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) SimpleMiddleware.py file: class SimpleMiddleware(MiddlewareMixin): def __init__(self, get_response): print("***********************************SIMPLE MIDDLEWARE") self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print("***********************************SIMPLE MIDDLEWARE") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response def process_request(self, request): print("***********************************SIMPLE MIDDLEWARE") return None url.py file: from app import views urlpatterns = [ path('hello', views.index, name='index'), path('core', include('core.urls')), ] However, when I run the application by the command "python manage.py runserver", I get the error: ImportError: SimpleMiddleware doesn't look like a module path Do you know what I'm doing wrong? -
in django smtp sending emails from wrong user
i have configured in settings.py like this EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'now@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 EMAIL_USE_TLS = True I am using this setting to send email for user registration and everything working fine. Now I have to make a page of contact-us in which user will send mail to my this id 'now@gmail.com' I am trying to send email to like this if request.method == 'POST': name = request.POST.get('name') sender_email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') try: send_mail(subject= subject,message= message,from_email=email ,recipient_list = [settings.DEFAULT_FROM_EMAIL],fail_silently = True,) except BadHeaderError: return HttpResponse('Invalid header found.') render(request, 'MainApp/ContactUs.html') but it still sending using 'now@gmail.com' .. why its the case ? cant i send email on 'now@gmail.com' from user ? -
Cannot locate base.html in root directory. Suspect template loader as problem
I have a base.html file in my root directory. I have a hello_world.html file in my personal_portfolio app's template file that contains {% extends base.html %} in hello_world.html. I have the appropriate entry in the 'DIRS': settings of my personal_portfolio project. I get a template not found error for base.html. In the debug info I see reference to 'django.template.loaders.app_directories.load_template_source'. My impression is that when 'APP_DIRS': is True, this loader is responsible for automatically loading each apps template file in a list of directories to search for templates. I see no reference to ' 'django.template.loaders.filesystem.load_template_source' which I understand is responsible for adding directories in the 'DIRS': setting to the search list. This is how base.html should be located. However, it seems that no matter what I do only the django.template.loaders.app_directories.load_template_source' loader is used. I even tried including a setting for TEMPLATE_LOADERS in settings.py. What I did as a work-a-round is modify the the app_directories.py module to add the directory I am pointing to in the 'DIRS': setting. Here is the app_directories modification in E:\Python Programs\Web Projects II\rp_portfolio\venv\Lib\site-packages\django\template\loaders\app_directories.py. enter code here #************** Revised app_directories.py """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. from django.template.utils import get_app_template_dirs from .filesystem import … -
How to modify url for pagination with aditional get parameters
I'm realising a search list using a simple form using GET. After that, I'm trying to introduce pagination to the list of objects that has been found using that form. The problem is that, inside of the template, I'm using the attribute request.get_full_path and then, adding the attribute 'page' with the following number of the paginator; I use that method because I don't want to loose all the information that the URL contains (csrfmiddlewaretoken, and my others form's parameters). The problem comes when I click more than once on the pages links, because my url has converted in something like: 'URL-WITH-GET-PARAMETERS'&page=X&page=N. The variable called 'worker list is the list of objects returned after the search. {% if workers_list.has_previous %} <a href="{{ request.get_full_path }}&page=1"> First </a> <a href="{{ request.get_full_path }}&page={{ workers_list.previous_page_number }}"> Previous </a> {% endif %} <span class="current"> Page {{ workers_list.number }} of {{ workers_list.paginator.num_pages }}. </span> {% if workers_list.has_next %} <a href="{{ request.get_full_path }}&page={{ workers_list.next_page_number}}"> Next </a> <a href="{{ request.get_full_path }}&page={{ workers_list.paginator.num_pages }}"> Last </a> {% endif %} I expect the output of 'my-url-pah-&formparameters=results&page=N'. -
How to fix: TypeError: QuerySet.annotate() received non-expression(s): eqmunir
I am adding a like functionality in my website where users can like each others posts. I have done this successfully, however have one issue. This is checking whether the user has already liked the post, which has to be performed specifically in my HOME view. This is so I can render my home page. To encounter this issue, I perform a .annotate() on my posts when retrieving them, and see if a user has liked a post. I then pass this onto my home template and check if the user exists within the posts likes property. Here's the related code. models.py: class Post(models.Model): file = models.ImageField(upload_to='images/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, through='Like', related_name='likes') def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] @property def total_likes(self): return self.likes.count() class Like(models.Model): status = models.BooleanField() post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) views.py: def home(request): posts = Post.objects.all() liked_or_not = Post.objects.annotate(likes__user=request.user) return render(request, 'posts/home.html', {'posts': posts, 'liked_or_not': liked_or_not}) home.html: {% if liked_or_not == True %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn btn-primary btn-lg btn-block"><span class="oi oi-caret-top"></span> Unlike {{ post.total_likes }} </button></a> {% else %} <a href="javascript:{document.getElementById('likepost{{ post.id }}').submit()}"><button class="btn … -
TemplateDoesNotExist users/login.html
I'm testing my site on linode port 8000 and it works...but I am getting a TemplateDoesNotExist error when I try to access certain links under my Users application from settings.py import os INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig',] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]''' from project urls.py from users import views as user_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] Project Directory: django_project -> django_project -> urls.py - __init__.py - settings.py -> users -> templates - login.html - urls.py - views.py ```TemplateDoesNotExist at /login/ users/login.html Request Method: GET Request URL: http://45.33.127.12:8000/login/ Django Version: 2.2.4 Exception Type: TemplateDoesNotExist Exception Value: users/login.html Exception Location: /home/nnmott/django_project/venv/lib/python3.7/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /home/nnmott/django_project/venv/bin/python Python Version: 3.7.3 Python Path: ['/home/nnmott/django_project', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/nnmott/django_project/venv/lib/python3.7/site-packages'] Server time: Thu, 22 Aug 2019 21:07:49 +0000``` Any help is appreciated! -
arranging bootstrap cards with for loop
I'm trying to make 2 cards per one line. I want them to align them with some space between them. I tried but it looks like only the first row have the way I want. Can someone please help me... {% for post in post %} {% if forloop.first %}<div class="row">{% endif %} <div class="col-sm-6"> <div class="card" > <img class="card-img-top" src="https://images.unsplash.com/photo-1556740758-90de374c12ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{post.title}}</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> </div> </div> <br> </div> {% if forloop.counter|divisibleby:3 %}</div><div class="row">{% endif %} {% if forloop.last %}</div>{% endif %} {% endfor %} -
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.