Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Report Card connection to Student model design
I have the two classes that will be used by Admin users to generate Forms in the Django's admin interface and displayed on the front-end using modelformset_factory. # Math, Language Arts, Physical Development etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False, null=True) grade = models.SmallIntegerField() def __str__(self): return self.name # Numbers, Math Operations, Shapes, Gross Locomotor Movement Skills etc... class Standard(models.Model): domain = models.ForeignKey('reportforms.Domain', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100, blank=False, null=True) assessed = MultiSelectField(choices=ASSESSED, max_choices=3, max_length=50, blank=False, null=True) # Trimesters this Standard is assessed (1,2,3) grading_scale = models.CharField(default='PROGRESS_INDICATOR', max_length=50, choices=GRADING_SCALE, blank=False, null=True) #A,B,C,D vs 1,2,3,4 ...etc display_order = models.SmallIntegerField(default=99, help_text="Order in which standard is displayed.") # Trimester Grade Received by Student # Hidden in admin.py t1 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True ) t2 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True) t3 = models.CharField(choices=PROGRESS_INDICATOR, max_length=50, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['domain', 'display_order'] My Question How do I create the relationship to a Student model and be able to enter grades for the student on the front-end. Front-End Screenshot I tried adding something like student = models.ForeignKey(Student) to my Standard model but this created a new Standard for every student report card created #view.py def EditStudentReportGrades(request, student_id): student = … -
i have some problems to deploy django project
I hope to deploy django-tutorial project. but when i excute the command, somthing wrong. uwsgi --http :8000 --home /home/ubuntu/myvenv/ --chdir /srv/django-tutorial/ -w mysite.wsgi this command is okay. sudo /home/ubuntu/myvenv/bin/uwsgi -i /srv/django-tutorial/.config/uwsgi/mysite.ini but it return "Internal Server Error" this is /srv/django-tutorial/.config/uwsgi/mysite.ini i think this file have some problems. [uwsgi] chdir = /srv/django-tutorial/ module = mysite.wsgi:application home = /home/ubuntu/myvenv/ uid = deploy gid = deploy http = :8000 enable-threads = true master = true vacuum = true pidfile = /tmp/mysite.pid logto = /var/log/uwsgi/mysite/@(exec://date +%%Y-%%m-%%d).log log-reopen = true -
Annotated queryset, same name as property on model instance not working
I would like some property to always be there on a model instance. But I also need to annotate it on a queryset for some views. Is this possible? Pseudo-code: Friend(models.Model): name= models.CharField() @property def current_location(self): return self.friendlocation_set.filter(departure_date=None).order_by( '-arrival_date').first() Location(models.Model): name=models.CharField() FriendLocation(models.Model): arrival_date = models.DateField() departure_date = models.DateField(blank=True, null=True) friend = models.ForeignKey('Friend', on_delete=models.CASCADE) location = models.ForeignKey('Location', on_delete=models.CASCADE) class FriendQueryset(models.Queryset): def annotate_current_location(self): last_location = Subquery(FriendLocation.objects.filter( friend=OuterRef('id'), departure_date=None).order_by('-arrival_date').values('location')[:1]) return self.annotate(current_location=last_location) What is the best way to do this? I'd like to keep the name the same. -
Continuous Query Notification (CQN) with Django rest framework python + oracle
im having troubles how to implement the CQN with django rest framework and python. I want when a change happen in the database (ORACLE DATABASE), my django could know about that and make the refresh of the information. Please guys help me, i was trying to find information about weeks -
How to nest two many-to-many field in Django ORM
I have a table that relates two tables, table Author and table Book. +----+------------+-----------+ | ID | Author(FK) | Book (FK) | +----+------------+-----------+ | 1 | 20 | 12 | | 2 | 20 | 35 | | 3 | 20 | 70 | | 4 | 25 | 15 | +----+------------+-----------+ I am using a serializer and my output looks like this: { "1": { "Author": "20", "Book": "12" }, "2": { "Author": "20", "Book": "35" }, "3": { "Author": "20", "Book": "70" }, "4": { "Author": "25", "Book": "15" }, } The desired output would be like this: [ { "author": 20, "books": [ 12, 35, 70 ] }, { "author": 25, "books": [ 15 ] } ] This is my serializer: class AuthorBooksSerializer(serializers.ModelSerializer): class Meta: model = AuthorBooks fields = '__all__' What should I do to merge all the books of an author into one array? -
Update profile changes with signals
There are two models and I want to update the profile bio via signals Models from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) Signals from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: # ! HOW TO IMPLEMENT THESE TWO LINES # ** Add website to user - instance: user else: # ! HOW TO IMPLEMENT THESE TWO LINES bio contains a list of websites for each user and the list has to be sorted and I need profile bio updated when websites are added or users are added in both ways I want profile to be updated. I commented on the lines that I have problems with -
How should I authenticate users in Nodejs with Django authentication
I'm using socket io from Nodejs to create a chat feature in my application which is mainly built using React+Django. I need to use Django's user authentication in Nodejs, so that users are authenticated before they can chat with other users. Here's my plan: When the user opens the chat feature, a post request is sent to the Django server containing the user's id and the user is authenticated. After successful authentication, the Django server sends a code to the Nodejs server, and the same code is sent to the user at the client side. Now, whenever the user sends a message, the codes are compared in the Nodejs server, and if they match, the message is sent. I'm not a pro in web technologies, and I'm pretty sure there are drawbacks to using this method so any help on its validity would be appreciated! (I know how to code it, just need to know if it's the right approach) -
heroku postgres psycopg2.errors.UndefinedTable
Would anyone have any tips for deploying heroku django app with the hobby free postgres version that heroku provides? This error below in the traceback almost seems similar when I was testing locally if I didnt do a python manage.py migrate in the django build process. Also new to django, heroku, and postgress to so tips greatly help. These are my steps using the heroku pipeline to deploy: git push heroku master heroku ps:scale web=1 heroku open This is the trace back through heroku logs when I try to view the webpage: 2021-04-28T15:42:39.226298+00:00 heroku[web.1]: State changed from crashed to starting 2021-04-28T15:42:46.842959+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2021-04-28T15:42:50.000000+00:00 app[api]: Build succeeded 2021-04-28T15:42:50.613040+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-04-28T15:42:50.614019+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Listening at: http://0.0.0.0:38735 (4) 2021-04-28T15:42:50.614239+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [4] [INFO] Using worker: sync 2021-04-28T15:42:50.624501+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [9] [INFO] Booting worker with pid: 9 2021-04-28T15:42:50.648659+00:00 app[web.1]: [2021-04-28 15:42:50 +0000] [10] [INFO] Booting worker with pid: 10 2021-04-28T15:42:51.320006+00:00 heroku[web.1]: State changed from starting to up 2021-04-28T15:43:08.733160+00:00 app[web.1]: Internal Server Error: / 2021-04-28T15:43:08.733171+00:00 app[web.1]: Traceback (most recent call last): 2021-04-28T15:43:08.733172+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute 2021-04-28T15:43:08.733173+00:00 app[web.1]: … -
NGINX not serving media files
I'm hosting a django (wagtail) app on nginx and nginx does not seem to want to serve static files on a certain path. When i host the exact same path in my file structure on two different paths on the website, oen works and the other doesn't. Configuration seems to be exactly the same. I set it up to the same folder for testing purposes. My nginx config is as following server { server_name www.clt.be clt.be; location = /favicon.ico { access_log off; log_not_found off; } location /media/ { autoindex on; root /datadrive/apps/website_prod/clt_website/clt_website/clt_website; } location /static/ { root /datadrive/apps/website_prod/clt_website/clt_website/clt_website; } location / { include proxy_params; proxy_pass http://unix:/run/www-prod-gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.clt.be/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.clt.be/privkey.pem; # managed by Certb> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = clt.be) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.clt.be) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.clt.be; return 404; # managed by Certbot } Has anyone encountered this problem before? I'm at a loss. Edit: the /media/ url is not working. -
Login with token django-rest-framework
how are you all? i working on a project with django rest framework i create the registration view without any problem,but in the login view i have an issue, when i try to log in the response return Invalid credentials note : i tried to login with email instead of username. the code: view.py class ObtainAuthTokenView(APIView): authentication_classes = [] permission_classes = [] def post(self, request): context = {} email = request.POST.get('username') password = request.POST.get('password') account = authenticate(email=email, password=password) if account: try: token = Token.objects.get(user=account) except Token.DoesNotExist: token = Token.objects.create(user=account) context['response'] = 'Successfully authenticated.' context['pk'] = account.pk context['email'] = email.lower() context['token'] = token.key else: context['response'] = 'Error' context['error_message'] = 'Invalid credentials' return Response(context) urls.py urlpatterns = [ path('login', ObtainAuthTokenView.as_view(), name="login"), ] i used this data to post : {"username":"x@example.com","password":"123456"} so why i facing this issue? thanks. -
Adding new object but change not binding data in form
I have problem when i add get_form in ModelAdmin to get request and current user i can add new object but when i what to change object data doesn't appear in form admin.py @admin.register(StaffLeave) class StaffLeaveAdmin(admin.ModelAdmin): model = StaffLeave exclude = [] readonly_fields = [] form = StaffLeaveForm list_display = ['staff', 'leave_type', 'date_of_leave', 'leave_end_date', 'academic_year'] def get_form(self, request, obj=None, **kwargs): StaffLeaveF = super(StaffLeaveAdmin, self).get_form(request, obj, **kwargs) class RequestStaffLeaveF(StaffLeaveF): def __new__(cls, *args, **kwargs): kwargs['request'] = request kwargs['user'] = request.user kwargs['instance'] = obj return StaffLeaveF(*args, **kwargs) return RequestStaffLeaveF forms.py class StaffLeaveForm(forms.ModelForm): current_user = "" class Meta: model = StaffLeave fields = ['staff', 'leave_type', 'reason', 'academic_year', 'date_of_leave', 'leave_end_date', 'status','approved_at'] #TODO this is working well when adding new object but on change data not visible in form def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.user = kwargs.pop('user') instance = kwargs.pop('instance') super().__init__(*args, **kwargs) how can i make data to appear in form when am changing object -
Best way to store Article with Wagtail CMS?
I am trying to understand what is the best way to store Articles in Wagtail website. I see two ways - to store Article as Wagtail Page, and store it as standard Django Model. I’m only at the beginning of my way, so I would like to ask more experienced users to share their approach for this situation. -
How to use template tags in Django
How to use url template tags without model, db in Django I am creating a bulletin board that communicates by DB <> API <> WEB method. Can django templates url parameter be used on 'Web' without model, db? I need to get two acquisitions, how should I use them? I've Googled and tried many things, but there was nothing I wanted to find. I must use the url tag. please help me. THANK YOU urls.py path('board/<int:pk>/comment/<int:id>/delete/', views.Commentapi_delete.as_view(), name="comment_delete"), template <form action="{% url 'comment_delete' ? ? %} method='POST'"> -
How to append GMT+ to datetime object in python
I have a datetime filed in my models.py and another field that saves the selected timezone as well (like Asia/Tehran). I need to append the the utc info of this timezone to my datetime object like this: '20/4/2021 18:33:00 Gmt+4:30 How can i do that? -
Why STATIC_URL is working without STATIC_ROOT? [Python 3.9]
I'm pretty confused here, I am trying to retrieve my static files (for testing purposes) via url with STATIC_URL setting, the problem is that I dont have specified the STATIC_ROOT setting and yet the STATIC_URL setting is still working Why is this supposed to work? the documentation says of STATIC_URL: URL to use when referring to static files located in STATIC_ROOT. But again, STATIC_ROOT is not specified; so why is this working?, i.e, going to the following url: http://127.0.0.1:8000/static/js/main.js is working, dont know why -
COUNT field incorrect or syntax error in filter __in django
I am trying to fetch data in the below manner: ts= Tags.objects.filter(tagtype=2) ls= list(p.entity for p in ts) print(ls) print(len(ls)) users= Users.objects.filter(email__in=ls) print(users) When I checked in DB len(ls) is greater than the result count from Users Table. How do I filter data from Users when the list being passed has more values... like list has 4560 values but matching values in users table is only 4199. I am able to get the data on SQL side, but not able to fetch the data using django filter. -
How can i add a team member in multi tenancy schema
I'm working on a small project using Django with Multi-Tenancy Schema Package, I would like to know how can I add a team member (the first time I use Multi-Tenancy Philosophy ) -
elasticsearch returns RequestError 400
GET 31searchskurecord/_search { "query": { "match_all": {} } , "sort": [ { "sort_order": { "order": "desc" } } ] } returns RequestError(400, 'search_phase_execution_exception', 'No mapping found for [sort_order] in order to sort on') -
Django Admin upload new models to current
recently started programming on django, still trying to understand it. Anyway, i've been assigned to maintain a website/webapp (i don't know how to call it) made in django, as part of the work produce modifies as client needs. Everything was fine untill the modifies are about the current setup. I've made a lot of tries but can't understand why adding new models to the project is not working. The project Listings contains the following models: Listing(Immobili) Photo Owner(Proprietario) Zone(Zona) All the models are related to the Listing. Current Admin form Here a code example (admin.py): @admin.register(models.Photo) class PhotoInline(admin.TabularInline): .... @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): .... inlines=[PhotoInline,...] What i'm trying to achieve is to add the concept of Video, but easier than photo, so i've made a model Video as follow: models.py: class Video(models.Model): listing = models.ForeignKey(...) video_name = models.CharField(...) video_url = models.CharField(...) admin.py: class VideoInline(admin.TabularInline): model = models.Video extra = 1 @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): .... inlines=[PhotoInline,VideoInline...] After those modifies i've launch the python manage.py makemigrations listings python manage.py migrate listings No output error, and the page was working as before. Any advice to upload this modify? Thanks to anyone that will just read the question. -
Django edit details for an existing post via a form
I am working on a job portal project and the recruiter can post an internship. After that, he has the option to edit his post as well. To do that, I display a form. (I am not using Django forms btw). I want to display the values as they are stored in the db in the form input fields. I am getting issues for radio, dropdown, ckeditor textfield and a dynamic input field for skills. Please guys, can you help? Here is my code snippet: <label>Internship Title</label> <input type="text" class="form-control" name="internship_title" value="{{ internship.internship_title }}" required> <input type="radio" id="customRadioInLine1" name="internship_mode" class="custom-control-input" value="Office" {% if '{{ internship.internship_mode }}' == 'Office' %} checked="checked" {% endif %}> <label class="custom-control-label" for="customRadioInLine1">Office</label> <input type="radio" id="customRadioInLine2" name="internship_mode" class="custom-control-input" value="Work From Home"> <label class="custom-control-label" for="customRadioInLine2">Work From Home</label> <label for="industry_type">Industry Type</label> <select class="form-control" id="industry_type" name="industry_type"> {% for ind_type in industry_types %} <option value="{{ind_type}}">{{ind_type}}</option> {% endfor %} </select> <label>Required Skills</label> <div class="input_skills_wrap"> <div> <input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-primary add-more-skill" type="button"><i class="glyphicon glyphicon- plus"></i></button> </div> </div> <label>Internship Description</label> <textarea name="internship_desc" required></textarea> <script> //EMPLOYMENT SKILLS $(".add-more-skill").click(function(e){ e.preventDefault(); $(".input_skills_wrap").append('<div><input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-danger remove-skill" type="button"><i class="glyphicon glyphicon-minus"></i></button></div>'); }); $(".input_skills_wrap").on("click", ".remove-skill", function(e){ e.preventDefault(); $(this).parent('div').remove(); }); CKEDITOR.replace('internship_desc'); -
how write custom view for page model in wagtail
i have page object as below in models.py: class PostPage(Page): template = 'Blog/post_page.html' # Database fields body = RichTextField() main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) promote_panels = [ InlinePanel('related_links', label="Related links"), MultiFieldPanel(Page.promote_panels, "Common page configuration"), ] .... and i want mix this page with other view as below in views.py: class PostPageView(PermissionMixin, PostPage): required_permission = 'special_user' or some views of django-role-permissions or generic-views how can i do that? after mixing them together how explain for context processor to using PostPageView instead of PostPage? -
Django: MultiSelect Field. How to store user checkbox's in database?
I am using Django MultiSelectField package, to allow tutors to choose what grade level they are comfortable teaching. However, I can't seem to find a way to store the user inputs in Django's db. Is this possible? This is the admin page for the field grade_level. Admin This is what the user sees. User. I can get a list of strings with Django's .getlist(). However, I cannot find a way to "check off" these values in the admin dashboard. Thank you! Template Model Form -
Ways to ban users in django
I want a kind of system to ban users. It could be in the admin, or it could be using code. If it's code, then it should allow me to ban certain users, for a certain period of time. It should redirect me to some page saying you are banned. If it's admin, then it's probably a package or module, with the same requirements. Please let me know how I can do this. Thanks! -
How to cache individual Django REST API POSTs for bulk_create?
I have a Django REST API endpoint. It receives a JSON payload eg. { "data" : [0,1,2,3] } This is decoded in a views.py function and generates a new database object like so (pseudo code): newobj = MyObj.(col0 = 0, col1= 1, col2 = 2, col3 = 3) newobj.save() In tests, it is 20x faster to create a list of x1000 newobjs, then do a bulk create: Myobj.objects.bulk_create(newobjs, 1000) So, the question is how to save individual POSTs somewhere in Django ready for batch writes when we have 1000 of them ? -
How can I make this code for getting objects for my list shorter?
I am retrieving database objects to add to a dict, but the keys can't be duplicates, so I've done it this way: carb1 = random.choice(carbs) protein1 = random.choice(proteins) carb2 = Food.objects.filter(category='Carbs').exclude(name=carb1.name)[0] protein2 = Food.objects.filter(category='Protein').exclude(name=protein1.name)[0] veg1 = random.choice(vegs) veg2 = Food.objects.filter(category='Vegetables').exclude(name=veg1.name)[0] meals = [carb1, protein1, carb2, protein2] exclude_these = [o.name for o in meals] carb3 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein3 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg3 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb3) meals.append(protein3) meals.append(veg3) exclude_these = [o.name for o in meals] carb4 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein4 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg4 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb4) meals.append(protein4) meals.append(veg4) exclude_these = [o.name for o in meals] carb5 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein5 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg5 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb5) meals.append(protein5) meals.append(veg5) exclude_these = [o.name for o in meals] carb6 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein6 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg6 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] But this just seems like a ridiculous amount of code to achieve what I want. Is there a way I can shorten this?