Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to determine attribute is select/choice in django model?
Currently implementing searchbox which provides two interface - textbox if required input is not normalized, and dropdown if required input is normalized and is defined with choices param in model, and select class in form.I've currently found that I can retrieve each fields' html snippet by doing str(field), for field in form, and with beautifulsoup or other html parsing library I can find input type(is text field or dropdown(select)), and option values for dropdown. But it seems too compilcated, and I'm currently guessing that there might be some way django provides to determine such things.Looking forward, and thanks in advance for any help. -
How to join 3 models of existing database tables with specific column key?
I'm developing a web app using Django REST as the backend, and Angular as the frontend. I have a legacy database (read-only) that has 3 tables that I want to join together to get all the data I need. Basically, I'm using the result of this query to auto-populate a form. The user will enter a known meter number into the form and then click a button that will pull the other related information into the form - minimizing data entry. Simplified database tables and fields MeterNumber bi_acct bi_srv_loc_nbr bi_mtr_nbr Customer bi_acct (join to MeterNumber table) other fields I need ServiceLocation bi_srv_loc_nbr (join to MeterNumber table) other fields I need So, as you can see, these tables can all join to the MeterNumber table based on the bi_acct and bi_srv_loc_nbr fields. I want to be able to make a REST call to something like: server/meter_number/123456 And then the JSON response would be something like: { "bi_acct": 111111, "bi_srv_loc_nbr": 222222, "bi_mtr_nbr": 123456, "customer": [ { "bi_acct": 111111, "needed_field": "... " } ], "service_location": [ { "bi_srv_loc_nbr": 222222, "needed_field": "..." } ] } And this response would be used to auto-populate the form. But how do I create these joins and have … -
How I can queryset all checkboxed objects after filtered in admin change list?
I have actions add_mail_group I trying to add all selected objects in admin change list from UserProfile models into Group models subscribers field But after uenter image description herese filter (list_filter) or selected all objects, or more than 100, thats added null objects. Can somebody help me, please? class UserProfile(models.Model): first_name = models.CharField(verbose_name='Name', max_length=32) email = models.EmailField(verbose_name='E-mail', unique=True) class Group(models.Model): title = models.CharField(verbose_name=' Name', max_length=128) subscribers = models.ManyToManyField(verbose_name='Users', to=UserProfile) def add_mail_group(self, request, queryset): from mailing.models import Group import datetime now = datetime.datetime.now() today = datetime.date.today() title = 'Group from date ' + now.strftime("%d-%m-%Y") mail_group = Group(title=title) mail_group.save() mail_group.subscribers.set(queryset) messages.add_message(request, messages.INFO, f'Group was added ') return HttpResponseRedirect("../") add_mail_group.short_description = 'Create email group' -
How to return Posts author ID and username instead of just ID in DjangoREST
When I make a GET request to my /api/posts/ I recieve only author ID, but I also want author username to display it. How would I do that? I want response to be something like this: [ { // all other stuff author: { id: 1, username: "foo" } } ] This is my Post viewset: class PostViewSet(viewsets.ModelViewSet): """Handle CRUD for Posts""" serializer_class = serializers.PostSerializer authentication_classes = (TokenAuthentication,) queryset = Post.objects.all() def perform_create(self, serializer): """Set author to current user""" serializer.save(user=self.request.user) And this is what I get in response: [ { "id": 1, "title": "Welcome!", "description": "Welcome test!", "created_at": "2019-09-21T01:05:58.170330Z", "author": 1, "community": 2 } ] I want to do the same for community as well but I think I'll figure it out from the author solution. -
How to manage Java and Python apps on docker?
I have a Python app based on Django that I run over a docker container. The app browses the file system and does analysis on some XML files and extracts embedded source code and exports that into separate files. The app should run a Java jar file that does static code analysis on files generated by the Django web app. I thought of isolating both parts of the whole platform. The Python Django part is on a container, the jar file (it's an open source tool) runs on another alpine container. Now I want to continue development of the tool and make the Django app run the tool through a command on each file that's generated that contains source code. Should I create another Django wrapper on the jar file to expose some endpoints so that the first container could run it? Is there another way I could enhance this architecture? Edit: The tool I'm using: https://github.com/AbletonDevTools/groovylint -
I'm trying to implement stripe payments on django but I am getting this error
Below is the error thrown. Immediately I try to submit payments by pressing the button I get the error attributed error at //charge. AttributeError at /charge/ module 'stripe' has no attribute 'Charge' Request Method: POST Django Version: 2.2.4 Exception Type: AttributeError Exception Value: module 'stripe' has no attribute 'Charge' This is my function code: if request.method == 'POST': charge = stripe.Charge.create( amount = 500, currency = 'usd', description = 'A django charge', source = request.POST['stripeToken'] ) return render(request, 'charge.html') -
Setting a condition based redirect in a class based view (Django)
I'm (beginner) creating a simple blog app. I created a class based view to create a blog post and it has a separate URL. I want it redirect to the login page (url name = 'login') if the user isn't logged in. In a function based view all I have to do is this: def postCreateView(request): if not request.user.is_authenticated: return redirect('login') I don't know how to do this in a class based view (inherited from generic CreateView). I tried modifying the init() method like this: def redirectLogin(self): return redirect('login') def __init__(self, *args, **kwargs): if(not self.request.user.is_authenticated): redirectLogin() super().__init__() (I named the class PostCreateView) But on debugging the Exception Value was 'PostCreateView' object has no attribute 'request'. I need the correct way (The Django convention way if it exists) to set a condition based redirect in class based view. Also I'm confused why it says the view doesn't have an attribute 'request'. Every view has request. I'm sure about it because I overrode the form_valid() method to set the author of the post as the currently logged in user like this: def form_valid(self, form): form.instance.author = self.request.user return super().form_valid() And it run perfectly fine when I logged in and created a post. … -
Django model field default value same as PK
I have a django model with id as PK and another field called sub_user which I want by default to have the same value as the ID.How can I do that? sub_user = models.IntegerField(default= ? ) -
Django TypeError at /servicesurvey/8:pk
This error occurs when I try to call another page to edit the information about the main service page. TypeError at /servicesurvey/8:pk edit_survey() got an unexpected keyword argument 'int' Request Method: GET Request URL: http://localhost:8080/servicesurvey/8:pk Django Version: 2.0 Exception Type: TypeError Exception Value: edit_survey() got an unexpected keyword argument 'int' home page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- /Css --> <link rel = "stylesheet" type = "text/css" href = "../static/survey.css" /> <!-- /Css --> <title>Delta</title> <!-- /Fonts --> <link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet'> <link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900" rel="stylesheet"> <!-- /Fonts --> </head> <body> <div> <div class="absolute"> <h1 id="home_name">Delta</h1> </div> <div id="Delta" class="logoPrincipal"> <img src="../static/logo.png" alt="Delta"> </div> <div> <ul class="nav"> <li> <a href="{% url 'qrcode' %}"> <img src="../static/images.png" alt="Leia o QR Code com seu celular"> </a> </li> <li> <a href="{% url 'servicesurvey' %}"> <img src="../static/form.png" alt="Leia o QR Code com seu celular"> </a> </li> </ul> </div> <div> <section> <p>teste123...</p> </section> </div> <div> <section> <p>teste123...</p> </section> </div> </div> </body> </html> edit page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Editar Pesquisa</h1> <form class="formSurvey" action="{% url 'edit_survey' survey.id %}" method="post"> {% csrf_token %} {{ surveyform }} <div class="row"> … -
Is it possible to extends only some part of the templates in django?
I have a blog app and in my about page I want to only extends navigation bar i don't want to extend sidebar which is present in my base templates. Is is possible to do, please explain. Because in my about page, I only want a images and some text with the navigation bar. -
Djano-viewsets. How to get the ID parameter from the path in perform_create fun
I'm trying to do a REST in Django using the VIEWSETS library. I created a Container model that works well. Container is associated with the ContainerModerator model. The endpoint should be: POST containers/{container_id}/moderators One of the fields in ContainerModerator is container_id. I would like to get it from the path. Below is what I have now. I tried in different ways to get there. I also read similar posts, usually for a library other than VIEWSETS. I am a beginner and I wonder if there is a simple, elegant solution for this case that will be easy for me to understand? Should I use other libraries like APIVIEW or GenericAPIView? models: class ContainerModerator(models.Model): moderator_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) container_id = models.ForeignKey(Container, on_delete=models.CASCADE) serializers: class ContainerModeratorSerializer(serializers.ModelSerializer): class Meta: model = models.ContainerModerator fields = '__all__' views: class ContainerModeratorViewSet(viewsets.ModelViewSet): serializer_class = serializers.ContainerModeratorSerializer queryset = models.ContainerModerator.objects.all() def perform_create(self, serializer): serializer.save() urls: router.register('v1/containers/<int:container_id>/moderators', views.ContainerModeratorViewSet) urlpatterns = [ path('', include(router.urls)) ] -
How to change Site model object in django data migration?
What I want to do is that I want to change Site display name and domain from example.com to mydomain.com . Normally, I can enter into the django admin and do this. But I want to use data migration. My code is as below: from django.db import migrations def change_site_name_from_example_to_mydomain_func(apps, schema_editor): Site = apps.get_model('sites', 'Site') site = Site.objects.get(name='example.com') site.name = 'mydomain.com' site.domain = 'mydomain.com' site.save() class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(change_site_name_from_example_to_mydomain_func), ] However, I get an error saying that there is no such app as sites. Te question is, how can I use Site model in a data migration? -
how to serve content of text file as raw text in Django
I am trying to serve raw text from a text file in my static directory using Django. I am able to view this text, but it is not formatted the same as the text file. It is ignoring the /n. My text file (test.txt) is formatted like this: #testscript print("hello world") another line In my view: class testUpdate(LoginRequiredMixin,TemplateView): template_name = 'testUpdate.html' login_url = 'login' def get(self, *args, **kwargs): f = open('static/updates/test.txt', 'r') file_content = f.read() f.close() return HttpResponse(file_content, content_type="text/plain") Which outputs in the browser: #testscript print("hello world") another line I have also tried .readlines() instead of .read() and this still ignores the /n -
How can a view call a function (which is not a view) in django?
Is it possible to create a view/function in django that is callable only another function I.e. the function doesn't accept get/post request. -
Online File Management
I am creating a django based website in which user can create folders and store some text (specifically urls and their 1 line description) in a hierarchical folder way .The site will contain a login option after that user can create folders and inside them subfolders and inside the sub folders, the user can store url and their description. I need help in set up of database so that whenever a user logins and click on a particular folder he/she can view his/her folders and their content and create new sub folders and delete them. I am trying to use postgresql, i am all okay with the front end but the main thing in which i need help is how to create database for each folders and how to load them in my website. PS: I am trying to keep a constraint that if a user has created folder 'A' he/she can store text but if a sub folder 'B' is created the user cannot store links in 'A'(parent folder) the links needs to be stored in the sub folders and notify to move the previously stored links to a sub folder. Same goes for the sub folders. Example now … -
How to give user a option to choose Login or Signup in python using django framework?
Hello I am creating a web app and I want to give usera option to login or signup using django . But the code was not giving the output I want . If Signin is choosen , the user will be redirected to his feed . If Signup is chosen , he need to create a new account using his email . I just Used This Code : import django import datetime def getdate(m,d,y): m=int(input("Enter Month :")) d=int(input("Enter Date :")) y=int(input("Enter Year :")) date1=datetime.date(m,d,y) return date1 print("WELCOME TO MOVIE REVIEW") asksgn=print("I Want To Sign In ") asksgnup=print("I Need To Create A Account ") sgn=input(asksgn) sgnup=input(asksgnup) if sgnup==True: class usrprofile: usrname,__pwd,dob,nick=0 def profile (self,usrname,__pwd,dob,nick): self.usrname=input("Enter Your Name :") self.__pwd=input("Enter Your Password :") self.dob=getdate() self.nick=input("Enter Your Nickname :") def __init__(self): print("Welcome To Movie Review Office") def __del__(): print("Bye Bye") -
Limiting access to objects in Django
I have a particular model and that model has finegrained access settings. Something like: class Document(models.Model): ... access = models.ManyToManyField(Group) Groups consist of particular tags, and those tags are linked to users. Long story short, one way or another the documents are only accessible by particular users. It is very important that this check does not slip through the cracks. So I can see a number of options. One is that every time I access a Document, I add the check: Document.objects.filter(access__group__tag__user=request.user) But there are two drawbacks: a) I query the documents model > 100 times in my views so I will have a LOT of repeated code, and b) it's quite likely that someone will at some point forget to add this restriction in, leaving documents exposed. So I am thinking that overwriting the objects() makes most sense, through a custom manager. That way I don't duplicate code and I don't risk forgetting to do this. class HasAccessManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(access__group__tag__user=request.user) class Document(models.Model): ... access = models.ManyToManyField(Group) objects = HasAccessManager() However, the problem becomes that request is not accessible there: name 'request' is not defined How to solve this? Or are there better solutions? -
convert sum value to percentage by userid django
trying to convert the total sum to percentage by userid. An error pops out when I tried to run. The error is: "unsupported operand type(s) for /: 'dict' and 'int'". Below is my code for Views.py def attStudName(request): students = MarkAtt.objects.values('studName__VMSAcc').annotate(mark=Sum('attendance')) ttlmark = MarkAtt.objects.values('studName__VMSAcc').aggregate(mark=Sum('attendance')) if (ttlmark): ttl = (ttlmark/1100) * 100 context = { 'students' : students, 'ttl' : ttl } return render(request,'show-name.html',context) How do i convert the total sum to a percentage? -
Django LDAP Authentication Group Membership problem
I am trying to implement LDAP authentication for a Django project. There are three different groups which are allowed to log in. user1 is a member of grp1 and user3 is a member of grp3. So they are supposed to be login but while user1 can log in user3 can not!. LDAP directory has Posix standards. Here is the configuration: from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery, PosixGroupType AUTH_LDAP_USER_SEARCH = LDAPSearch( 'cn=Users,dc=company,dc=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)', ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'cn=Groups,dc=company,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=posixGroup)', ) AUTH_LDAP_GROUP_TYPE = PosixGroupType() AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery('cn=grp1,cn=Groups,dc=company,dc=com') | LDAPGroupQuery('cn=grp2,cn=Groups,dc=company,dc=com') | LDAPGroupQuery('cn=grp3,cn=Groups,dc=company,dc=com') ) AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_superuser': 'cn=grp1,cn=Groups,dc=company,dc=com', 'is_active': ( LDAPGroupQuery('cn=grp1,cn=Groups,dc=company,dc=com') | LDAPGroupQuery('cn=grp2,cn=Groups,dc=company,dc=com') | LDAPGroupQuery('cn=grp3,cn=Groups,dc=company,dc=com') ), } Debug output is here: search_s('cn=Users,dc=company,dc=com', 2, '(uid=%(user)s)') returned 1 objects: cn=user3,cn=users,dc=company,dc=com DEBUG 2019-09-21 08:09:13,193 config 378 140589423471392 search_s('cn=Users,dc=company,dc=com', 2, '(uid=%(user)s)') returned 1 objects: cn=user3,cn=users,dc=company,dc=com cn=user3,cn=users,dc=company,dc=com is not a member of cn=grp1,cn=groups,dc=company,dc=com DEBUG 2019-09-21 08:09:13,253 backend 378 140589423471392 cn=user3,cn=users,dc=company,dc=com is not a member of cn=grp1,cn=groups,dc=company,dc=com Caught LDAPError while authenticating user3: NO_SUCH_OBJECT({'desc': 'No such object', 'matched': 'cn=Groups,dc=company,dc=com'},) WARNING 2019-09-21 08:09:13,257 backend 378 140589423471392 Caught LDAPError while authenticating user3: NO_SUCH_OBJECT({'desc': 'No such object', 'matched': 'cn=Groups,dc=company,dc=com'},) search_s('cn=user1,cn=users,dc=company,dc=com', 0, '(objectClass=*)') returned 1 objects: cn=user1,cn=users,dc=company,dc=com DEBUG 2019-09-21 08:44:14,586 config 405 … -
How add multiple fliters to a model
I have inventory, status and transaction tables. Transaction has many to one inventory link and inventroy has one to one relation to status. I am trying to pull all the transaction with check out > 3 sep and inventory which has staus checkout in Django. I am using following syntax to pull in pyton, it give error inventory = Inventory.objects.get(status = 2) transactions1 = Transaction.objects.filter((checkout_time__gt='2019-09-03') and inventory__in=inventory.id) -
Systemctl enabled service does not load at boot
I'm running multiple Django instances and have followed this guide to set it up: running two instances of gunicorn That means that I have a template file (/etc/systemd/system/gunicorn@.service): [Unit] Description=gunicorn daemon After=network.target PartOf=gunicorn.target # Since systemd 235 reloading target can pass through ReloadPropagatedFrom=gunicorn.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/webapps/%i ExecStart=/home/ubuntu/webapps/djangoenv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/%i/kb.sock kb.wsgi:application [Install] WantedBy=gunicorn.target And I am running these instances: systemctl start gunicorn@project1 systemctl start gunicorn@project2 This all works very well. The systems run properly and all is well. However, I have enabled the services: systemctl enable gunicorn@project1 systemctl enable gunicorn@project2 Returning something like: Created symlink /etc/systemd/system/gunicorn.target.wants/gunicorn@project1.service → /etc/systemd/system/gunicorn@.service. So far, so good. However, when I reboot the system these units do NOT go live: systemctl status gunicorn@project1 ● gunicorn@project1.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn@.service; indirect; vendor preset: enabled) Active: inactive (dead) dmesg returns no errors, neither does journalctl: # journalctl -u service-gunicorn.service -- Logs begin at Thu 2019-02-28 18:29:51 UTC, end at Sat 2019-09-21 08:31:11 UTC. -- -- No entries -- # journalctl -u service-gunicorn@project1.service -- Logs begin at Thu 2019-02-28 18:29:51 UTC, end at Sat 2019-09-21 08:31:11 UTC. -- -- No entries -- I have tried to re-enable the service but no change either. When I … -
chrome inspect doesnt showing javascript files in my django application
1.My django application when inspected in Google Chrome in sources tab it shows css files but not the JavaScript file. I Included external link in my django code using '{% %}' but not working, even loaded static at top of page. -
Image upload not working with DRF and React
I am trying to implement image upload functionality using React and DRF. I believe it is not working properly. When I tried to upload image with correct format, it is working fine. But when I tried to upload invalid image, in response it is giving me a long error other than I mentioned in code. class ArticleManager(models.Manager): def active(self, *args, **kwargs): return super(ArticleManager, self).filter(draft=False).filter(publish__lte=timezone.now()) class Articles(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) short_title = models.CharField(max_length=300, blank=True, default='not available') content = models.TextField() draft = models.BooleanField(default=False) # publish = models.DateField(auto_now=False, auto_now_add=False) publish = models.DateField(auto_now_add=True, blank=True, null=True) read_time = models.IntegerField(default=0) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(unique=True, blank=True) like = models.BooleanField(default=False) image = models.ImageField(null=True, blank=True, upload_to='images/articles/') thumbnail = models.ImageField(null=True, blank=True, upload_to='images/articles/thumbnail/') objects = ArticleManager() def __unicode__(self): return self.title def __str__(self): return self.title class Meta: ordering = ['-timestamp', '-updated'] def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if not self.pk: self.slug = create_slug(Articles, self.title) if self.image: image_type = self.image.name.split('.')[-1] self.image.name = '{}.{}'.format(self.slug.replace('-', '_'), image_type) if not self._get_thumb(): raise ValueError("Thumbnail could not be created") # I am expecting to get this error return super(Articles, self).save( force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields ) def _get_thumb(self): image = Image.open(self.image) image.thumbnail((200, 200), Image.ANTIALIAS) thumb_name, thumb_extension = os.path.splitext(self.image.name) … -
Create custom page view counter in Django
I want to create my own view counter. I got inspired from django-hitcount. I read all models of this app. In these lines: class HitCountMixin(object): """ HitCountMixin provides an easy way to add a `hit_count` property to your model that will return the related HitCount object. """ @property def hit_count(self): ctype = ContentType.objects.get_for_model(self.__class__) hit_count, created = HitCount.objects.get_or_create( content_type=ctype, object_pk=self.pk) return hit_count I couldn't understand the meaning and usage of ContentType and get_for_model(self.__class__). Can anyone help me? Source of this model is here. -
How to create multiple images for specific product using django ajax jquery
i'm learning django and i'm trying building ecommerce website , I want to build a system that allows users to upload images to specific product in the store so I tried to pass the id of the product in url parameter and try to access that id from my class based view so I can add images to that item, but i had always a problem showing up and i can't figure out what is the problem, This my code urls.py from django.urls import path from item.views import ProgressBarUploadView app_name = 'item' urlpatterns = [ path('progress-bar-upload/<int:pk>/', ProgressBarUploadView.as_view(), name='progress_bar_upload'), ] views.py class ProgressBarUploadView(View): def get(self, request, *args, **kwargs): print(self.kwargs['pk']) # i want to print pk of product photos_list = Photo.objects.all() return render(self.request, 'zwwebsite/item_images_creation.html', {'photos': photos_list}) def post(self, request, *args, **kwargs): time.sleep(1) form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() print(self.kwargs['pk']) # i want to print pk of product data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) models.py class Photo(models.Model): item = models.ForeignKey(Item, null=True,on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) file = models.FileField(upload_to='media/item_image') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', ) my template {% load staticfiles %} <!DOCTYPE html> …