Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Augmented Reality video developed using unity in Django (python)?
I created an Augmented reality video using unity. I want to use that video to write backend in django(python). Can anyone tell me how to import AR video developed in Unity to Django framework ? -
How can i run a project after clonning from github?
I want to run a specific project after downloading it from Github. I read all the instructions also but i didn't understand how to run it with my existing interpreter. I have installed all the required packages also. Please help someone and please don't flag my comment as useless. Django Job Portal -
How to change/mark a color of the roads in map? (FYI: I'm using Django framework)
Please help I'm using Django as a framework. It will be more helpful if we mark according to longitude and Latitude. -
Django: Attribute error 'Signage' object has no attribute subscription_id?
I have the following model: class Signage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) subscription_plan = models.CharField('subscription_plan', default='', blank=True, max_length=255) subscription_id = models.TextField('subscription_id', default='', blank=True) transaction_id = models.TextField('transaction_id', default='', blank=True) def __str__(self): return self.id Here is the serializer: class SignageSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Signage fields = ('id', 'user', 'subscription_plan', 'subscription_id', 'transaction_id') read_only_fields = ('id', ) class CreateSignageSerializer(serializers.ModelSerializer): def create(self, validated_data): signage = Signage.objects.create(**validated_data) return signage def update(self, instance, validated_data): instance.subscription_plan = validated_data.get('subscription_plan', instance.subscription_plan) instance.subscription_id = validated_data.get('subscription_id', instance.susbcription_id) instance.transaction_id = validated_data.get('transaction_id', instance.transaction_id) instance.user = validated_data.get('user', instance.user) instance.save() return instance class Meta: model = Signage fields = ('id', 'user', 'subscription_plan', 'subscription_id', 'transaction_id' ) read_only_fields = ('id',) Here is the view: @api_view(['GET', 'POST']) def createSubscription(request): client = razorpay.Client(auth=("rzp_test_BmzgkoO2Is1glp", "oHmTJUCrdw2mP39BCrZdTY0t")) if request.method == 'GET': subscription_id = request.GET.get("subscription_id", None) if subscription_id is not None: return Response(client.subscripton.fetch(subscription_id)) else: return Response(client.subscription.all()) else: subscription = client.subscription.create(data={ "plan_id": request.data["plan_id"], "total_count": request.data["total_count"] }) signage = Signage.objects.get(id=request.data["signage_id"]) payload = { "subscription_plan": request.data["plan_id"], "subscription_id": subscription["id"] } updated_signage = CreateSignageSerializer(signage, data=payload, partial=True) if updated_signage.is_valid(): updated_signage.save() else: return Response(updated_signage.errors, status=status.HTTP_400_BAD_REQUEST) return Response(subscription, status=status.HTTP_200_OK) This is the error I get: AttributeError at /api/v1/subscriptions/ 'Signage' object has no attribute 'susbcription_id' In the database the rows do not have any … -
Django: How to raise Http401 and Http403 exceptions like Http404, RAISE EXCEPTION not RESPONSE
I'm trying to make an api using Django, and i'm verifying the request header if it contains an api key and raise an exception according to that, like so: def _check_driver_authorization(request): if request.headers.get('authorization') is not None: token = request.headers['authorization'] user = Driver.objects.filter(access_token=token) if user.exists(): return raise Http401 else: raise Http403 I didn't find anyone trying to make it like this, and i've searched many threads in here, they are all trying to return responses (render), my case i'm trying to interupt the request and raise the exception. I inspired this from get_object_or_404. -
Unable to configure web server (tried nginx, apache, gunicorn) with sokcet.io for a django application
I have a Django Application using python-socketio for communicating internally with other apps in my project. I am not able to use Django signals due to some constraints in the project. When I try to configure the web server for my application, the SocketIO throws an error when binding the application to the SocketIO. The Django Application is able to run when commented out the binding of the application. I am using 'threading' method for the socket communication. I have also tried it with 'eventlet' method in uwsgi when trying to connect with gunicorn. I have given a good research regarding the same but unable to figure out where I have gone wrong. I have given the wsgi.py file for your reference. import os import socketio from django.core.wsgi import get_wsgi_application from socket_app.views import sio from socket_app import client.socket_connection as client from socket_app.client import * os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) -
How to view API data within a GET method that's created using POST method in Django (without a model)?
I have created a DRF API that allows me to submit an image using the POST method via POSTMAN. The image is not stored in the model. After it's submission, I want to view the image's name in the browser using the Django Rest Framework. After reading sources in the net, I found out that people used the GET method in order to view all the data in a model. However, I don't have a model (don't require it for now) so how can I implement this requirement? The result should be something like this: { "image_name": <"name_of_the_image_stored"> } This is what I had done so far: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ImgSerializer from rest_framework import status from rest_framework.parsers import FileUploadParser class ImageAPI(APIView): def post(self, request): parser_classes = (FileUploadParser,) #key is 'image' when uploading in POSTMAN file = request.data.get('image', None) if file: uploaded_file = file fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) filename = fs.save(uploaded_file.name, uploaded_file) data = [{"image_name": filename}] serializer = ImgSerializer(data, many = True).data return Response(serializer, status = 200) else: return Response("Please upload an image", status = 400) def get(self, request): #What should I do here in order to view the submitted image above? serializers.py: from … -
How To Set Up a Error log and Access Log in python for Ubuntu 18.04 digital ocean server
i am new in Ubuntu 18.04 digital ocean server and Python. If any way to Create Error log and access log on my Ubuntu 18.04 digital ocean server? can anyone help me? -
How to provide different serializers based on incoming request
I am trying to provide different serializers based on incoming request for my categoryname Field in my model Role. Here is what i have tried: def get_serializer_class(self): categoryname = Role.objects.filter(categoryname=categoryname, pk=pk1, owner=owner) if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'): return RoleSerializerDepth if self.request.method == 'PUT' and 'Developer' in categoryname: return RoleSerializerDeveloper if self.request.method == 'PUT' and 'Investor' in categoryname: return RoleSerializerInvestor if self.request.method == 'PUT' and 'Auditor' in categoryname: return RoleSerializerAuditor if self.request.method == 'PUT' and 'Educational' in categoryname: return RoleSerializerEducationalInstitution return RoleSerializerBasic Here is my model class Role(models.Model): address1 = models.TextField(name="address1", max_length=150, null=True) address2 = models.TextField(name="address2", max_length=150, null=True) vat = models.CharField( max_length=100, null=True) categoryname = models.CharField(max_length = 100, blank=True, db_index=True) date_created = models.DateField(null=True) is_active = models.BooleanField(null=True) is_passive = models.BooleanField(null=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='roles', on_delete=models.CASCADE) And my serializers from rest_framework import serializers from .models import Role from core.serializers import DynamicFieldsModelSerializer, BasicSerializer from user.serializers import CustomUserSimpleSerializer from rest_framework.validators import UniqueTogetherValidator class RoleSerializerBasic(DynamicFieldsModelSerializer ,BasicSerializer,): owner = serializers.ReadOnlyField(source='owner.username') # class Meta(BasicSerializer.Meta): model = Role # Model to serialize fields = ('address1', 'address2','vat','categoryname','date_created', 'owner') extra_kwargs = { 'categoryname': { 'validators': [] } } def update(self, instance, validated_data): address1 = validated_data.pop['address1'] address2 = validate_data.pop['address2'] categoryname = validated_data.pop('categoryname') vat = validated_data.pop('vat') date_created = validated_data.pop('date_created') instance.save() return instance … -
Django SplitDateTime widget throws 'list' object has no attribute 'strip'
I am trying to create event with start date-time and end date-time with django. In the forms I've tried to seperate the date and time inputs with AdminSPlitDateTime widget (I'd like to have some JS for the input.) When I tried to create an event django gives me "'list' object has no attribute 'strip'" error. Also happens with SplitDateTimeWidget. When I removed the widget or use DateTimeInput widget (no split) everything works as expected. But User can confuse to enter the proper format for date time. SO I want to user AdminSplitDateTime. It must be something with spliting the date and time with widgets but I couldn't figure a way to solve this. Using Python 3.7 django 2.2.7 pipenv 2018.11.26 my Model is class Event(models.Model): event_start = models.DateTimeField() event_end = models.DateTimeField() notes = models.CharField(max_length=140, null=True, blank=True) hasta = models.ForeignKey(Hasta, on_delete=models.CASCADE) doktor = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.event_start} -- {self.event_end}' class Meta: ordering = ['event_start'] my Form class is: class EventCreateForm(ModelForm): event_start = forms.DateTimeField(widget= admin_widgets.AdminSplitDateTime()) event_end = forms.DateTimeField(widget=admin_widgets.AdminSplitDateTime()) def __init__(self, *args, **kwargs): """this whole thing is for filtering the hasta objects. User can only create an event with his patients.""" self.user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['hasta'].queryset = Hasta.objects.filter(doktor_id=self.user.id) class Meta: … -
Best index for a Django model when filtering on one field and ordering on another field
I use Django 2.2 linked to PostgreSQL and would like to optimise my database queries. Given the following simplified model: class Person(model.Models): name = models.CharField() age = models.Integerfield() on which I have to do the following query, say, Person.objects.filter(age__gt=20, age__lt=30).order_by('name') What would be the best way to define the index in the model Meta field? Which of these four options would be best? class Meta indexes = [models.Index(fields=['age','name']), models.Index(fields=['name','age']), models.Index(fields=['name']), models.Index(fields=['age'])] Thank you. -
Read sqlite from request body in Django
I want to read the sqlite database from request body without saving it into temporary file. The request has been sent by: curl -X POST --data-binary @mydb.sqlite3 -H "Content-Type: application/octet-stream" "http://localhost:8000/upload_sqlite" My view function like this: def upload_sqlite(request): print(request.body.decode('utf-8')) conn = sqlite3.connect(request.body) cursor = conn.cursor() cursor.execute("SELECT * FROM table") # do something cursor.close() conn.close() return HttpResponse(status=200) And the console output is here: b'SQLite format 3\x00\x04\x00\x01\x01\x00@ \x00\x00\x00\x18\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x0...' ...ignored... File "/path/to/views.py", line 208, in upload_sqlite conn = sqlite3.connect(request.body) ValueError: embedded null byte -
What are the cons of using mysql's reserved keywords as fields with django?
I have a Django model as: Class DataFile(models.Model): file = models.FileField(upload_to=get_file_upload_path) But, file is a reserved keyword in MySQL. I know that we can use any reserved keyword as column name by wrapping it in ``. My senior advised me not to use reserved keywords and use something which is nearly meaningful other than just file. What are the cons? -
django - Way to avoid custom manager for specific queries
I have the following issue: I am working on a grown project which uses the pattern of overriding the get_queryset() method in the manager. # Model declaration class MyModel(models.Model): ... objects = MyModelManager() # Manager declaration class MyModelManager(models.Manager): def get_queryset(self): return super(MyModelManager, self).get_queryset().exclude(is_visible=False) This causes some records to become basically invisible when you using the django ORM. I need now in certain edge cases to use the base get_queryset() method and NOT to use the custom one. I could clean up and change all the code but this is a lot of work. So my question: Is there a way to make a query like this MyModel.objects.all() and avoid using the custom manager method? Hope I made my point clear enought. Thx Ron -
Django: Getting a list of meetings that a certain user is in
I am new to Django and I am trying to get a list of meetings that a user is in, so that I can display them on a calendar. I have the following in models.py: class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True, unique=True) password = models.CharField(max_length=50, null=True) class Meeting(models.Model): id = models.AutoField(primary_key=True) admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) location = models.CharField(max_length=200, null=True) start_date = models.DateTimeField(default=None, null=True) end_date = models.DateTimeField(default=None, null=True) description = models.CharField(max_length=2000, null=True) class Member(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE) Essentially, a user and a meeting are linked in the Member model. I have the following function in database.py, which creates a new Meeting: def createMeeting(name, location, admin, start_date, end_date, description): new = Meeting(name=name, location=location, admin=admin, start_date=start_date, end_date=end_date, description=description) if not duplicate(Meeting, new): new.save() membership = Member(user=admin, meeting=new) if not duplicate(Member, membership): membership.save() For a certain user that is logged in, I want to be able to get a list of all the meetings that they are a member of. I know that I will need to use the Member model, but I am not sure what is the best method to get all the meetings a user … -
Return JsonResponse from function in Django REST
I have a query in which all fields are required. I want to make sure they're full. It turns out a lot of duplicate code. So I decided to create a function to which I pass values from a field. But the request continues rather than sending a response code 400. My views.py def pay(request): body = request.body.decode('utf-8') if not body: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'empty query' }, }) body = json.loads(body) phone = body.get('phone') amount = body.get('amount') merch_name = body.get('merchant_name') #check_field(phone) if not phone: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'phone field is empty' }, }) if not amount: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'amount field is empty' }, }) if not merch_name: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'merch_name field is empty' }, }) My function: def check_field(field): if not field: logger.info('its work') return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': '{} field is empty'.format(field) }, }) How i can fix it? -
Django Javascript not working in HTML to Ajax call
I'm trying to detect changes in a Form to change the following parameters depending on the previous one. Concretely when I change id_send_to(Client) it shows a list of companies from the client. I think that this should be done with Ajax Call. This is the code and when I check in the inspector I cannot see the console.log {% extends "helpdesk/base.html" %} {% load i18n bootstrap %} <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#id_send_to").change(function () { console.log( $(this).val() ); }); }); </script> Any Idea ? -
Django-models Change format of dateField as "DD-MM-YYY"
I am using django-model's-dateField in my django-project and wanna change my dateFields format in admin view. Currently (default) django gives format in YYYY-MM-DD but i want to modify that and in need of DD-MM-YYYY I've been struggled too much in this and till no solution. Also providing my code, may help.. my settings.py have: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='User_Profile') mobile = models.BigIntegerField() alternative_number = models.BigIntegerField() DOB = models.DateField() and then i register it in admin output on admin as you can see in my admin page there is a dateField with format 2019-11-04 but i want in form of DD-MM-YYYY as 04-11-2019. I tried LANGUAGE_CODE = 'de-at' that would work for me but the problem is it changes the local language also. -
Django view - template returned as bytestring (b'')
i have a strange problem with Django templates after merging recent changes. I migrated my application from Django 2.0.5 to 2.1.7, had some places in code to correct but nothing related with existing templates. After rebuild and deploy my templates are returned as bytestring in HTTP response body: b'<!DOCTYPE html>\n\n<html lang="en">\n <head ... Django settings charset is set to default utf-8 (i have some polish signs in page body) and files are encoded as: text/html; charset=us-ascii As far as i know us-ascii is subset of UTF-8 so it should be good. My base template is visible by template loader under common_app/base.html: <!DOCTYPE html> {% load pipeline navigation_tags i18n %} <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"> <title>XXX {% block title %}{% endblock title %}</title> {% stylesheet 'common' %} {% javascript 'common' %} {% block header %} {% endblock %} {% stylesheet 'sb-admin' %} {% javascript 'sb-admin' %} ... </head> <body> {% block body %} ... {% if user.is_authenticated %} ... {% render_navigation %} ... {% endif %} ... {% if error %} ... {% else %} {% block content %} {% endblock %} {% endif %} ... {% block footer %} {% endblock footer %} … -
Django reverse() method still throwing NoReverseMatch exception error even after adding the application name space
This is my urls.py file with my route names. from django.urls import path from . import views app_name = "procurement" urlpatterns = [ path('', views.index, name='index'), path('my_redirect/',views.my_redirect, name="my_redirect"), path('members/', views.members, name="members"), path('addMember/', views.addMember, name="addMember"), path('removeMember/', views.removeMember, name="removeMember"), path('requisition/', views.new_requisition, name="new_requisition"), path('user_department', views.user_department, name="user_department"), path('part1_requisition', views.part1_requisition, name="part1_requisition"), path('back_to_requisition_part1/', views.back_to_requisition_part1, name="back_to_requisition_part1"), path('part2_requisition/', views.part2_requisition, name="part2_requisition"), path('part3_requisition/', views.part3_requisition, name="part3_requisition"), path('ajax_filter', views.ajax_filter, name="ajax_filter"), path('pdu', views.pdu, name="pdu"), path('accounting_officer', views.accounting_officer, name="accounting_officer") ] And in my views.py file, I have something like this: @login_required def ajax_filter(request): """ Filter's ajax requests. """ if request.is_ajax(): first_name = "Byenkya" if first_name: return JsonResponse({ "success": True, "url": reverse('procurement:part3_requisition', args=[first_name]), }) return JsonResponse({ "success": False }) I really don't know why the reverse function is still raising the exception even after adding the namespace. Please someone help am new to django. -
how to delete record from django?
I have looked for alot of forums on how to do it but it just doesnt work, it seems like I could not get the button to link to the views method. views: item_id = int(item_id) p = Item.objects.get(item_id=item_id) p.delete() return redirect('viewproducts') viewproducts.html:(only taking the important parts out, also ignore the edit button) <tr> <td>{{i.item_id}}</td> <td>{{i.type}}</td> <td>{{i.name}}</td> <td>{{i.price}}</td> <td>{{i.description}}</td> <td>{{i.supplier}}</td> <td> <button onclick="/edit/{{item}}" type="button" class="btn btn-success"> Edit</button> <a href="/razer/deleteproducts/{{i.item_id}}" id={{i.item_id}}> Delete</a> </td> {% endfor %} urls.py: url('home/', home, name = 'Home Page'), url('addmembers/', addmembers, name = 'Add new members'), url('addproducts/', addproducts, name = 'Add new products'), url('members/', viewmembers, name = 'View all members'), url('products/', viewproducts, name = 'View all products'), url('deleteproducts/<int:item_id>', deleteproducts) ) all it doesis that it takes me to the same page as products, but with the link as http://127.0.0.1:8000/razer/deleteproducts/000999 Can someone help me please? Want to figure things out. -
How to run two requests parallel in django rest
I have two requests, which are called from react front end, one request is running in a loop which is returning image per request, now the other request is registering a user, both are working perfect, but when the images request is running in a loop, at the same time I register user from other tab,but that request status shows pending, if I stops the images request then user registered,How can I run them parallel at the same time. urls.py url(r'^create_user/$', views.CreateUser.as_view(), name='CreateAbout'), url(r'^process_image/$', views.AcceptImages.as_view(), name='AcceptImage'), Views.py class CreateUser(APIView): def get(self,request): return Response([UserSerializer(dat).data for dat in User.objects.all()]) def post(self,request): payload=request.data serializer = UserSerializer(data=payload) if serializer.is_valid(): instance = serializer.save() instance.set_password(instance.password) instance.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class AcceptImages(APIView): def post(self,request): global video stat, img = video.read() frame = img retval, buffer_img = cv2.imencode('.jpg', frame) resdata = base64.b64encode(buffer_img) return Response(resdata) These endpoints I am calling from react,the second endpoint is being calling in a loop and the same time from other tab I register user but it shows status pending and If I stop the image endpoint it then register the user,how can I make these two request run parallel. I have researched a lot but can't find appropriate solution, there … -
Writing javascript code in Django templates I got an error " Uncaught TypeError: Cannot set property 'innerHTML' of null"
This error is occurring in my console in the below line. function updateCart(cart) { for (var item in cart) { document.getElementById("div"+item).innerHTML = "- " + cart[item] + " + "; } localStorage.setItem('cart', JSON.stringify(cart)); document.getElementById('cart').innerHTML = Object.keys(cart).length; console.log(cart); } -
Can I redirect with method POST?
On my website the user can answer questions. If the user clicks (GET request) on a question the question_detail view is called and rendes the question_detail.html template with a question object. If the user clicks on a submit button a POST request is sent to the same question_detail view that renders question_detail_solution.html. On this template the user can submit a comment form that is handled by the add_comment_to_question view. Once the comment is submitted I want the user to be redirected back to the same question_detail_solution.html template. It is important that the same context is passed into the template. Can I do a redirect with method POST from add_comment_to_question and is this best practice? Or should I define another view that renders question_detail_solution.html and redirect from question_detail (POST) and add_comment_to_question to this view? Or something else? Thank you for your answer! def question_detail(request, pk): question = get_object_or_404(Question, pk=pk) user_profile = Profile.objects.get(user=request.user) solved_questions = user_profile.solved_questions.all() if request.method == 'GET': context = {'question':question} return render(request, 'question_detail.html', context) else: try: answer = int(request.POST['choice']) is_correct = question.choice_set.get(id=answer).correct if is_correct: user_profile.solved_questions.add(question) form = CommentForm() context = {'question':question, 'answer':answer, 'correct':is_correct, 'form':form} return render(request, 'question_detail_solution.html', context) except KeyError: messages.error(request, "Please make a choice!") context = {'question': question} … -
Django button class forloop trigger javascript
i have forloop in Django template and want to make button for elements if condition contains true to show additional info as infobox, or popup. Best way to do this is javascript, but how to trigger each one separately? I dont know how many buttons will be. I could use forloop counter, but how to activate js then? {% for hist in histor %} <a class="trigger_popup_{{ forloop.counter }}"><img src='{% static "images/info.PNG" %}'></a> {% if hist.ikona == 1 %} <img src='{% static "images/hist/108.png" %}'> {% elif hist.ikona == 2 %} <img src='{% static "images/hist/154.png" %}'> {% elif hist.ikona == 8 %} <img src='{% static "images/hist/499.png" %}'> {% endif %} {% endfor %} What to add in this: var modal = document.getElementById("trigger_popup_"); button / link class may be trigger_popup_4, trigger_popup_5, trigger_popup_88 How to manage this?