Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Inlineformset not saving in class based updateview
I have a Book and Chapter model with one-to-many relationship. In my views.py I have two classes ChapterEdit and ChaptersManage, to update one Chapter and all Chapters respectively. I am using inlineformset for the ChaptersUpdate view to edit all the chapters that belong to a book. But when I update, the POST request doesn't do anything. The view is not saving the changes to the DB. I don't see any errors either. views.py class ChaptersManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Book fields = ["title", "order"] template_name_suffix = '-manage' #book-manage.html slug_field = 'slug' slug_url_kwarg = 'book_slug' def get_context_data(self, **kwargs): context = super(ChaptersManage, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = ChapterFormSet(self.request.POST, instance=self.object) context['book'] = self.get_object() else: context['formset'] = ChapterFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(ChaptersManage, self).form_valid(form) forms.py class ChapterEditForm(ChapterForm): def __init__(self, *args, **kwargs): super(ChapterEditForm, self).__init__(*args, **kwargs) class Meta(ChapterForm.Meta): fields = ChapterForm.Meta.fields ChapterFormSet = inlineformset_factory( Book, Chapter, form=ChapterEditForm, fields=('title', 'order'), extra=0) What am I missing? -
Django login form not loggin in user with Vuetify
I am new to web development. I am unable to login using django login view after I use vuetify text-field however there is no problem when I don't use Vuetify. Here is the code: Base template <html> <head> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> </head> <body> <div id="app"> <v-app> <v-content> <v-container>{% block forms %}{% endblock forms %}</v-container> </v-content> </v-app> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <script> new Vue({ el: '#app', vuetify: new Vuetify(), }) </script> </body> </html>``` Template {```% extends 'LoginAndSignUp/BaseAuthenticationPage.html' %} {% block forms %} <form action="" method="post"> {%csrf_token%} <v-text-field label='Username'> {{form.username}} </v-text-field> <v-text-field label='Password'> {{form.password}} </v-text-field> <v-btn type='submit'>Login</v-bt> </form> {% endblock forms %}``` -
Django : How to get all data related to logged in user
I want to create a view that returns all data from a model related to the currently logged-in user. eg i have a model that has a relationa to the User table set belo in user_rel : from django.db import models from django.contrib.auth.models import User class ProcessInfo(models.Model): date_created = models.DateTimeField(auto_now_add=True, null=True) user_rel = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag) I want to write a view and this is what I have : def processList(request): user_pk = request.user.id processess = ProcessInfo.objects.get(user_rel=user_pk) context ={ 'processess':processess, } return render(request, 'process/process_list.html', context) I am expecting a list of all processes inserted by the currently logged in user. How do I fix this vew? -
Using multiple dropzones in one form and sending data to django which takes only one request
First I am a beginner in dropzone and javascript. I have one html form, 3 instances of dropzone and the view.py. I want to send with each instance of dropzone different types -> Pictures, documents and videos. There are also data like char and int which I packed in the picture instance by using formData.append. So far I am able to get data from the first instance (picture) by using mydropzone.processQueue() when I fire the submit button on my form. How do I get the other files from the other dropzones into that request? Here the html part: <form id="postform" action="" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{ form.media }} {% include 'Admin/includes/customformfield.html' %} <div id="dropzoneBild" class="dropzone"></div> <div id="dropzoneVideo" class="dropzone"></div> <div id="dropzonePdf" class="dropzone"></div> <div class="row-6"> <button class="btn btn-primary btn-round" type="submit" name="Submit">Submit</button> </div> </form> Here the dropzone instance for picture. The other two dropzones are the same except that the paramName is different and there is no formData.append for the char and int, also the acceptedFiles is different: (function () { var postform = document.getElementById('postform'); Dropzone.autoDiscover = false; var myDropzonebilder = new Dropzone("div#dropzoneBild", { url: postform.action, paramName: "filebilder", autoProcessQueue: false, uploadMultiple: true, parallelUploads: 50, maxFiles: 50, addRemoveLinks: true, acceptedFiles: ".jpeg,.jpg,.png", init: … -
Django import export display all of the values in foreignkey into csv
This is a random model i created to show what im looking for. In this model the store email field is a foriegn key taken from another model which is already populated. There are 10 values in the store email field and i want the exported csv to show all 10. But currently it shows the selected in the picture. -
TemplateDoesNotExist at /admin/listofposts/post/add/
I am trying to install quill-editor but it gives the TemplateDoesNotExist error when I am trying to open it from django admin panel Error during template rendering In template /home/tanmoy/.local/lib/python3.6/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> 28 {% endfor %} 29 </fieldset> -
Django: BaseEmailMessage send BCC emails
When I send emails using BaseEmailMessage, the recipients see each other. I want to avoid this. I tried to use be bcc instead of the to parameter: class ExampleEmail(BaseEmailMessage): pass ExampleEmail(context=context).send(bcc=['example@example.com']) I get an error that the to parameter is required. How can I send emails without recipients being aware of each other? -
what is django most used for
so i know django is a frame work. But I wanted to know what it was most use for. In this post I am linking the most upvote comment. Said it is known/famous/use for Django admin.But I want to know what else it is use for before I try to learn/use it. Also is it useful for database web stuff if so what do people usually use it for in database web stuff? Thanks in advance sorry if this is a really amateur question Is Django for the frontend or backend?. -
How to validate fields properly in Graphene Django
I'm using django-phonenumber-field and graphene-django. Could you tell me how to let graphql throw an error when I'm creating an user with incorrect telephone number format? And also I would like to know how to test it. -
Change Django Celery beat interval
I'm newbie with Django Celery, I ran this command: celery -A projectname beat -l info It print that maxinterval -> 5.00 minutes (300s) I want to extend it to 10 minutes, how can I do it ? -
making a battle royle result sheet. (django)
I have made a model class Results. It stores 'position' of a team and 'kills' secured by team during a tournament. The model class is as follows:- class Results(models.Model): teams=models.ForeignKey(Teams,null=True,on_delete=models.CASCADE) position= models.IntegerField(blank=True,null=True) kills=models.IntegerField(blank=True,null=True) matches=models.ForeignKey(Matches,null=True,on_delete=models.CASCADE) placement_point=models.IntegerField(null=True,default=0) kill_points=models.IntegerField(null=True,default=0) total_points=models.IntegerField(null=True,default=0) now, the team which get 1st postion gets 10 placement points, 2nd get 8, 3rd get 6, 4th get 5, 5th get 4 and all other teams get 0 placement points. Also each kill give 1 kill points(ex 15 kill-> 15 points). This position vs position points is also stored in table class PointsTable(models.Model): position=models.IntegerField(null=True) placement_point=models.IntegerField(null=True) kill_points=models.IntegerField(null=True,default=1) here teams represent individual team like fnatic, cloud9 etc. You can ignore matches field in Results class. All i want to automatically calculate and fill total_points, placement_point, kill_points. Example :- if fnatic get 2nd position with 15 kill then placement_point=8, kill_points=15*1,total_points=8+15=23. actually i m trying to solve this problem using django signal. But i m stuck.Kindly help me out, Thanks. -
Auto model creation through relationship Django
I got a model class Incarico(models.Model): polizza = models.OneToOneField(Polizza, default=None, blank=True, on_delete=models.CASCADE, null=True) and this model here class Polizza(models.Model): partite = models.CharField(max_length=50, default=None, blank=True, null=True) i need to create First the Incarico model through a form compiled by some users, at the moment of creation of Incarico, Polizza needs to be created and linked with the same id. How could i manage to do this? Any help is appreciated!!! -
Requested setting INSTALLED_APPS, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from proto.department import DepartmentSummary courseA = course.objects.values_list('No_Students', flat=True) courseA = list(courseA) department_name=['BSCS'] count = 0 total_students = 0 length = len(courseA) i=0 while i<length: if courseA>0: count=count+1 total_students = total_students+courseA for name in department_name: lt, created = DepartmentSummary.objects.get_or_create( Department_Name=name, ) if not created: lt.Active_courses = count lt.Active_students = total_students lt.save() ``` *i'm trying to fetch data from a model and perform calculations on it and then uploading it into another model but it's showing me this error can anyone tell what to do.* -
Unable to view Product Page - Python django
Im new to python and django and working on a ecommerce project but facing some issues with product details page. Below are the codes for your reference. pls help out what im doing wrong here. Im trying to get product.product_name but its giving error no attribute view: def product_page(request, myid): print(myid) product = Lat_Product.objects.filter(id=myid) print(product) return render(request, 'product_page.html', {'product': product}) url urlpatterns = [ path('', views.lat_product, name="home"), path('product_page/<int:myid>', views.product_page, name='product page') ] model class Lat_Product(models.Model): objects = models.Manager() product_name = models.CharField(max_length=100) product_price = models.IntegerField() product_desc = models.CharField(max_length=150) product_disc = models.BooleanField() product_image = models.ImageField(upload_to='pics') product_new = models.BooleanField() result Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 1 <QuerySet [<Lat_Product: Lat_Product object (1)>]> [08/Jun/2020 17:21:37] "GET /product_page/1 HTTP/1.1" 200 17009 Not Found: /product_page/site.webmanifest [08/Jun/2020 17:21:37] "GET /product_page/site.webmanifest HTTP/1.1" 404 3017 -
Django: how to dynamically generate pdf of the state of current page and email automatically?
I would like to send whatever is in the current page (either as html or as pdf), as an email upon click of a link. Is there a way to do this in DJango? -
Django Url Content Redirect working on Windows but Ubuntu
When i test on windows it's working properly but on uwsgi/nginx Ubuntu it always display previous variables on redirect page. Thank you for your help. My code is basically user enter some variables on home page then i redirect it to the second page to see each time if it has been updated. def create(request): global subnet global vlan_Name if request.method=="POST": vlan_Name=request.POST.get("vlan", "") subnet=request.POST.get("Subnet", "") def nexus(request): context={ 'subnet':subnet, 'vlan_name': vlan_Name, 'vlan_id': VLAN_ID, 'hsrp1':hsrp1, 'hsrp2':hsrp2, 'hsrp_array':hsrp_array, 'gateway':gateway, 'FW_IP':FW_IP, } return render(request,'nexus.html',context) HTML FILE: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> </title> </head> <body style="background-color:LIGHTGREEN;"> <p>name {{vlan_name}} <p> <p>mysubnet {{subnet}} <p> <form action = "/submit" method="post"> {% csrf_token %} <input type="submit" value="Send" style="font-family:verdana;" > </form> </body> </html> -
Why is my Django form returning the QueryDict without the submitted data?
The issue I'm having is that my form data returns not None nor the form values I entered, but simply just the usual csrf_token string and the button's value. I verified this by printing Form(response.POST).data, which returns a QueryDict with just the csrf_token value and the value of the submit button: <QueryDict: {'csrfmiddlewaretoken': ['the token string'], 'save_customer': ['save_customer']}> Contrast this with the other working form's output that works. (I happen to be executing both procedures nearly identically): <QueryDict: {'tail': ['aasdf'], 'aircraft': ['asdf'], ...it's all here... 'csrfmiddlewaretoken': ['the token string'], 'add': ['add']}> So basically, my HTML file includes 2 forms. One form works, and the other doesn't. Having more than one form shouldn't be an issue, especially considering one form is in it's own separate container, and the other form resides in a modal. They do not share any "divs" with each other, nor any "parenting". However, it should be noted that the 2nd form's corresponding view is automatically executed on page load and without any prior doing. The simple existence of the second form causes this to happen. I've deleted the javascript files, removed all traces of javascript functionality within the second form, and yet the view still gets called … -
Auth system checks superuser instead of custom user moel?
I created a custom authentication model. I am trying to authenticate custom user model but instead of that it checks for superusers(users that are created on python shell). Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name='email address',max_length=255,unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) username =models.CharField(max_length=80,unique=True) Views.py class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) def get(self, request, format=None): queryset = User.objects.all() serializer = UserRegistrationSerializer() return Response(serializer.data) Serializers.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) user = authenticate(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'email':user.email, 'token': jwt_token } Basically i am trying to authenticate my custom created users (created from my custom registration form instead of user).Can somebody help? -
Accessing additional fields from a grouper in a Django group_by
How can I access fields other than the grouper in a Django group_by function? class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return "%s" % (self.event.title) def description(self): return "%s" % (self.event.description) class Event(models.Model): description = RichTextUploadingField(max_length=200) view: def my_view(request): events = dateEvent.objects.all() context = { 'events': events, } return render(request, 'view.html', context) template: <ul> {% for event in dateEvents_list %} <li><h5>Event: {{ event.grouper }}</h5> <h6>Description: {{ event.description }}</h6> #How can access the description of the main event? <ul> {% for dateEvent in event.list %} <li>date: {{ dateEvent.start_date_time }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> I'd like to have the title, which is the grouper so it's fine, but also the description. -
Set field default value from field in foreign key - Django
I have two models, Product & Order, and an intermediate model (OrderProduct). The intermediate has an FK to Product in a field called product, and one to Order in order, and an integer field max_quantity not related to them. What I want is set the default value of max_quantity to be product.inventory, But when attempting that, I get: "product" has no attribute "inventory", Even though I have a field called inventory in Product My question is: How can I make this work? max_quantity = models.IntegerField(default=product.inventory) -
TypeError: __init__() got an unexpected keyword argument 'required'
I am using django 3.0 I am new to django I face the error that shows TypeError: init() got an unexpected keyword argument 'required' . my models.py code : from django.db import models from django.utils import timezone from django.utils.text import slugify from django.utils.encoding import smart_text PUBLISH_CHOICES = [ ('private', 'Private'), ('public', 'Public'), ] class BlogPost(models.Model): title = models.CharField( max_length=2000, verbose_name='Post Title', unique=True, error_messages={ "unique": "Enter unique title." }) post_description = models.TextField(blank=True, null=True) post_images = models.ImageField(upload_to='pics') date_of_publish = models.DateField(default=timezone.now) published = models.CharField( max_length=250, choices=PUBLISH_CHOICES, default=None) author_name = models.CharField(max_length=250) slug = models.SlugField(max_length=1000, required=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(BlogPost, self).save(*args, **kwargs) class Meta: verbose_name = 'Blog Post' verbose_name_plural = 'Blog Posts' Ouptput error: init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'required' -
Deploying Django website: SECRET_KEY must not be empty
I'm trying to host a website on Linode server. I'm actually following a Corey Schafer tutorial on youtube, but now I'm stuck. So at this point I'm running commands with SSH in the server, but when I run any manage.py commands, specifically python3 manage.py runserver 0.0.0.0:8000, I'm getting the error in the title. Here's the full error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. settings.py: """ Django settings for trident_site project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ … -
Display owner full name in field panel list
i want to edit the wagtail page model owner so it displays full names not just the username in the wagtail admin. I created a separate class that inherits from the page model so i'm more flexible in customizing the admin area. class PageAdmin(ModelAdmin): model = BlogPage menu_icon = "doc-full" menu_label = "All posts" list_display = ("title", "date", 'category', 'owner') modeladmin_register(PageAdmin) The field pannel content_panels = Page.content_panels + [ FieldPanel('owner'), Is there a way to edit the display value of the owner via hooks or any other method to display first and last name instead of just the username in the admin panel? Thank you! -
Custom Token Authenticating for external microservices in Django DRF
I am using a CustomTokenAuthentication class which extends Django rest framework's Token authentication. class CustomTokenAuthentication(TokenAuthentication): keyword = 'Bearer' def authenticate_credentials(self, key): # username = get_username() username = self._fetch_authorized_user(key) User = get_user_model() user = User(username=username) return user, key _fetch_authorized_user(key) uses an external login client to login users. Question: How do I extend this for external system authentication i.e. Allowing other microservices to authenticate and access these APIs as well. The external login client can't be touched so _fetch_authorized_user(key) will not find a valid username. I'm thinking of adding a fallback when that happens but what would that be? Is it Django's own authentication? (Creating a db and creating profiles for valid external microservices). Can both even work in parallel? Open to other suggestions -
django get filtered by parameter
The site I am building has 6 profiles (desks) and these are accessed via buttons at the top of the page using: path('home/<slug:slug>/', HomeView.as_view(), name='homepage') and is accessed by a button with: {% url 'homepage', slug=desk.slug %} So is filtered in the queryset. How can I access what that value so I can use it in the template for styling purposes? basically I want to highlight the desk button on the page so the user has visual feedback on where he is. Is there a way to do this nicely, as currently the only way I can think of doing this is to use: {% request.url %} and then split off the end of the url, but that seems like a nasty hack to me. Unfortunately google can't get past the word filter so all I get is django-filter documentation and issues.