Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return Queryset using Annotate and SUM in Django ORM?
I'm setting a new ViewSet using Django Rest Framework. And I want to return values from the database using Annotate and Sum with Django ORM (Or raw query). Trade.objects.value('company_id', 'fund_id', 'buy_sell').annotate(quantity=Sum('quantity')) How to be able to return queryset using them? This is just an variation of Trade.objects.all() I also tried using raw query: Trade.objects.raw("""SELECT `id`, `fund_id`, `company_id`, `buy_sell`, SUM(`quantity`) AS `quantity` FROM `operations_trade` GROUP BY `fund_id`, `company_id`, `buy_sell`""") No success. This is my serializer: class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = '__all__' The Model: class Trade(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) is_directional = models.BooleanField(default=True) fund = models.ForeignKey('Fund', on_delete=models.CASCADE) broker = models.ForeignKey('Broker', on_delete=models.CASCADE) currency = models.ForeignKey('Currency', on_delete=models.CASCADE) buy_sell = models.CharField(max_length=1) quantity = models.IntegerField() unity_price = models.FloatField() commission = models.FloatField() foreign_exchange = models.FloatField() date = models.DateField() settlement = models.DateField() And my View: class TradeViewSet(viewsets.ModelViewSet): serializer_class = TradeSerializer queryset = Trade.objects.all() def get_queryset(self): queryset = Trade.objects.all() filtrated = self.request.query_params.get('filtrated', None) if filtrated is not None: queryset = Trade.objects.values('company_id', 'fund_id', 'buy_sell').annotate(quantity=Sum('quantity')).order_by('fund_id') # queryset = Trade.objects.raw("SELECT `id`, `fund_id`, `company_id`, `buy_sell`, SUM(`quantity`) AS `quantity` FROM `operations_trade` GROUP BY `fund_id`, `company_id`, `buy_sell`") return queryset I expect the output of queryset as an dict/object to use on the client side. When not returning, but printing the queryset … -
How to create an event when submitting a specific buttom within a list
I have a list of different servers. So when clicking on the button "connect", I want to connect to that specific server. How can I pick the right button with jQuery? Thank you in advance! {% for server in servers%} {%if server.credential.user == user%} {%if server.credential.protocol == 'vnc'%} <a> <div class="p-l-20" id="server_details"> <h4>{{server.name}}</h4> <h6>Hostname: {{server.hostname}}</h6> <h6>IP Address: {{server.ip}}</h6> <h6>Protocol: {{server.credential.protocol|upper}}</h6> <h6>User: {{server.credential.user}}</h6> <button type="button" >Connect</button> </div> </a> {%endif%} {%endif%} {%endfor%} -
Can execute PostgreSql query in django
I am trying to execute PostgreSQL query in Djnago but I have some problems. I would like to execute this query: SELECT * FROM data_affectedproductversion WHERE vendor_name LIKE 'cisco' AND product_name LIKE 'adaptive%security%appliance%' AND version='9.1(7)16' It works if I execute it in pgAdmin query editor, but when I try to execute it with django it does not work. I tried something like this: results = AffectedProductVersion.objects.raw("SELECT * FROM data_affectedproductversion WHERE vendor_name LIKE 'cisco' AND product_name LIKE 'adaptive%security%appliance%software' AND version='9.1(7)16';") for result in results: print(result) This is the traceback Traceback (most recent call last): File "<console>", line 1, in <module> File "venv\lib\site-packages\django\db\models\query.py", line 1339, in __iter__ self._fetch_all() File "venv\lib\site-packages\django\db\models\query.py", line 1326, in _fetch_all self._result_cache = list(self.iterator()) File "venv\lib\site-packages\django\db\models\query.py", line 1349, in iterator query = iter(self.query) File "venv\lib\site-packages\django\db\models\sql\query.py", line 96, in __iter__ self._execute_query() File "venv\lib\site-packages\django\db\models\sql\query.py", line 130, in _execute_query self.cursor.execute(self.sql, params) File "venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) IndexError: tuple index out of range Any idea what I am doing wrong and how can I transform this PostgreSQL query … -
Different URL request than expected
I have a question about ajax url for comment delete problem is this Expected URL: delete_comment_ajax/223 Executed URL: /todo/31/delete_comment_ajax/223 It's probably because I originally went to the detail page and then sent the request. If you know how to fix it, please let me know. $(".comment_delete_button").click(function(e) { e.preventDefault(); var id = $(this).attr("id"); alert('삭제 id : ' + id); $.ajax({ type: "POST", url: 'delete_comment_ajax/' + id, data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { $("#comment_table_" + id).remove(); alert('comment 삭제 complete '); } }); }); -
LoginForm produces unknown validation error in Django
I have created a Login and Register Model form. Register form is working fine but when I submit Login form it shows a validation error "User with this Email already exists" which I did not define. Instead of redirecting to success url, the page just reloads with the validation error. Any suggestion would be welcome. forms.py class LoginForm(forms.ModelForm): email = forms.EmailField(max_length=100, widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Email"}), required=True) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Password", 'name':"login_password"}), required=True) class Meta: model = CustomUser fields = ('email','password',) Views.py class LoginView(FormView): model = CustomUser form_class = LoginForm success_url = reverse_lazy('first_app:home') template_name = 'login.html' def form_valid(self, form): print('Inside form_valid of LoginView') email = form.cleaned_data.get('login_email') passw = form.cleaned_data.get('login_password') print('1') user = authenticate(username=email,password=passw) print('2') login_auth(self.request,user) messages.success(self.request,'Logged in successfully') return redirect('first_app:home') Template <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} <h2 class="text-center">Sign In</h2> {% for error in form.email.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> {{ error }} </div> {% endfor %} <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> {{ form.email }} </div> </div> {% for error in form.password.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> {{ error }} </div> {% endfor %} <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="padding-right: 15px;padding-left: 16px"><i class="fa fa-lock"></i></span> {{ form.password }} </div> </div> <div … -
Django SearchRank annotation not being assigned, bug in production but not dev
My Django application (Apache/WSGI with Postgres backend) is running into an error in production which I can't reproduce in dev or by using the Django shell on the production machine. How can I debug this? The application has a Story model class Story(models.Model): title = models.CharField(max_length=400) content = models.TextField(blank=True) quality = models.FloatField(default=0) search = SearchVectorField(null=True) with a signal to populate search on save: @receiver(post_save, sender=Story) def update_search_vector(sender, instance, **kwargs): Story.objects.filter(pk=instance.pk).update(search=SearchVector('title', 'content')) When a user searches, I want to return relevant and high-quality results. I assign score as the harmonic mean of these two values: query = SearchQuery(form.cleaned_data['query']) stories = stories.annotate( rank=SearchRank(F('search'), query), score=F('rank') * F('quality') / (F('rank') + F('quality')) ).filter(rank__gte=SEARCH_RANK_CUTOFF).order_by('-score') This works fine in dev and on the Django shell in production. But when executed via the running app, the following error is raised: django.core.exceptions.FieldError: Cannot resolve keyword 'rank' into field. I'm having trouble figuring out how to debug this. Could it be some kind of erroneous queryset caching? -
How to access data from another model using same foreign key?
I want get college data using general_info foreign key. without making nested serializer of college_set in GeneralInfo serializer. Is there any alternative in django rest framework or is not possible? I have tried above below line of code but its not working. is there any other way? college = serializers.CharField(source='general_info.college_set', read_only=True) models.py from django.db import models class GeneralInfo(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) address = models.CharField(max_length=30) class Student(models.Model): general_info = models.ForeignKey(to=GeneralInfo, on_delete=models.PROTECT) course = models.CharField(max_length=30) marks = models.CharField(max_length=30) class College(models.Model): general_info = models.OneToOneField(to=GeneralInfo, on_delete=models.PROTECT) name = models.CharField(max_length=30) address = models.CharField(max_length=30) serializer.py from rest_framework import serializers class MySerializer(serializers.ModelSerializer): name = serializers.CharField(source='general_info.first_name', read_only=True) college = serializers.CharField(source='general_info.college_set', read_only=True) class Meta: model = Student fields = ('name', 'college') -
Cannot connect django with mysql database
I am trying to connect django with mysql database eventhough i have a database name crudapp which i have created it gives me this error whenever i run python manage.py runserver it says unknown database crudapp, Any help would be appreciated thanks.... The error i got: C:\Users\User\Desktop\crudapplication>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wra at 0x027516A8> Traceback (most recent call last): File "D:\python\New folder\lib\site-packages\django\db\backends\base\base. line 216, in ensure_connection self.connect() File "D:\python\New folder\lib\site-packages\django\db\backends\base\base. line 194, in connect self.connection = self.get_new_connection(conn_params) File "D:\python\New folder\lib\site-packages\django\db\backends\mysql\base , line 227, in get_new_connection return Database.connect(**conn_params) File "D:\python\New folder\lib\site-packages\MySQLdb\__init__.py", line 84 Connect return Connection(*args, **kwargs) File "D:\python\New folder\lib\site-packages\MySQLdb\connections.py", line , in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1049, "Unknown database 'crudapp'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\python\New folder\lib\site-packages\django\utils\autoreload.py", 225, in wrapper fn(*args, **kwargs) File "D:\python\New folder\lib\site-packages\django\core\management\comman unserver.py", line 120, in inner_run self.check_migrations() File "D:\python\New folder\lib\site-packages\MySQLdb\connections.py", line , in __init__ super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (1049, "Unknown database 'crudapp'") settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'crudapp', 'USER': 'root', 'PASSWORD': 'warnaa', 'HOST': 'localhost', 'PORT': '3307', } } -
anchor tag in django template not working
In my django project, inside one of my templates, no anchor tag is working. here is my code of template: layer_details.html When I click on any anchor, the url is showing in the browser but not redirecting to that link. -
Edit - __init__() got an unexpected keyword argument 'instance'
I am trying to create "Edit" for my form. urls.py url(r'^app_1/(?P<id>[-\w]+)/edit/$',views.edit, name = 'edit'), forms.py class Forma(forms.Form): naslov = forms.CharField(label='naslov') datumObjave = forms.DateField(label='datumObjave') autor = forms.CharField(label='autor') email = forms.EmailField(label='email') models.py class Clanak(models.Model): naslov = models.CharField(null=False, blank=True, max_length=120) datumObjave = models.DateField(null=False, blank=False) autor = models.CharField(null=False, blank=True, max_length=50) email = models.EmailField(max_length=75, null=True, blank=True) def __str__(self): return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) views.py def edit(request, id): data = get_object_or_404(Clanak, id = id) if request.method == "POST": form = Forma(request.Clanak, instance=data) if form.is_vaild(): data = form.save(commit=False) data.naslov = request.user data.datumObjave = request.user data.autor = request.user data.email = request.user return redirect('readAllNew') else: form = Forma(instance=data) template = 'readAllNew.html' context = {'form': form} return render(request, template, context) readAllNew.html {% for x in data %} <tr> <td>{{x.naslov}}</td> <td>{{x.datumObjave}}</td> <td>{{x.autor}}</td> <td>{{x.email}}</td> <td><a href="{% url 'delete' x.id %}">delete</a></td> <td><a href="{% url 'edit' x.id %}">edit</a></td> </tr> {% endfor %} So when I hit edit link at my "readAllNew.html" I get error: TypeError at /app_1/5/edit/ init() got an unexpected keyword argument 'instance' I think something is wrong with my view but I am not sure what. -
Failure On Deploying Django On Docker
Docker tree file structures tree -L 3 . ├── banax_api │ ├── activities │ │ ├── admin.py │ │ ├── api_views.py │ │ ├── apps.py │ │ ├── enums.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── serializers │ │ ├── tests.py │ │ └── urls │ ├── api │ │ ├── api_views.py │ │ ├── apps.py │ │ ├── exceptions.py │ │ ├── filter.py │ │ ├── __init__.py │ │ ├── jwt │ │ ├── management │ │ ├── migrations │ │ ├── pagination.py │ │ ├── permission_classes │ │ ├── __pycache__ │ │ ├── renderers │ │ ├── router.py │ │ ├── tests.py │ │ └── ViewClasses │ ├── banax_platform │ │ ├── database_routers │ │ ├── email │ │ ├── enums.py │ │ ├── helper_functions.py │ │ ├── __init__.py │ │ ├── local_settings.py │ │ ├── local_settings.py.sample │ │ ├── mollie │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── social │ │ ├── third_party_apps_settings.py │ │ ├── urls.py │ │ ├── utils │ │ └── wsgi.py ├── banax_platform.conf ├── docker-compose.yml ├── Dockerfile ├── gunicorn.service └── requirements.txt Dockerfile: FROM python ENV PYTHONUNBUFFERED 1 COPY … -
DRF and Token authentication with safe-deleted users?
I'm using a Django package named django-safedelete that allows to delete users without removing them from the database. Basically, it adds a delete attribute to the model, and the default queries like User.objects.all() won't return the deleted models. This works as expected, except in one case. I'm using Token Authentication for my users with Django Rest Framework 3.9, and in my DRF views, I'm using the built-in permission IsAuthenticated. Here is the code : class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_authenticated) The problem When a user is soft deleted, he's still able to authenticate using its token. I'm expecting the user to have a 401 Unauthorized error when he's soft deleted. What's wrong? -
How to implement to do tasks by schedule?
I have django-project with some tasks, which are saved in db. I need that tasks are executed in certain time. I thiink about cron or celery, but I see only function like repeated actions, but I need to do in time which is saved in my db. How can I do this? -
getting a number instead of field name when i use want distinct values with its count
I am very new to Django I have table Category which contains category class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category class Meta: verbose_name_plural = "categories" and also table "Post" which uses "Category" table as foreign key class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE ) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) but using below query what i get is Post.objects.values('category').order_by('category').annotate(the_count=Count('category')) result <QuerySet [{'category': 2, 'the_count': 5}, {'category': 3, 'the_count': 4}]> what i want is <QuerySet [{'category': "fashion", 'the_count': 5}, {'category': "travel", 'the_count': 4}]> how do i fix this problem Thanks in advance! -
Django get model from serializer class from view
I'm using Django 2.x and Django REST Framework I have a serializer like class DestroyAccountSerializer(serializers.ModelSerializer): class Meta: model: User and view class DeleteAccountView(generics.DestroyAPIView): serializer_class = DestroyAccountSerializer permission_classes = (IsAuthenticated,) def get_object(self): # return self.get_serializer().Meta.model.objects.get(pk=self.request.user.pk) return self.request.user I want to use the model defined in the view which is defined in the serializer. I tried with self.get_serializer().Meta.model But this gives an error Meta has no attribute model How to get model being used by the serializer class in the view? -
Invalid form when uploading file in Django
I need to upload file on a Django page, however, after following the official tutorial, I was not able to upload it, it always gives the error "invalid form", and when I tried to print out the error msg of the form, it says "This field is required". One thing notable is: I have 2 forms on one page, one is this upload form and the other one is for filling out information. Not sure if this is the root cause. I have tried all solutions provided on the Internet. Template file: <form id="uploadForm" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" value="upload" name="sourcefile"> <button type="submit">Upload</button> </form> Forms.py: from django import forms from .models import SourceFile class UploadFileForm(forms.ModelForm): class Meta: model = SourceFile fields = ('file', 'title') Models.py: from django.db import models # Create your models here. class SourceFile(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField(upload_to="media/") Views.py def model_form_upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = SourceFile(file_field=request.FILES['file']) instance.save() return JsonResponse({'error': False, 'message': 'Uploaded Successfully!'}) else: print("Invalid form") # return JsonResponse({'error': True, 'errors': form.errors}) else: form = UploadFileForm() return render(request, 'source_validation.html', {'form': form}) -
written a Cron job in django, and using it from __init__.py file of my project thus it runs two times, How to solve it?
I'm new to django and i got a task to do that is to schedule a job, such that 1} The job should start running only when I type pyhton manage.py runserver and 2}Should stop when I stop the server, the probelm is that i have achieved 1st part but when i type python manage.py runserver the command which i want to put in crontab gets runs 2 times and creates 2 entries thus the job runs twice and also 2} part of the task is still pending, please help me out with this, as I'm a beginner please pardon for my coding errors.. I had tired the crontab package in django and also background tasks in django but the problem is i'm not able to prefectly set it up and running. # /home/smartify/Desktop/website/music/__init__.py from music.cronjobs import croncode # /home/smartify/Desktop/website/music/cronjobs/croncode.py from crontab import CronTab import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") django.setup() my_cron = CronTab(user='smartify') print('cron ran..') job = my_cron.new(command='python /home/smartify/Desktop/website/music/cronjobs/writedate.py',comment='dateInfo') print('cron command ran') job.minute.every(1) my_cron.write()` in the same folder as cron jobs i have my python script i want to run import datetime with open('/home/smartify/datetetetteet/dateInfo.txt', 'a') as outFile: outFile.write('\n' + str(datetime.datetime.now()) + ' Hello World') -
request.is_ajax() returns FALSE in Django. Cant find out why
I am trying to implement AJAX functional in my project, as a test, to get a first grip with technology . I have following view: class ContactAjax(View): form_class = ContactForm template_name = "testapp/contact.html" def get(self, *args, **kwargs): form = self.form_class() return render(self.request, self.template_name, {"contactForm": form}) def post(self, *args, **kwargs): if self.request.method == "POST" and self.request.is_ajax(): form = self.form_class(self.request.POST) form.save() return JsonResponse({"success": True}, status=200) else: if self.request.is_ajax(): return JsonResponse({"NO success": " ajax"}, status=400, safe=False) else: return JsonResponse({"NO success": "no ajax"}, status=400, safe=False) All works except self.request.is_ajax(): always returns False. I have read here Django request.is_ajax returning false , that HTTP_X_REQUESTED_WITH should be present in the header. I have checked it with whiteshark and it seems like it is not in there (logs are at the end of the main text). I kind of have almost zero knowledge in JS and I expect that I messed up with the script itself and I dont have HTTP_X_REQUESTED_WITH because of that. Could you please checked it and say if it wrong or not and whether I dont receive HTTP_X_REQUESTED_WITH becouse of the script or becouse of something else or becouse I do it completely wrong way perhsps? <!-- templates/testapp/contact.html --> {% extends "base.html" %} … -
how to get 'NOT crashed image file' from Unity to Django?
I'm using Unity 2018.3. and try to HTTP POST Request with image from Unity to Django. try to take a picture in Unity and then POST the image to Django server. I want to receive in server and make it to image file. well, when i send for image file to byte[] using EncodeToPNG() or EncodeToJPG(), the server got it but when i print it the data it was crash seems like encoding error. so it can't write to image format. (the take a picture code is working right.) Django server result image i saw a bunch of things about this issue so i tried to other way like use WWWform or JSON but anything couldn't works.. how to get image form Unity to Django? All help appreciated! Thanks, all. take a picture void TakeSnapshot() { Texture2D snap = new Texture2D(frontCam.width, frontCam.height); snap.SetPixels(frontCam.GetPixels()); snap.Apply(); _SavePath = pathForDocumentsFile("photo"); System.IO.File.WriteAllBytes(_SavePath + ".png", snap.EncodeToPNG()); bytes = snap.EncodeToPNG(); //bytes = snap.EncodeToJPG(); UnityEngine.Object.Destroy(snap); path = _SavePath + ".png"; StartCoroutine(ServerThrows()); } POST to server IEnumerator ServerThrows() { List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("photo", bytes, "byte[]")); //UnityWebRequest www = UnityWebRequest.Post(url, null, bytes); UnityWebRequest www = UnityWebRequest.Post(url, formData); www.chunkedTransfer = false; yield return www.SendWebRequest(); if (www.isNetworkError || … -
How to run python code in string format in django views?
I build a platform on django for run python scripts. user write their python script on textarea and after click on button it should run on back-end and check testcases from database(like hackerrank). I have tried with eval() function but the problem is when user write input() in his/her code it should take the values from database for input. If anyone know how to solve this problem please help me out... -
Django Email template and object move
I have made a view that sends email through a template to an email address. I want to send the name of the user, who originally created the request but I am unable to wrap my head around it, because it's FK. I've tried running it through a for loop and creating objects but that just prints the entirety of the data. Views.py def accept_leave(request): #accept email all_item = Leave.objects.all() context ={'all_item':all_item } subject = "Leave Accepted"#email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = ['talhamurtaza@clickmail.info'] # email to with open("C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.txt", 'rb') as f: msgbody = f.read() msg = EmailMultiAlternatives( subject=subject, body=msgbody, from_email=email_from,to=to_email) html_template = get_template( "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/accept_email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() return render(request, 'projectfiles/email.html', context) def reject_leave(request): #reject email all_item = Employee.objects.all() context = {'name': request.user} subject = "Leave Rejected" # email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = ['talhamurtaza@clickmail.info'] # email to with open( "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.txt", 'rb') as f: msgbody = f.read() msg = EmailMultiAlternatives( subject=subject, body=msgbody, from_email=email_from, to=to_email) html_template = get_template( "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() return render(request, 'projectfiles/rejectemail.html',context) models.py class Employee(models.Model): employee_name = models.OneToOneField(User, on_delete = models.CASCADE) employee_designation = models.CharField(max_length = 10) employee_department = models.CharField(max_length = 35) def __str__(self): … -
Styling django MultiSelectField
I used the django MultiSelectField to create a form to have multiple select options. class Profile(models.Model): cat_choices = ( ('Internships', 'Internships'), ('Scholarships', 'Scholarships'), ('EntranceExams', 'EntranceExams'), ) category=MultiSelectField(choices=cat_choices,default='none') I created a form called profile_form with the category field. In html, I wanted my form to appear with an image on the top and just a check button below the image, with the check button refering to each cat_choices in the category. Something like this In the image I used html to display it. profile.html <!DOCTYPE html> <html> <body> <style> div.item { vertical-align: top; display: inline-block; margin-right: 50px; text-align: center; width: 120px; } img { background-color: grey; } .caption { display: block; } </style> <div class="item"> <img src="internship.png"> <span class="caption"><input type="checkbox" name="Internship" value="Internship"></span> </div> <div class="item"> <img src="jobs.png"> <span class="caption"><input type="checkbox" name="Jobs" value="Jobs"></span> </div> <div class="item"> <img src="scholarship.png"> <span class="caption"><input type="checkbox" name="Scholarship" value="Scholarship"></span> </body> </html> How do I write this html page in django such that each check button referin to each choice appears below the image. -
Django get client user name when access webAPI hosted in IIS from client browser
We have a django restful api to save data in SQL Database. This API is hosted in IIS and consumed by Angular application. How to get client user name who browsed it from local machine? There is no user model available in database. -
Submit button are not submitting form as i have 2 buttons with ajax requests
I have a form with it is own submit button and there is a button inside that form that has the attributes type=button, onclick=somefunction().. the button with the onclick runs great but the other button is not submitting at all. I've made sure that the button with the function on click have type=button and other button have type=submit Here is my code: {% extends 'base/base.html' %} {% block content %} <!-- Page Content --> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <!-- page content --> <br><br> <h3>إنشاء فاتورة بيع جديدة </h3> <br><br> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <form method='post' autocomplete="off" action="."> {% csrf_token %} <div class="autocomplete" style="width:100%"> <b>هاتف العميل </b><br> {{ create_sell_invoice.client }} <br> <p style="display: none;" id="shown_name"> client name </p> <div id="add_new_client" style="margin:25px;padding: 25px;display: none;"> <form method='POST'> {% csrf_token %} <small style="color:rebeccapurple;">يمكنك إضافة عميل جديد برقم هاتف جديد</small> <br><br> <b>إسم الطالب</b> {{ add_client_from_invoice_form.student_name }} <br><br> <b>ولى الامر</b> {{ add_client_from_invoice_form.parent_name }} <br><br> <b>العنوان</b> {{ add_client_from_invoice_form.address }} <br><br> <b>الهاتف</b> {{ add_client_from_invoice_form.phone1 }} <br><br> <b>المستوى</b> {{ add_client_from_invoice_form.level }} <br><Br> <button type="button" class="btn btn-success form-control" onclick="sendingRequest()"> إضافة </button> </form> … -
Django (CSRF token missing or incorrect) suppress logging
In our webapplication it's pretty common that users accidentally open the login page in multiple tabs and trigger the "CSRF token missing or incorrect" error in Django. I would like to suppress this specific message in our logging, because it generates a lot of noise and the issue isn't really fixable. On the other hand, any other issue in the login process should be logged, so I would not want to exclude a whole Django app or class from logging. Do you have any suggestions on how to suppress this specific common error message?