Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep two auth system in django
I am working on product where my client can list products on the websites using my platform. I already have login system for my clients. Now I want to have another auth service for buyers on website that is client of out clients. I cant keep both the users in same django table. How to aproch this problem? -
Django Accounting/ Book Keeping/ Ledger App Open Source
I am on quest for an all in one accounting/book keeping/ ledger software for Django. After slaying many a dragons, exploring deep dungeons and looking for threads on all websites, I was able to find some old applications built on, which are not compatible with latest django versions. List of some are as follows: https://github.com/dulacp/django-accounting https://github.com/prikhi/AcornAccounting https://github.com/kunkku/django-financial-accounting And so on.. Further searches in other realms made me realize there are some good open source apps for other platforms like, for PHP: https://akaunting.com/ So much of efforts don't seem to lead me to any satisfactory destination. Finally I thought, why not consult with all my mates here. Here I am on my quest, in need of help from you guys, If you have any idea about such app or you can give me any lead in solving this puzzle, it will be a great help. -
how to assign multiple checkbox field in form to ajax request
I tried following way but not working , i got name from form but nothing got assigned to sharewith. I want all selected checkbox to get assigned to one id "sharewith" and they should be send to server with ajax request, is it possible form: <div class="modal-body"> <p class="statusMsg"></p> <form role="form">{% csrf_token %} <div class="form-group"> <label for="inputName">kcategory</label> <input type="number" class="form-control" id="inputName" placeholder=node name/> </div> <div class="form-check" id="sharewith"> <label for="sharewith">Share with</label></br> {% for sharewith in users %} <input class="form-check-input position-static" type="checkbox" value="{{ sharewith.uid }}"> <label>{{ sharewith.umail }}</label></br> {% endfor%} </div> </form> </div> ajax: function submitContactForm() { var token = '{{csrf_token}}'; var name = $('#inputName').val(); var sharewith = $("#sharewith").val() if (name.trim() == '') { alert('Please enter your name.'); $('#inputName').focus(); return false; }else{ $.ajax({ headers: { "X-CSRFToken": token }, type:'POST', url:'sharing', dataType:"json", traditional: true, data:'contactFrmSubmit=1&name='+name+'&sharewith'+sharewith, beforeSend: function () { $('.submitBtn').attr("disabled","disabled"); $('.modal-body').css('opacity', '.5'); }, success:function(msg) { if (msg == 'ok') { $('#inputName').val(''); $('.statusMsg').html('<span style="color:green;">sucessfully saved</p>'); } else { $('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>'); } $('.submitBtn').removeAttr("disabled"); $('.modal-body').css('opacity', ''); } }); } } how can i assign all checkboxes to sharewith, any help -
Deploying my Django-React app on Heroku with static files served through AWS S3
My SPA works fine locally (React app served by Django via runserver) but when deploying my Django-React app on Heroku and serving my static files by AWS S3 using django-storages and boto3, everything (compiled js, css, media files, etc.) works fine except that static images referenced via React does not render. Basically, everything else has a url like this:https://<my-bucket>.s3.amazonaws.com/static/js/main.js while my static image url remains like http://127.0.0.1:8000/static/media/logo when ran locally and http://<mysite>.herokuapp.com/static/media/logoon heroku. Snippet of how I reference images on \Component.js: import React from 'react'; import logo from "../static/media/logo.png"; const Component = () => ( <div> <img className={classes.logo} src={logo} alt="logo" height="32px" /> </div> ) my \conf.py import datetime import os AWS_USERNAME = "username" AWS_GROUP_NAME = "Group" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID", "my_access_key") AWS_SECRET_ACCESS_KEY = os.environ.get( "AWS_SECRET_ACCESS_KEY", "my_secret_access_key") AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = '<folder>.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = '<folder>.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = '<bucket_name>' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } -
Django Admin, Collapsable text boxes
How do I get these Textboxes to be collapsible? I went through the documentation and this is what I wrote, but the changes are not being reflected. Also, Is there any alternative I can use instead of limiting the user to select a max of 2 project manager or testers or what ever user they want to specify? (Is there a way such that, the user can click on a + button or something so that another user can be listed is what I mean) class FlatPageAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('Project_Name', 'Project_Description', 'Admin_Name', 'Admin_Mail_ID', 'Project_Manager_1', 'Project_Manager_1_Mail_ID', 'Technician_1', 'Technician_1_Mail_ID', 'Tester_1', 'Tester_1_Mail_ID', 'Status_of_the_project', 'Created', 'Finish_Date', 'Supporting_Documents', ) }), ('Add More Users', { 'classes': ('collapse',), 'fields': ('Project_Manager_2', 'Project_Manager_2_Mail_ID', 'Technician_2', 'Technician_2_Mail_ID', 'Technician_3', 'Technician_3_Mail_ID', 'Additional_User_1', 'Additional_User_1_Type', 'Additional_User_1_Mail_ID', 'Additional_User_2', 'Additional_User_2_Type', 'Additional_User_2_Mail_ID', 'Additional_User_3', 'Additional_User_3_Type', 'Additional_User_3_Mail_ID', ), }), ) -
Employee Management System in Django
Developing Employee Management System in Django.I'm new to Django.I used the tutorial on django's website but I think it's not enough for me to do something like this. I want to start to this feature of Employee Module: 1 Admin Can add a new employee. 2.Admin can see the list of all employee. 3.Admin can update and edit the details of employee. 4.Admin can able to delete the employee. 5.Employee can see their information. Can anyone please provide me the lead so I can able to achieve this. Thanks in advance. -
django unable to pass request to form while using formset. Produces `__init__() got an unexpected keyword argument 'request'`
#forms.py class RequestModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(RequestModelForm, self).__init__(*args, **kwargs) class BusinessForm(RequestModelForm): class Meta: model = Business fields = ('title', 'stitle', 'gstin', 'address') def clean_gstin(self): user = self.request.user gstin = self.cleaned_data['gstin'].upper() if Business.objects.filter(owner=user, gstin=gstin).exists(): raise ValidationError("A Business with that GSTIN already exists") return gstin #views.py class BaseFormView(FormView): def get_form_kwargs(self): kwargs = super(BaseFormView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return super(BaseFormView, self).form_valid(form) class Meta: abstract = True class BusinessCreateView(BaseFormView): BusinessFormSet = formset_factory(BusinessForm, extra=3) form_class = BusinessFormSet success_url = '/dashboard' template_name = "business/business_create_form.html" Everything works well if I set extra=1 for the formset_factory. But when extra = 2 or something greater than 1, the error is thrown: __init__() got an unexpected keyword argument 'request' I have identified the problem here. Since I'm popping request inside the __init__ function of RequestModelForm(which is called multiple times when extra is set to more than 1). And there is no request since it is already been popped. I tried doing self.request = kwargs.get("request") instead of self.request = kwargs.pop("request"). But this throws another error 'BusinessForm' object has no attribute 'request'. How to overcome this? Any Help? -
request post method error: get empty array
I want to post a request from electron application to Django application. After posting, I could get the data of email, but I couldn't get answer. It is empty even though I post the data along with it. answer is an array of objects. electron (.js)file $(".submit-btn").click(() => { var submit_answer = [] for(var i = 0; i < questions.length; i++){ localforage.getItem(Q[i], (err,value) => { submit_answer.push(value) }) } request({ method: 'POST', url: "http://127.0.0.1:8000/get_question_lists/", json: true, body: { email: email, answer: JSON.stringify(submit_answer), }, }) }) django (views.py)file @csrf_exempt def get_question_lists(request): """ API to get a list of questions """ if request.method == 'GET': ... elif request.method == 'POST': data = JSONParser().parse(request) print data print data['email'] print data['answer'] # print empty array return None -
How to compare a database foreign key value with form foreign key value in Django?
I have a Django project and I encountered with a problem of comparing a database foreign key attribute with form foreign key attribute. My project files are below : My Model.py File: class Teacher(models.Model): Name = models.CharField(max_length=100) Designation = models.CharField(max_length=100,choices=DESIGNATION) Department = models.CharField(max_length=100,choices=T_Dept) Address = models.CharField(max_length=100) def __str__(self): return self.Name + ", " + self.Designation + ", " + "("+self.Department +"), "+ self.Address class Moderation(models.Model): year = models.CharField(max_length=100,choices=T_Year) semester = models.CharField(max_length=100,choices=T_Semester) examtype = models.CharField(max_length=30,choices=EXAMTYPE) examyear = models.CharField(max_length=30,choices=EXAMYEAR) NamAdd = models.ForeignKey(Teacher, on_delete=models.CASCADE) position = models.CharField(max_length=100,choices=POSITON) def __str__(self): return unicode(self.NamAdd) My forms.py File : class modaForm(forms.ModelForm): class Meta: model=Moderation fields=[ 'year', 'semester', 'NamAdd', 'position','examtype','examyear' ] My HTML File : <form action="{% url 'modIni' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="col-sm-12 col-md-4"> <br> <div class="input-group"> <span class="input-group-addon">Year &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; </span> {% load widget_tweaks %} {{ modForm.year|add_class:"form-control" }} </div> </div> <div class="col-sm-12 col-md-4"> <br> <div class="input-group"> <span class="input-group-addon">Semester </span> {% load widget_tweaks %} {{ modForm.semester|add_class:"form-control" }} </div> </div> <div class="col-sm-12 col-md-4"> <br> <div class="input-group"> <span class="input-group-addon">Exam Type</span> {% load widget_tweaks %} {{ modForm.examtype|add_class:"form-control" }} </div> </div> <div class="col-sm-12 col-md-4"> <br> <div class="input-group"> <span class="input-group-addon">Exam Year</span> {% load widget_tweaks %} {{ modForm.examyear|add_class:"form-control" }} </div> </div> <div class="col-sm-12 col-md-4"> <br> <div class="input-group"> <span … -
using path function and a slug from a different function
So I have an url like "/dramaName" with path('<slug>', views.seasons, name='seasons'), On top of this I want to have "/dramaName/s1e1" but the problem is I'm not sure how to bring the slug dramaName to the new url. in views.py #the below method allows me to create a page with the seasons of the specific drama. def seasons(request, slug): seasons = Season.objects.filter(drama__name=slug) now as for the contents I want it to be like drama/s1e1 but to do that I need to borrow slug from the above view for the drama part. I'm just not sure how to do that def contents(request, slug): content = Content.objects.filter( do I put two slug for the arguments? how do I filter twice? #path('<slug:>/<slug>', views.contents, name='contents'), can someone please help me -
How to query Groups and sort them descending based on number of users in Django?
I need to create a query using the ORM that satisfies the following conditions: Exclude the groups that the current user belongs to Sorts the groups in descending order by the number of users What I have tried so far is: groups = ( Group.objects.exclude( id__in=request.user.groups.all().values_list("id", flat=True) ) .annotate(users=Count("user_set")) .order_by("-users") ) This is excluding properly the groups that the current user belongs to, but I don't have so clear how I can achieve the ordering. I am getting the following error: Cannot resolve keyword 'user_set' into field. -
django give access to a page after entering a password to see content
Hello I would like to know if it is possible to make a page protected by password in django I mean that to see the content of the page you need to enter a password and you don't need to be logged to do that -
Django 1.11 JavaScript catalog not translating text in JavaScript files
I have followed these Django translation docs https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#internationalization-in-javascript-code but can't seem to get translations working in JavaScript files. Here is the code I have added: In urls.py urlpatterns = i18n_patterns( ...., ...., url(r"^jsi18n/$", JavaScriptCatalog.as_view(), name="javascript-catalog"), ) In my base templates: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> In the js file that contains a translation: $(document).ready(function() { console.log(gettext('Error: No help available!')); }); I'm testing it out with this in my djangojs.po file for the 'de' locale: msgid "Error: No help available!" msgstr "THIS IS GERMAN YO" I've run these commands: manage.py makemessages -d djangojs manage.py compilemessages But when viewing the German page I get the fallback text (which is in English). -
Adding Django models constraints?
I have the model Period as below: class Period(models.Model): number = models.PositiveIntegerField(primary_key=True) start_time = models.TimeField() end_time = models.TimeField() How can I add constraints to make Period.start_time < Period.end_time and Period models have the order like this? Period 1: 7:00-7:50; Period 2: 7:50-8:40; ... The field number express the order of the period instance. My approach is adding methods to check if it is valid . However, I want to know that there is any database way to do this. -
Django path error while trying install skin for Admin
I'm trying to install the following skin for my Django admin. I followed all the instructions till the part where I have to update my urls.py url(r'^admin/', include('djadmin.urls')), I've changed the code and tried entering path('admin/', djadmin.urls), also tried path('admin/', include(djadmin.urls)), But its still giving me an error in this line of code. I've added djadmin to my installed files and also updated the middleware. Could anyone help me out? -
myString is unsubscriptable
Here is the problem. Whenever I try to reach my text that is defined in a class with django model, I can retrieve the data but if I want to edit it, I get an error that says: text is unsubscriptable I tried to get the attribute of my class by using getattr, Its still an error. I couldn't achieve it so I was going to ask the solution and why? I believe that It's about django model but I'm not sure of it. from django.db import models # Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): """A string representation of the model.""" return self.text[:50] # The first 50 characters -
how to prevent form submit form when validation from server send failed in django?
I have a login page, when user write username and password, I want to pass this information to server(post) and if I have error i want to just show error message and if I have not error so I want to submit it, in this case always prevent form submit. In the below code always prevent submit and get error message from server and show it: login.js $('#login-form').submit(function(e){ var message; $.post('/login/', $(this).serialize(), function(data){ obj = JSON.parse(data); message = obj.message; alert(message); }); e.preventDefault(); }); view.py // if username and password is faild message="login information is failed" return HttpResponse(json.dumps({'message': message})) //else with specific data return render(request, 'front/member.html', data) I want to do like this: if(message) e.preventDefault(); // else submit but first e.preventDefault(); execute and then message set from server what can i do for this problem? -
How to add sub field count to django ORM model?
I am trying to send sub model count information with the main model to HTML template. I have PROJECT and Companies models: class Projects(models.Model): name = models.CharField(max_length=255) note = models.CharField(max_length=255, default='') def __str__(self): return self.name class Companies(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) name = models.CharField(max_length=255) note = models.CharField(max_length=255, default='') def __str__(self): return self.name I need to show, projects have how many companies(company count): Project name | company.no project1 | 3 project1 | 5 -
Django REST - Serialize User.get_all_permissions
I am building an application with a Django Rest backend, and a VueJS front end and am working through authorization and authentication. I have the authentication working well, but am a bit stuck on letting the front end (VueJS) know what the user has authorization to do in terms of Add/Change/View/Delete for a model. For example, if a user cannot add a customer, I don't want to show the 'Add Customer button'. Working through the Django docs, and solutions on StackOverflow, I believe the simplest way is to send the user's permissions from Django to VueJS. The 'best'/'simplest' way I can see to get the permissions is with the following: userModel = User.objects.get(request.user) return User.get_all_permissions(userModel) Where I am stuck is exactly where to put this logic and how to serialize it. Does the above belong in the View, Serializer, other? Up until now, I have only been working with Models (ModelSerializers and ModelViews), but I don't believe this falls into this category. Thanks in advance... -
In Django, how do you keep a module's url configurations encapsulated inside the module?
Currently, I import url configurations into my Django project with: from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path from rest_framework import routers from greeter.views import GreeterViewSet ROUTER = routers.DefaultRouter() ROUTER.register(r'greeters', GreeterViewSet) urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include(ROUTER.urls)), ] Is there a way where I can move these parts of the code: ROUTER = routers.DefaultRouter() ROUTER.register(r'greeters', GreeterViewSet) into a separate file in greeter/urls.py? And still keep these URLs: GET /greeter/ to fetch list of greeters POST /greeter/ to create a new greeter I have tried: my_project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path, re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^greeters/', include('greeter.urls')), ] greeter/urls.py from django.conf.urls import url, include from rest_framework import routers from .views import GreeterViewSet ROUTER = routers.DefaultRouter() ROUTER.register(r'^', GreeterViewSet) urlpatterns = [ url(r'^', include(ROUTER.urls)), ] But got: $ curl -H 'Accept: application/vnd.api+json; indent=2' -X POST http://localhost:8000/greeters/ { "errors": [ { "detail": "Method \"POST\" not allowed.", "source": { "pointer": "/data" }, "status": "405" } ] } In case it helps, here is my original question that has been resolved: Method "POST" not allowed with Django Rest Framework -
How to represent this two level deep relationship in Django Admin?
The scenario is like this, I have three models : Category, Subcategory and Posts and reltionship among them is like this. class Category(models.Model): cat=models.CharField(max_length=10) def __str__(self): return self.cat class Subcategory(models.Model): cat=models.ForeignKey(Category,on_delete=models.CASCADE,null=True) subcat=models.CharField(max_length=10) def __str__(self): return self.cat class Posts(models.Model): title=models.CharField(max_length=15) subcat=models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True) def __str__(self): return self.title Everything is fine. I have added categories from admin panel and added and linked subcategories with categories too. I, however, want to add posts from admin panel too. Now, the problem is when I'm adding a post from admin panel and selecting subcategories, it lists all the subcategories from all the categories( which is obvious as I have subcategory field in post model). I don't want this behavior, I want to get subcategories from only certain category while saving. For eg: I have a category Django and its subcategories ORM, VIEWS. Plus I have additional subcategories from other categories, say C++. So, If I am publishing a Post and I want that to come from Django category, it should only list ORM and VIEWS in the suggestion in the admin panel. I'm open to make modification in models, like if an additional field is required or something similar like that. Any leads appreciated. -
How to rename owner to owner_id in ModelSerializer using PrimaryKeyRelatedField?
I would like to rename my owner field to owner_id since it is not nested and will only contain the owner's id. I've made some attempts, but receive errors such as {"owner":["This field is required."]}. Here is my serializers.py: class UserJobApplicantSerializer(serializers.ModelSerializer): job_id = serializers.PrimaryKeyRelatedField(source='job', queryset=Job.objects.all()) owner_id = serializers.PrimaryKeyRelatedField( source='owner', read_only=True, default=serializers.CurrentUserDefault() ) class Meta: model = JobApplicant fields = [ 'id', 'job_id', 'owner_id', 'timestamp', ] read_only_fields = ['id',] The view overrides the perform_create and injects the owner_id into the validated_data: class UserJobApplicantAPIView(generics.ListCreateAPIView): lookup_field = 'pk' serializer_class = UserJobApplicantSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): return JobApplicant.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.validated_data['owner_id'] = self.request.user.id return super(UserJobApplicantAPIView, self).perform_create(serializer) What is the correct approach to doing this? Is it possible using PrimaryKeyRelatedField, or would I need to use another type of field (or custom)? I have it working for job_id but job_id is different since it's provided by the user. I'm using DRF 3.8.2 with Django 1.11.15. -
the browser shows "This site can't be reached"
I have a problem, my problem is that the browser shows "This site can't be reached" or "The connection was reset." I have followed the tutorial "How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 18.04" from beginning to end, and yeay it works but it only takes a few moments until I reload my website and the problem occurs Then I followed the "Troubleshooting Nginx and Gunicorn" method to find my problem but with insufficient experience and really just plunging the world like this I was confused about what was wrong and this problem happened. there was one thing that made me hesitate to give a little details on the core of my problem, when I looked at the gunicorn application and gunicorn socket there was a little showing something was wrong and something was stopped. I ask for all of you who really understand so that I can help me to solve this problem and give as many steps as possible or maybe you can find other causes. thank you: D This is the tutorial link that I used maybe this picture can help maybe this picture can help maybe this picture can help -
Changes to my Angular js file will not show
I am trying to figure out why changes to my app's angular js file will not show. I am running a Django app and every time I make changes to the app I do a collectstatic and compileall. The changes would be to a grid table's row name. I have completely changed the name then ran those commands. What I see after restarting the Nginx server and uwsgi would be the old table row names. Am I missing something here? Every other change that I have made seems to be working fine. -
django - pass multiple instance into form and save it in DB
I have a view where they are multiple posts and I want when the user like one of them, the form take the user_id and the post_id and save it into the DB. This is th Models.py: class LikePost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Posts, on_delete=models.CASCADE) def __str__(self): return self.user.username, self.post.name Forms.py: class LikePostForm(forms.ModelForm): class Meta: model = LikePost exclude = ['user', 'post'] Views.py: def posts(request): if request.method == 'POST': form = LikePostForm(request.POST) if form.is_valid(): u = form.save(commit=False) u.user = request.user u.shop = request.shop u.save() return redirect('posts') else: form = LikePostForm() context = { 'posts': Pots.objects.all(), 'form': form } return render(request, "posts.html", context) and this the form in posts.html: <form action="{% url 'posts' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-outline-success">Like</button> </form> this is the error I got: 'WSGIRequest' object has no attribute 'post' please help me