Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to relate two models (send json) to backend | DjangoRest | ReactJS
The question might not be clear from the title. I want to relate two models. I have created the backend and everything is working fine on the frontend (React) and backend (Django) but I want to connect two models Tags and Startups. I am creating the Startup and I want to relate tags that are already created to the startup. I do not understand how can I acheive that. I can do this using django admin. My admin view of creating a startup looks like this - I can relate tags using the list you see in the Tags: field. I want the same layout in the frontend to relate my models. I have created this - I have all my tags in the dropdown list shown in the picture. I am sending this data object to my DjangoRest Api - { "name": "NameS", "description": "DescS", "contact": "contact@gmail.com", "tags": [ { "name": "First Tag" }, { "name": "Third Tag" } ] } This is creating a new startup but without any related tags - Here is my startup api view - I want to acheive the task my django admin is doing using react. -
Left Join in Django
I have the following models: class Patient(models.Model): patient_first_name = models.CharField(max_length=50) patient_last_name = models.CharField(max_length=50) patient_name = models.CharField(max_length=100) patient_email = models.EmailField(max_length=100) gender = models.CharField(max_length=50) class PatientMedicalRecord(models.Model): patient = models.ForeignKey(PatientTable) mrn = models.CharField(max_length=50, unique=True) patient_height = models.IntegerField(blank=True, null=True) patient_weight = models.IntegerField(blank=True, null=True) age_risk = models.BooleanField(default=False) I want to query on patient table for getting all the patient. also i need MRN column value from PatientMedicalRecord table which contain record for particular patient if exists. How can i do this with djnago ORM? -
Django Queryset annotate based on unique value
I am trying to write a queryset operation that transforms the first table into the second table as efficiently as possible This is the criteria: For each name, how many unique schools are affiliated with it? Also, the exact names and schools are unknown beforehand. Name School John USC John USC John UCLA Adam UCSD Adam USC Name num_unique_schools John 2 Adam 2 -
rename the get_field_display in django serializer
i am trying to use the get_field_display function in Django in my serializer but I want to rename it to something else(consider it worker_role). what should I do? class AdminUnsubscriberListSerializer(serializers.ModelSerializer): worker_role= "get_role_display" . . . -
Why doesn't my html file get my javascript file. load static
here is my settings.py: STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIR = [STATIC_DIR] here is the end of my html page: {% load static %} <script src="{% static '/js/script.js' %}" type="text/javascript"></script> </html> {% endblock %} I have a folder static and inside it, there are two more folders one is js and the other is css. But when I try to load it, it always says "GET /static/js/script.js HTTP/1.1" 404 1795 I have tried many things but it does not work. Someone please help. -
loop or any other function in django for below mentioned project
Models: class ddlname(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField(default='00:00') endate=models.DateField() status=models.ForeignKey(status,on_delete=models.CASCADE,default='Yet To Assign') def __str__(self): return self.name Forms: from dataclasses import fields from django import forms from .models import ddlname class nameform(forms.ModelForm): class Meta: model=ddlname fields='__all__' Views: def home(request): if request.method=='GET': form=nameform() return render(request,'home.html',{'form':form}) else: form=nameform(request.POST) if form.is_valid(): form.save() return redirect('/details') def details(request): context={'details':ddlname.objects.all().order_by('stdate','sttime')} return render(request,'details.html',context) home template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="#" method="post"> {% csrf_token %} {{form}} <button type="submit">submit</button> </form> </body> </html> details template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <table> <thead> <tr> <td>Name</td> <td>St Date</td> <td>St Time</td> <td>Status</td> </tr> </thead> <tbody> {% for d in details %} <tr> <td>{{d.name}}</td> <td>{{d.stdate}}</td> <td>{{d.sttime}}</td> <td>{{d.endate}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> Requirement: from home template form, I will input stdate as 22-02-2022 and endate as 25-02-2022 along with name(test) sttime(00:00). I should get the output as: test 22-02-2022 00:00 22-02-2022, test 23-02-2022 00:00 23-02-2022, test 24-02-2022 00:00 24-02-2022, test 25-02-2022 00:00 25-02-2022, and get save to DB. The above mentioned code gives the output as test 22-02-2022 00:00 25-02-2022, request anyone to help me on this issues … -
How to do validation using django models in knockout js
knockout.js var ViewModel = function () { var self = this; self.securityKey = ko.observable(""); if self.securityKey == employee_no self.save = function () { var formdata = new FormData(); formdata.append('securityKey', self.securityKey()); $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/api/", data: formdata, headers: {'X-CSRFToken': csrftoken}, processData: false, contentType: false, success: function (){ alert('Done!') }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) models.py from django.db import models from app_user_mngmt.models import UserProfile # Create your models here. class Kiosk(models.Model): securityKey = models.CharField(max_length=5) employee_no = models.OneToOneField( UserProfile, on_delete=models.CASCADE, primary_key=True, default = False, ) views.py @api_view(['POST']) def security_validate(request): serializer = Kioskserialize(data = request.data) return Response(data) html div class="bord-r h-100 card text-center"> <div class="form-group"> <label class="float-left text-white">Enter Last 5 Character</label> <div class="input-group input-group-rounded mb-3"> <input type="text" class="form-control" name="securityKey" data-bind="value: securityKey" id="securityKey" placeholder="" aria-label="" aria-describedby="basic-addon2"> <div class="input-group-append"> <span class="input-group-text bg-white" id="basic-addon2"> <button type="button" class="btn"><i class="ion-ios-arrow-thin-right"></i></button> </span> </div> How to do validation using django models in knockout js I have given html ..In that html security key field is there If i given any code in that security field it should display error what i need is check validation of employ no is equal to given security number how to do validation for django models employee number is … -
Foreignkey get avatar
I am learning how to build a Learning management system and I am having trouble trying to attach a users avatar to any posted comments they make. Any direction/help would be really appreciated. So I have a Profile model and a Comment model and I have added a Foreignkey to the Profile model in my Comment model. How can I get the users avatar from the Profile model and render this in the comments box in HTML? Here are my models: class Comment(models.Model): course = models.ForeignKey(Course, related_name='comments', on_delete=models.CASCADE) user_avatar = models.ForeignKey(Profile, null=True, related_name="comments", on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=100) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True, null=True) occupation = models.CharField(max_length=100, blank=True, null=True) residence = models.CharField(max_length=100, blank=True, null=True) active_id = models.BooleanField(default=True) avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics/',default='uploads/default.jpg') and my views.py: @api_view(['POST']) def add_comment(request, course_slug, lesson_slug, pk): data = request.data name = data.get('name') content = data.get('content') course = Course.objects.get(slug=course_slug) lesson = Lesson.objects.get(slug=lesson_slug) profile = Profile.objects.get(id=pk) comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, user_avatar=request.profile, created_by=request.user) serializer = CommentsSerializer(comment) return Response(serializer.data) serializers.py: class CommentsSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'name', 'content', 'created_at', 'user_avatar', 'created_by') -
The annotation 'item_id' conflicts with a field on the model in Django 3.0
I have updated my project latest versions of python and Django I am getting this error "The annotation 'item_id' conflicts with a field on the model" Here is my views.py selected_pricelist = int(pricelist or request.COOKIES.get('selected_pricelist', 0)) if selected_pricelist: try: item_prices = ItemPrices.objects.filter( item__in=data, client=client, pricelist_id=selected_pricelist) except ItemPrices.DoesNotExist: logger.debug('Item prices not found') selected_pricelist = '' else: data = item_prices.order_by('-item__created_at').annotate( item_id=F('item_id'), item_name=F('item__item_name'),form=F('item__form'), part_number=F('item__part_number'),height=F('item__height'), description=F('item__description'),girth=F('item__girth'), currency=F('pricelist__currency'),long=F('item__long'),pot_size=F('item__pot_size'), lat=F('item__lat'),grading=F('item__grading'),area=F('item__area'), unit_price=F('price'), quantity=F('item__quantity'), supplier=F('item_id__supplier_one__supplier_name'), batch_number=F('item_id__batch_number')).values() Here is my models.py class JobItems(models.Model): item_name = models.CharField(max_length=512) batch_number = models.CharField(max_length=200, blank=True, null=True) .... .... class PriceList(TimeStampedModel): client = models.ForeignKey(Client,on_delete=models.CASCADE) name = models.CharField(max_length=40) currency = models.CharField(max_length=10, choices=CURRENCY_CHOICES, default=CURRENCY_CHOICES[0][0]) class Meta: ordering = ('name', ) unique_together = (('client', 'name'), ) def __str__(self): return self.name class ItemPrices(TimeStampedModel): client = models.ForeignKey(Client,on_delete=models.CASCADE) pricelist = models.ForeignKey(PriceList,on_delete=models.CASCADE) item = models.ForeignKey(JobItems,on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, help_text=_('Price in GBP')) class Meta: unique_together = (('pricelist', 'item'), ) Here is my error traceback Traceback (most recent call last): File "/home/xyz/abc/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/xyz/abc/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/xyz/abc/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/xyz/abc/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/xyz/abc/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/xyz/test/dev-1.8/server/mcam/views.py", line 8238, … -
Datalist tag not working on making changes in HTML file related to Django
I am working on a task where I have to make a drop-down box with search filter. Here:- What is happening here is after selecting Fiscal year, it is displaying Annual work plan for the user according to that (after filtering). But it is displaying the drop down only, what I want is it should display the drop down with a filterbox too. In forms.py, select annual work plan is as follows:- Select_Annual_Work_Plan = forms.ModelChoiceField(queryset=annual_work_plan.objects.none().order_by("Annual_Work_Plan_ID"), label='Select Annual Work Plan', ) -> Its a ModelChoiceField. This is the function in views.py as ajax_load_Select_Annual_Work_Plan, by which we are rendering the html to display the dropdown, function is as follows:- @login_required() def ajax_load_Select_Annual_Work_Plan(request): Fiscal_year_val = request.GET.get("Fiscal_year") Select_Annual_Work_Plan_list = annual_work_plan.objects.filter(Fiscal_year = Fiscal_year_val).order_by("Annual_Work_Plan_ID") return render(request, "procurement_data/Select_Annual_Work_Plan_dropdown_list_options.html", {"Select_Annual_Work_Plan_list": Select_Annual_Work_Plan_list}) Select_Annual_Work_Plan_dropdown_list_options.html file is as follows(This is the complete code of this file):- {% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %} <option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option> {% endfor %} I tried datalist tag of the html, which is basically used for the dropdown with search box but that is not working here as:- <div> <datalist id="suggestions"> {% for Select_Annual_Work_Plan in Select_Annual_Work_Plan_list %} <option value="{{ Select_Annual_Work_Plan.pk }}">{{ Select_Annual_Work_Plan}}</option> {% endfor %} <input autoComplete="on" list="suggestions"/> </datalist> </div> I tried some jQuery solutions … -
dj-rest-auth page not found while clicking on confirmation link
Via Postman I send POST http://127.0.0.1:8000/dj-rest-auth/password/reset/ with json: { "email" : "pyroclastic@protonmail.com" } I received the email with the confirmation link:http://localhost:8000/dj-rest-auth/password/reset/confirm/3/b18epl-d065751bdebfd3abacd0ddd62c419877 However upon clicking on this link it shows Page not found (404) As you can see through my url.py, I tried other ways (including ones in the faq and the api endpoints and config pages and went through the source codes) url.py from django.contrib import admin from dj_rest_auth.registration.views import VerifyEmailView from django.urls import path from django.urls import include, re_path from django.conf.urls.static import static from django.conf import settings from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView from allauth.account.views import ConfirmEmailView from django.views.generic import TemplateView from .router import router from BackendApp.views import P2PListingModule, empty_view, GoogleLogin, FacebookLogin urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('entity/', include(router.urls)), path('enduser/<str:pk>/service/', P2PListingModule.userServiceListing), path('enduser/<str:pk>/request/', P2PListingModule.userRequestListing), path('enduser/<str:pk>/swap/', P2PListingModule.userSwapListing), path('enduser/<str:pk>/premade', P2PListingModule.userPremadeListing), path('entity/p2p_listing/order/', P2PListingModule.placeOrder), path('api/p2plisting/service', P2PListingModule.ServiceListingView.as_view()), path('api/p2plisting/request', P2PListingModule.RequestListingView.as_view()), path('api/p2plisting/swap', P2PListingModule.SwapListingView.as_view()), path('api/p2plisting/premade', P2PListingModule.PremadeListingView.as_view()), re_path(r'^', include('django.contrib.auth.urls')), path('dj-rest-auth/password/reset/', PasswordResetView.as_view(), name="rest_password_reset"), path( "dj-rest-auth/password/reset/confirm/", PasswordResetConfirmView.as_view(), name="rest_password_reset_confirm", ), path( # path('/dj-rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,32})/$', "/dj-rest-auth/password/reset/confirm/<uuid:uidb64>/<slug:token>/", # PasswordResetConfirmView.as_view(), # ConfirmEmailView.as_view(), TemplateView.as_view(template_name="password_reset_confirm.html"), ), path('auth/google/', GoogleLogin.GoogleLoginView.as_view(), name='google_login'), path('auth/facebook/', FacebookLogin.FacebookLoginView.as_view(), name='fb_login'), re_path(r'^accounts/', include('allauth.urls'), name='socialaccount_signup'), # path('dj-rest-auth/account-confirm-email/', ConfirmEmailView.as_view(), name='account_email_verification_sent'), # re_path(r'^password-reset/$', # TemplateView.as_view(template_name="password_reset.html"), # name='password-reset'), # re_path(r'^password-reset/confirm/$', # TemplateView.as_view(template_name="password_reset_confirm.html"), # name='password-reset-confirm'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns = [ # url(r'^admin/', include(admin.site.urls)), # ] + … -
Why not cached when crossing domain?
I write a django project,use minio to save files like css,js. The project run on a:8100,minio run on b:9001. When I open(new open) the page by browser,I get the result: It showed: not cached.(200 http code) But the response has headers(the server want the client to keep cache): And when I click the refresh button.It shows different(the client cached!): It cached? response status code is 304. But if I click by new open(not refresh), the response's http code also is 200,which shows not cached. And the another page,like the situation above(but the image more large,about 5-7 Mb),not cached,both click refresh and new open page. Could anyone tell anything about the cache when crossing domain? I hope the staticfile could use local cache when crossing domain >..< -
how to use pagination in ListView in django using get_paginate methed
class ManageStudentView(ListView): model = Student template_name = 'student/manage_student.html' def get_context_data(self, **kwargs): kwargs = super(ManageStudentView, self).get_context_data(**kwargs) kwargs['student'] = User.objects.filter(user_type=STUDENT) return kwargs def get_queryset(self): search_query = self.request.GET.get("student", None) if search_query != None: return Student.objects.filter(name__contains=search_query) return Student.objects.all() def get_paginate_by(self, queryset): self.paginate_by = settings.PAGINATION_NUMBER return self.paginate_by -
how to join multiple table sum in single query with foreign key Django ORM
Here i giving table Structure: class MainTable(models.Model): code = models.CharField(max_length=25) qty = models.FloatField(default=0) class Table1(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_one') date = models.DateField() qty = models.FloatField(default=0) class Table2(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_two') date = models.DateField() qty = models.FloatField(default=0) class Table3(models.Model): code = models.ForeignKey(MainTable, on_delete=models.CASCADE, related_name='table_three') date = models.DateField() qty = models.FloatField(default=0) I want this type of table: ________________________________________________________ | Code | qty | table1_sum| table2_sum | table3_sum | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | --------------------------------------------------------- |code1 | 5000 | 2000 | 3000 | 4000 | -------------------------------------------------------- I am traying this query but it does not give proper value: query = MainTable.objects.all().annotate(table1=(Sum('table_one__qty')),table12=(Sum('table_two__qty')),table3=(Sum('table_three__qty'))) In this query, table one gives the actual value but the other table gives the wrong value. need proper query. -
Direct assignment to the reverse side of a related set is prohibited in custom Django query
So I'm trying to use the Django ORM in a non-standard way - I want to get relationships with related tables, but I am trying to do via a raw query - mostly because I need to use ORDER BY RAND() rather than the standard Django random query method, because it's substantially slower. So I have this query: base_sql = "SELECT article_sentence.id, article_sentence.language_id, article_sentence.per_language_id, rule_mapping_sentence.rule FROM article_sentence " join_sql = "JOIN rule_mapping_sentence ON (article_sentence.id = rule_mapping_sentence.sentence_id) " where_sql = "WHERE article_sentence.id IN " subquery_sql = "(SELECT sentence_id FROM rule_mapping_sentence GROUP BY sentence_id HAVING COUNT(*) >= 0) " order_sql = "ORDER BY RAND() " limit = "LIMIT " + str(number) query = base_sql + join_sql + where_sql + subquery_sql + order_sql + limit sentences = models.Sentence.objects.raw(query) However I get: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use rule.set() instead. This seems to be due to the way that my models are related. Here's my sentence model: class Sentence(models.Model): sentence = JSONField(default=dict, null=True, ) json = JSONField(default=dict, null=True, ) per_language = models.ForeignKey( PerLanguage, on_delete=models.CASCADE, null=True, related_name="sentence" ) language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True) Here's my Rules model: class Rules(models.Model): rule = models.CharField(max_length=50) function = models.CharField(max_length=50) definition = … -
Django - models.ForeignKey Giving error that mentions class is not defined
I am developing a Student management system in django and while making it I got this class Dept(models.Model): id = models.CharField(primary_key='True', max_length=100) name = models.CharField(max_length=200) def __str__(self): return self.name class Course(models.Model): dept = models.ForeignKey(Dept, on_delete=models.CASCADE) id = models.CharField(primary_key='True', max_length=50) name = models.CharField(max_length=50) shortname = models.CharField(max_length=50, default='X') def __str__(self): return self.name and while doing make migrations I get this error by what means Can I get this right and how can I tackle this error (studentmanagementsystem) C:\Users\harsh\dev\student management\student_management>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\harsh\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\harsh\anaconda3\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\harsh\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 10, in <module> class Dept(models.Model): File "C:\Users\harsh\dev\student management\student_management\student_app\models.py", line 18, in Dept class Course(models.Model): File "C:\Users\harsh\dev\student … -
Django Model default field overridden by seriliazer
I set my default value of publish to True in the model, but after creating a new entry in the EntrySerializer it saves as False. I can manually correct this by overriding the create() method in the serializer, but I'm wondering it there's a more elegant way. class EntrySerializer(serializers.ModelSerializer): class Meta: model = Entry fields = '__all__' read_only_fields = ['code', 'author', 'slug', 'created', 'modified'] My model class Entry(models.Model): slug = models.SlugField(max_length=255) title = models.CharField(max_length=200) description = models.TextField() publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) media = models.TextField(validators=[URLValidator()], null=True, blank=True) def save(self, *args, **kwargs): if not self.id: slug_str = "%s %s" % ( uuid4().hex[:6].upper(), self.title) self.slug = slugify(slug_str) super(Entry, self).save(*args, **kwargs) Results of post request { "id": 9, "slug": "f4eabc-new-test", "title": "new test", "description": "dsfsdfs", "publish": false, "created": "2022-02-22T03:12:52.479158Z", "modified": "2022-02-22T03:12:52.479190Z", "media": null, "author": 1 } -
Define mysql command line args in Django DATABASES settings
When using mysql with Django, the presence of .my.cnf causes this: $ python manage.py dbshell ERROR 1045 (28000): Access denied for user 'foo'@'localhost' (using password: YES) CommandError: "mysql --user=foo --host=localhost --default-character-set=utf8mb4 quxdb" returned non-zero exit status 1. I'd like to keep my my.cnf and be able to use dbshell, etc. Is there a way to set --no-defaults or other mysql command line args in DATABASES in settings.py? -
Django Forbidden (CSRF cookie not set.): / POST / HTTP/1.1" 403 2864 on Google Colab
so i'm tryin to run my Django web program on Google collab based on this tutorial https://medium.com/@arsindoliya/running-django-on-google-colab-ea9392cdee86 And i did it the web can running! running web But, if i want to make POST it's always error like this Forbidden (CSRF cookie not set.): / [22/Feb/2022 02:13:47] "POST / HTTP/1.1" 403 2864 And i'm already try some solution like put the CSRF_COOKIE_SECURE = True inside my settings.py but still not working and i do put the @csrf_token on my form too and it's still not working. Also i wanna try this solution to from django.views.decorators.csrf import csrf_exempt but i'm still don't understand how to use that. Does anyone has a solution for it? I'm still new in Django and i made it for my college's final project, so any solution that you guys make really helpful for me. Thank you -
Problem linking CSS file to HTML file using Django
I had some issues linking a CSS file to HTML file while using Django. Here is my HTML file where I linked a static file name home.css {% load static %} <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> My folder is organised as so for my templates folder: \Users\me\Desktop\mysite\templates\base\home.html And for my static folder: \Users\me\Desktop\mysite\static\home.css Doesn't someone know from where does the problem come? -
My website template is aligned to the left side
My code is exceeding the word limit so you can see the code here. This is my template and when I run the server locally, the webpage is kinda aggined to the left side like this. But in fact, it should look like this.. I set the static directory in the settings.py as STATIC_DIRS = (os.path.join(BASE_DIR, "static"),) and I loaded the static on the top of the page as shown. Can't figure out the problem. -
How to apply split function to a specific field in Django's queryset
I am using Django and groupby based on the 'teacher' field. However, there are two or three values in the 'teacher' field as well as one, so I want to split it. However, I get an error saying that 'F' object has no attribute 'split'. If you have any other workaround, please help me! [views.py] counts = Research.objects.values(F('teacher').split('/'))\ .annotate(count=Count('id', distinct=True))\ .values('teacher', 'count') teacher subject Helen math Adam/Jennie science Jennie music The result I want to get is: <Queryset: [{teacher:'Helen', count:'1'}, {teacher:'Adam', count:1}, {teacher:'Jennie', count:2}]> -
403 Forbidden when using Django's PermissionRequiredMixin
I'm trying to restrict access to the view 'GovernmentView' to users whose account has True on the field 'is_government' by implementing the PermissionRequiredMixin argument. But it's not working. Registered users who have True for the field 'is_government' are getting the 403 Forbidden error (and Superusers who have False on that field do not see the error and can access the template). How can I fix this error and restrict access as stated above? Thanks. settings.py: LOGIN_URL = reverse_lazy('users:login') LOGIN_REDIRECT_URL = 'users:home' urls.py: app_name = 'users' urlpatterns = [ path('', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('activate-user//', views.activate_user, name='activate'), path('home/', views.home, name='home'), path('government/', views.GovernmentView.as_view(), name='government'), models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_active = models.BooleanField(default=True) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_government = models.BooleanField(default=False, verbose_name="Gov't Official") date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email @staticmethod def get_absolute_url(self): return reverse("users:home") views.py: class GovernmentView(PermissionRequiredMixin, ListView): permission_required = 'CustomUser.is_government' template_name = 'users/government.html' model = List form_class = Form def get_context_data(self, **kwargs): context = super().get_context_data() context["List"] = List.objects.all() return context government.html: {% if request.user.is_government%} <div class="nav"> <a id="government" {% block government %} class="selected" {% endblock %} href="{% url 'users:government' %}"></a> </div> {% endif … -
in this django code when i post some text saveed in the table betwen (' my text i post ',)
view def Apply2 (request): if request.method=="POST": q1 = order.objects.last() if q1 is not None: q1.Course_Selection = request.POST["1221"], q1.save() response = redirect('/apply3') return response return render(request,'Apply_Now2.html') -
Django with aurora, how to use two instances?
I have django script with mysql My settings is below. mysql server is in the local. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": 127.0.0.1, "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } } Now I want to use amazon AURORA It has two instances reader/writer How can I set the instance to django??