Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django 2.2 Models with multiple foriegn keys ,how can one access and filter data?
I have this model of products class Product(models.Model): name = models.CharField(max_length=50) productId = models.AutoField(max_length=50,primary_key=True) productType = models.CharField(max_length=50) productPrice = models.PositiveIntegerField(default=0) matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials Ex. Cotton 90%, Spandex 10%') #Multiple Material divided by comma,mat1 is main material seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA') cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA') I have two foreign Keys, one is to User Class for seller information and another is to Categories with Model Name Cat1. For Same i have related names catlevel1 and sellers. I am using this code in html to access products by current logged in user. {% for prod in user.sellers.all %} {% for color in prod.colors.all %} {% for size in prod.sizes.all %} <tr> <td>{{ prod.name }}</td> <td>{{ prod.productPrice }}</td> <td>{{ prod.matType }}</td> <td>{{ color.colorMain }},{{ color.colorTrim }}</td> <td>{{ size.nameSize }}</td> <td>{{ size.quantity }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} The first loop (first line): {% for prod in user.sellers.all %} accesses all the products by current_user user. Here sellers is the related name of foreign key seller I want to get data using both foreign keys,seller in User Class and categories under cat1. So the main aim is to get products that is of current … -
Multiple authentication types in Django App
I have a Django App which exposes some REST APIs, with LDAP authentication enabled. It is working fine. Now, I want this app to support OKTA authentication as well so that Web UI client can authenticate via OKTA, not through LDAP. How can I configure my Django project to support both kinds of authentication (Ldap + Okta)? -
Django: deletion of files after conversion from TextField to File
I'm very new to Python Programming Language and Django platform. I encountered a problem after converting the texts filled in TextField to a '.txt'. Supposedly if I want to delete the files that I have just created as '.txt' (as given in write_text in Model.py), how can I do it in the Model.py? I have tried it using FileField to upload (as given in fail_fid in Model.py) and delete the files and it works fine. Codes in models.py: from django.db import models class fail_fid(models.Model): Fail_Fid_Title = models.CharField(max_length=100, default=False, null=True) Fail_Fid = models.FileField(upload_to='fids/faillist', blank=True) def __str__(self): return self.Fail_Fid_Title def delete(self, *args, **kwargs): self.Fail_Fid.delete() super().delete(*args, **kwargs) class write_text(models.Model): Fail_Fid_Title = models.CharField(max_length=100, default=False, null=True) Write_Text = models.TextField(default=True, blank=True) Codes in forms.py: from django import forms from .models import fail_fid, write_text class fidForm2(forms.ModelForm): class Meta: model = fail_fid fields = ('Fail_Fid_Title', 'Fail_Fid') class fidForm3(forms.ModelForm): class Meta: model = write_text fields = ('Fail_Fid_Title', 'Write_Text') Codes in views.py from django.shortcuts import render, redirect from .forms import fidForm1, fidForm2, fidForm3 from .models import fail_fid, write_text def failfid(request): fids1 = raw_mica.objects.all() fids2 = fail_fid.objects.all() fids3 = write_text.objects.all() fids4 = fids2 | fids3 return render(request, 'fid_list.html', {'fids2': fids2, 'fids3': fids3, 'fids4': fids4}) def upload_fid(request): if request.method == 'POST' and … -
signing up a Custom user model with createMixinModel
I want to write an API for a Custom User Model with MiXin. I wrote a CustomUser which inherits Django User Model. Then I defined Student Profile with some attributes. in serilizer.py I defined the fields I want to get information from Users. Now in Views.py I don't know how to code to sign up user with CreateMixinModel class StudentSignUpView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView, ): """This part is relatng to sign up students a""" queryset = Student.objects.all() serializer_class = StudentSignUpSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request,**kwargs): serializer = self.get_serializer(data=request.POST) print("answerrrrrr----------->>>", serializer) if serializer.is_valid(): customusers = CustomUser.objects.all() I want to be able a custom user to sign up -
There's Reverse Accessor Error occuring. What is it and how do I solve it?
[I used related_name but it didn't work[][1]1 -
How do I pass table data from a template over to Django on a button/submit click?
My template has a search field that brings up results on a table. In the table, with each result, I'd like to place a "+" Button that will allow the user to save that row of results to their profile. Here is what the page looks like: https://imgur.com/txKSuj0 The relevant chunk of my template: <form action="{% url 'foodlog:detail' foodlist.id %}" method="post"> {% csrf_token %} {{ form2 }} <input type="submit" name="search" value="Search"> </form> {% if foodResults %} <table> <th>Food</th> <th>Calories per 100 grams</th> <th></th> {% for x, y inResults %} <tr> <td>{{ x }}</td> <td>{{ y }}</td> <td> <input type="submit" name="add" value="+" method = "post"> </td> </tr>> {% endfor %} </table> {% endif %} Relevant chunk of my view: if request.method == 'POST': if 'add' in request.POST: #psuedo code #object.create(food=[buttonrow, firstheader], calories=[buttonrow, secondheader]) #object.save() I also don't know why those '<<<<<' appear on the page, as shown in the image. -
How to override model form to add current post_id as ForeignKey for Comment?
I am creating a Post-comments app. I am unable to override the model form for Comment to use the id of the Post being commented on using instance of the post. I have tried using various permutations of the value for the post_id with no success. Here is my models.py: class Post(models.Model): pid = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home')#, kwargs={'pk':self.pk}) class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) My view for creating a comment is as follows: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] return super(CommentCreateView, self).form_valid(form) def get_success_url(self): if blog_messages: messages.success(self.request, self.message) return reverse('blog-home', kwargs={'pk': self.kwargs['post_id']}) The template for creating the comment is as below: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Answer</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info", type="submit">Submit </button> </div> </form> </div> {% endblock %} … -
Django form processing, use data as variable
I'm pretty new in Django development. What i'm trying to accomplish is to process the data from forms and execute that on a windows/linux servers. I have already tried to provide the data through char.field and after clicking the button it was able to display it on the home page. My question is, how can i pass the data to subprocess.check_output and execute it on the servers ? Does it needs to be on the dictionary before returning it on the template? Because when I tried to add a function to execute it via subprocess. The home page is not proceeding due to "No object provided attribute is null" -
Click a html tag, modal form display and data is filled up in form
I'm coding about edit user. I want when I click a tag next to username, edit modal form display and user data is filled up in form. Can show me how do it? Thanks -
How to display result below the form without submitting it in django
Hi I have a form which has a multi-select dropdown on selecting i want to give result without submitting the form. Once result (pass/ fail) is viewed then submit the form and its details get saved in the db. So how do i show result based on the dropdown? -
django.db.utils.ProgrammingError: column "role" of relation "APP_profile" does not exist
Currently, I am facing the above-mentioned error when I am trying to execute the command python3 manage.py migrate I cannot figure out the issue and the posts on Stackoverflow suggest to delete the migrations and recreate it, which I did. But I still face the same issue. Please find below some code: models.py: from __future__ import unicode_literals from django.db import models from bokeh.themes import default from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from django.utils import timezone # Create your models here. class Project(models.Model): REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) form_type = models.CharField(max_length=20, blank=False, null=False) created_at = models.DateTimeField(default=timezone.now()) status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Profile(models.Model): NORMAL = 1 APPROVER = 2 REVIEWER = 3 ROLE_CHOICES = ( (NORMAL, 'Normal'), (APPROVER, 'Approver'), (REVIEWER, 'Reviewer'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() admin.py: from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Profile, Project admin.AdminSite.site_url = '/MyProject' class … -
How to add URL component to current URL via a HTML button? (Django 2.1)
I have a HTML button that is supposed to sort the search results by alphabetical order. Button HTML code: <a href="?a-z=True" type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a> views.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') if request.GET.get('a-z') == 'True': articles = articles.order_by('Title') Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen? -
Django - Unable to open database file (sqlite3.OperationalError)
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } The db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 The root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. My Apache2 config file: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName sub.domain.com ServerAlias sub.domain.com DocumentRoot /var/www/lab <Directory /var/www/lab> Options FollowSymLinks AllowOverride All </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/lab/static <Directory /var/www/lab/static> Require all granted </Directory> <Directory /var/www/lab/chatbot> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/lab/chatbot/wsgi.py WSGIDaemonProcess django_app python-path=/var/www/lab python-home=/var/www/lab/venv … -
Creating a new viewset with multiple filters for the viewset get method
Hi i have a viewset that I am creating. I want to over ride the the get functino and get all the records that have the filtered parameter which is passed into the get view. I also want to be able to do the rest of the crud functionality - GET POST PUT DELETE - and use the paramater that is passed through the url as a parameter for the POST and UPDATE. Right now, when i pass in the parameter, rather than filter the data that is returned, it is giving me no details found which is not what i want. i want it to be used as a secondary filter for all the records that i get back from the database. Here is the code: viewset class PreferenceUserViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer class PreferenceNamespaceViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def list(self, request, namespace=None): # switch user_id value with logged in users id queryset = Preference.objects.all().filter(user_id=1, namespace=namespace) serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) urls: path('preferences/<str:namespace>/', PreferenceNamespaceViewSet.as_view({ 'get':'list' })), path('users/<int:pk>/stacks/', person_stack, name='user-stacks'), I … -
Does rest framework @action kwargs replace class values or not?
I have tried to search the answer for this question on rest framework docs or stackoverflow but I have not been able to find it. Suppose a rest framework viewset: class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() in this case, the extra_action action will have no permission nor authentication classes or will have the ones defined at class level? what happens if I override the get_permissions method? class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_permissions(self): permission_classes = self.permission_classes[:] if self.action == 'extra_action': permission_classes.append(MyPermissionClass) return [permission() for permission in permission_classes] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() Thank you for your help! -
How to enter ForeginKey values in a model with CreateView
I am creating a wiki and need to put in values in the model called revision. This table has a foreigkey to wikipage. My problem is that I am unable to insert values in the revision model. I have tried using def form_valid(self, form) like you would when entering user, without any luck. Models.py class Wikipage(models.Model): title = models.CharField(max_length=100) date_created = models.DateTimeField('Created', auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Wikipages" class Revision(models.Model): wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revisions') content = models.TextField('Content') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) last_edit = models.DateTimeField('Last Edited', auto_now=True) comment = models.TextField('Comment', blank=True) class Meta: verbose_name = 'Revision' verbose_name_plural = 'Revisions' ordering = ['-last_edit'] get_latest_by = ['last_edit'] def __str__(self): return self.content View.py Class WikipageCreateView(CreateView): template_name = 'wiki/wikipageform.html' model = Wikipage fields = ['title'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) The template are as simple as possible with {{ form.as_p }} and all the necessary stuff. -
how to use django_tables2 to filtering table containing data that does not come from django model
I am a newbie in Python and django. I'm creating web application which expose some part of HTTP API of one of my company Security System. Wrapper for the API I keep in file ReducedHXAPI.py. The only data which I keep in db are ip address of the Security System, and authentication data used to login to API. I successfully created a code which shows sortable list of hosts registered in company Security System. Now I'm trying to implement exporting created list of hosts and enabling inline filter for columns. Unfortunately all my attempts (based on tutorials and docs on: https://django-tables2.readthedocs.io/en/latest/index.html and https://django-filter.readthedocs.io/en/master/ ) produce only errors. Could someone help me in making it works and understanding philosophy of django_tables2 and django_filters, please? models.py: from django.db import models class ServerConnection(models.Model): ConnectionName = models.CharField('Connection Name', max_length=200, help_text="Enter name for this connection") ServerAddress = models.CharField('Server Address', max_length=200, help_text="Enter name or IP address of FireEye HX console") APIUser = models.CharField('API User', max_length=200, help_text="Enter name of user who has access to API") APIPassword = models.CharField('API Password', max_length=200, help_text="Enter name of user who has access to API") def __str__(self): """String for representing the Model object (in Admin site etc.)""" return self.ConnectionName ============================================================ views.py (extract) import … -
Sending email from modal in Django
I'm trying to create a simple contact form in a modal window and send email to console at the beginning but it doesn't work. I've got everything set. I've got email backend set correctly as I can send an email from the console. When opening the modal, the url of the website is not changing. Does it have something to do with this? This is what I'm getting in the console [02/Jul/2019 22:30:22] "GET /contact/ HTTP/1.1" 200 1224 [02/Jul/2019 22:30:29] "POST / HTTP/1.1" 200 2229 views.py def email(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): mail = form.cleaned_data["from_email"] subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] send_mail(subject, message, mail, ["example@gmail.com"], fail_silently=False) messages.success("Done") return redirect("homepage") else: form = ContactForm return render(request, "home_page/contact_form.html", {"form": form}) forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) urls.py urlpatterns = [ path('', views.home, name='homepage'), path('contact/', views.email, name='contact')] And html {% load crispy_forms_tags %} <h1>Leave me a message</h1> <form method="post" action=""> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> -
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server which is built in .net framework now this server call API and then implement data with frontend. can you tell me this is good option or not because this is adding one another server means it can make my process slow and cost me more but for security purpose is it good or not? first I implemented my api direct in frontend but everyone can check my api and this can harm my website. I am creating e-commerce website. I didn't used php because I know .net better. -
Make ModelForm Field Larger in Django
I have a ModelForm where there is a description field. Django generates the field at its standard size but I'd like to make it, say, twice as large. I seem to be failing at Googling how to do this. HTML {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST"> <br> <br> <br> {% csrf_token %} <div class="column"> <label for="form.reference">Reference ID: </label><br> <!-- <input type="text" value="{{ reference_id }}">--> {{ form.reference }} <br> </div> <div class="description"> <div class="column"> <label for="form.description">Description: </label> <br> {{ form.description}} </div> </div> <div class="column"> <label for="form.cases">Cases: </label> <br> {{ form.cases }} <br> </div> <div class="column"> <label for="form.count">Count: </label> <br> {{ form.count }} <br> <br> </div> <br> <br> <button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button> </form> Forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') Again I am looking to increase the size of the field for 'description' -
How to get form widgets to render in custom template
I am attempting to have dJango form widgets render on my HTML page. forms.py assignment: class MenuItemsFormBase(forms.Form): name = forms.CharField(max_length=200) html assignment: <div class="col-sm-6 ce_name"> <b>Name:</b><br/> {{ form.name }} </div> From what I understand, this should create an element. Instead, it is rendering the following: " Ricky " What am I doing wrong that is preventing the widgets from rendering? -
Django CBV link product to user and allow to modify only his data
hello I did not understand the principle of django CBV for example I want to create an anonymous voting system and I want to make sure for example that the user can vote only once and I want to crypt also the vote and do some manipulation on the field. add to that I would like to know how to connect an object created to the user and thus allow it to change only these objects (election) my Model #model from datetime import datetime from django.http import Http404 from django.db import models, connection from django.db.models import Q from dzstudent import settings from django.contrib.auth import get_user_model User = get_user_model() class VotingNotAllowedException(Exception): pass class Election(models.Model): """ Represents elections. which can be composed of one or more ballots. Voting only allowed between vote_start and vote_end dates. """ userElec = models.ForeignKey( User, related_name="election", on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False, unique=True, help_text="Used to uniquely identify elections. Will be shown " + "with ' Election' appended to it on all publicly-visible pages.") introduction = models.TextField(blank=True, help_text="This is printed at the top of the voting page below " + "the header. Enter the text as HTML.") vote_start = models.DateTimeField(help_text="Start of voting") vote_end = models.DateTimeField(help_text="End of voting") def __str__(self): … -
Graphene query hangs indefinitely when testing with pytest
I am trying to test my backend, written in Django 2.2.2 and Python 3. I created some graphql queries which are definitely working when testing with the graphql web interface. When testing with pytest and the graphene test client, however, these queries would always hang indefinitely. I put together a reproducible example which is actually based on the code example from the graphene-django documentation. test_example.py: import pytest import graphene from graphene_django import DjangoObjectType from graphene.test import Client from django.db import models class UserModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class User(DjangoObjectType): class Meta: model = UserModel class Query(graphene.ObjectType): users = graphene.List(User) def resolve_users(self, info): return UserModel.objects.all() schema = graphene.Schema(query=Query) client = Client(schema) def test_user(): query = ''' query { users { name, lastName } } ''' result = client.execute(query) assert 0 # dummy assert This example behaves in the same way (stalls forever, no errors). I am using the latest graphene-django (2.3.2) and pytest (4.6.3). I should probably also mention that I'm running this inside a Docker container. Any ideas why this happens? Is this a bug in the graphene-django library? -
What jobs are available for js and Django web app development?
How useful is it in the current software engineer world to know how to make web apps with javascript frontend and Django backend? I want to make a web app from these but I also want to know if this fun project could get me a job doing the same thing at real companies. I have searched a lot on Google for answers but it just pops up with things like if JS is better than Python. -
Date Validation --> end date must be greater than start date
I need to write a script where it validates the end date is greater than the start date. Also the start date/end date cant be before the current date. Needs to be written in Django 1.8.