Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels elastic beanstalk (linux 2) hooks postdeploy: -b command not found
For deployment of django channels on elastic beanstalk (linux 2 AMI) I tried implementing this blog ,it required creation of ./platform/hooks/postdeploy/ and in it two files 01_set_env.sh and 02_run_supervisor_daemon.sh, on eb deploy it fails and on checking the eb-engine.logs this error shows up. 2021/09/28 05:05:44.382229 [ERROR] An error occurred during execution of command [app-deploy] - [RunAppDeployPostDeployHooks]. Stop running the command. Error: Command .platform/hooks/postdeploy/02_run_supervisor_daemon.sh failed with error exit status 2. Stderr:.platform/hooks/postdeploy/02_run_supervisor_daemon.sh: line 13: -b: command not found 02_run_supervisor_daemon.sh #!/bin/bash # Get system environment variables systemenv=`cat /opt/elasticbeanstalk/deployment/custom_env_var | tr ' ' ',' | sed 's/%/%%/g' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/:$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` systemenv=${systemenv%?} systemenv=`echo $systemenv | sed 's/,/",/g' | sed 's/=/="/g'` systemenv="$systemenv"" # Create daemon configuration script daemonconf="[program:daphne] command=daphne -b :: -p 5000 backend.asgi:application directory=/var/app user=ec2-user numprocs=1 stdout_logfile=/var/log/stdout_daphne.log stderr_logfile=/var/log/stderr_daphne.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true environment=$systemenv" # Create the Supervisor conf script echo "$daemonconf" … -
BitBucket Deploy to Google Cloud appEngine could not find file Django
I have .yml file for pipline of django the code for deploye is - pipe: atlassian/google-app-engine-deploy:0.7.3 variables: KEY_FILE: $KEY_FILE PROJECT: $PROJECT DEPLOYABLES: 'realpars_platform/app.yaml' VERSION: '${BITBUCKET_BUILD_NUMBER}' PROMOTE: 'true' STOP_PREVIOUS_VERSION: 'true' EXTRA_ARGS: '--verbosity=debug --quiet' But when i run this Error showes. ERROR: (gcloud.app.deploy) [/opt/atlassian/pipelines/agent/build/realpars_platform/app.yaml] does not exist. ✖ Deployment failed. -
Check Python Version Used in Mod_WSGI
I can't find out which python environment is being used or install location is being used by mod_wsgi in Apache. In my apache config I didn't gave any specific venv config. ServerName ServerAlias DocumentRoot /home/Downloads ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/Downloads/static <Directory /home/Downloads/static> Require all granted </Directory> <Directory /home/Downloads/samples> Require all granted </Directory> <Directory /home/Downloads> <Files wsgi.py> Require all granted </Files> </Directory> #WSGIDaemonProcess group python-path=/home/Downloads python-home=/home/envlin WSGIProcessGroup group WSGIScriptAlias / /home/Downloads/wsgi.py I removed the critical info and replaced with random info. Here's my apache restart log Apache Logs Apache/2.4.46 (Ubuntu) OpenSSL/1.1.1j mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations Question Is there any way to get which python version and install location is being used by mod_wsgi. **Python Path's ** If I fetch python path's normally here's the result. sys.path = [ '/root', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.9/dist-packages', ] -
Python 2.7 Failed building wheel for MySQL-python
I'm new to Python && Django. In activated virtual environment when i run pip install mysqlclient==1.3.9 I get Failed building wheel for MySQL-python I tried to install without specific version as well. I also tried solutions like running: sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-pil python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev and updated pip. ERROR: Command errored out with exit status 1: command: /home/tech/Projects/dpython/sk/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-8CZORn/mysql-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-8CZORn/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-igaywV cwd: /tmp/pip-install-8CZORn/mysql-python/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -ffile-prefix-map=/build/python2.7-5hlAcC/python2.7-2.7.18=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o _mysql.c:44:10: fatal error: my_config.h: … -
Editing Forign Key Attributes Of a Model From Django Admin
I have two model classes in my django project. class User(AbstractBaseUser, PermissionsMixin): username = None phone = models.CharField(max_length=16, unique=True) password = models.CharField(max_length=255, default="asdf") name = models.CharField(max_length=255, default="User") email = models.EmailField(max_length=255, blank=True, null=True) class Booking(models.Model): profile = models.ForeignKey(User, null=False, on_delete=models.CASCADE, db_index=True, default=1) latitude = models.DecimalField(decimal_places=20, max_digits=30, default=1.0000) longitude = models.DecimalField(decimal_places=20, max_digits=30, default=1.0000) Now In the django admin panel, I want to change the name of the user from the edit screen of a booking. I tried with Inline Models, with it I can edit booking from user's edit screen but it is not working in this case. Is there any other options available for this? -
Admin email handler with filter keeps sending emails
I am trying to silence a specific error getting emailed through the django.request logger: 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, } The filter silence_invalid_header is attached to the handler: 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false', 'silence_invalid_header'], 'class': 'django.utils.log.AdminEmailHandler' } } This is the filter configuration: 'silence_invalid_header': { '()': 'mysite.logger_utils.SilenceInvalidHttpHostHeader' } And the filter class itself: class SilenceInvalidHttpHostHeader(logging.Filter): def filter(self, record): return 'Invalid HTTP_HOST header' not in record.msg However, I keep getting emails. Although django.request is set to propagate, it should propagate to Django's default logger django defined in django.utils.log.DEFAULT_LOGGING: 'django': { 'handlers': ['console'], } And that hanlder just writes to the standard output: 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', } So why do I keep getting emails with that error and how can I silence them? -
base64 saves blank image - django
im trying to capture image from webcam , but when i decode it using base64 it only saves a blank image ? this is what i tried class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': data = request.POST.get('documents') format, imgstr = data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) images = UploadDocumentsForm(request.POST,request.FILES) if data: photo = Document.objects.create( booking = obj, docs = data ) photo.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('choose or capture right image ..')) return render(request,'booking/add_img.html',{'obj':obj,'form':images}) here is my template const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const imgFormat = canvas.toDataURL(); docs.value = imgFormat const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { context.drawImage(player, 0, 0, canvas.width, canvas.height); e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); <form action="" method="POST" enctype="multipart/form-data" dir="ltr">{% csrf_token %} <input type="text" name="documents" id="document"> <video id="player" controls autoplay></video> <button id="capture">Capture</button> <canvas id="canvas" width=320 height=240></canvas> <button class="header pt-2 text-white px-4 p-1 rounded-lg mt-4">{% trans "save" %}</button> </form> please is there solution , i appreciate your helps .. thank you in advance .. -
Passing data from a view to a form in django
I have a django formtool: the first step it needs to insert a name and select N values from a MultipleChoiceField. When user submit this form in the second step, I need to show N MultipleChoiceField where every elements of each MultipleChoiceField are retrieved from the database. I need to take the values of the first step form, retrieve from Db the data e send these to the second steps (forms.py). For the second step I suppose I need a formset. I have read some few questions about passing value from a view to a form but any solution. This is my code: forms.py from django import forms from station.models import Station from django.forms import formset_factory from .models import Vdl station_all=Station.objects.all() class VdlSelectStationsForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) class VdlSelectSensorsForm(forms.Form): sensor_list_for_station = forms.ModelMultipleChoiceField(queryset=Vdl.objects.all()) #filter(id_user = id_user)) VdlSelectSensorsForm = formset_factory(VdlSelectSensorsForm, extra=1) views.py from django.shortcuts import render from .forms import VdlSelectStationsForm, VdlSelectSensorsForm from formtools.wizard.views import SessionWizardView class VdlWizard(SessionWizardView): template_name = "vdl.html" form_list = [VdlSelectStationsForm, VdlSelectSensorsForm] def get_form_initial(self, step): initial = {} # If at second step, add image path to initial data for canvas field if step == '1': first_step_data = self.storage.get_step_data('0') … -
Why I cannot get email user login with line by Django django-social-auth
Django Setting AUTHENTICATION_BACKENDS = [ 'social_core.backends.line.LineOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_LINE_KEY = '???????' SOCIAL_AUTH_LINE_SECRET = '????????' SOCIAL_AUTH_LINE_SCOPE = ['profile email openid'] I follow this scope and request but the response don't send user email to my app -
How to parse date string containing mm/yyyy in django models?
I'm writing existing SQLite3 database to django models. Some dates replicate themselves and I need them encoded, so I create a class in the model to store unique periods in the following form: mm/yyyy. What would be the right syntax to set date, so in django they have the same format, but as a datetime object? class Periods(models.Model): period = models.DateField() def __str__(self): return self.period Thanks in advance. -
Can't log in into Django admin panel
I did look up the other people having a similar problem, but mine is slightly different. When I try to log in the Django admin panel, my credentials (which are correct) don't work: I'm told I have to enter the right ones, that it might be case-sensitive, etc. This occured first on a project where I fiddled with custom user/superusers and did terrible things to migrations, so I understood the root of the problem. Now, the real problem is that when I switched back to another (fully working) project and tried to log into the admin console, I still had (and have) this bug even though a) it worked before and I haven't touched the code since (a week ago) b) I'm using Django's user model for this project. I tried clearing my cookies and restarting my computer, but nothing's working. Both projects are fully independant; the only common point they have is django + being hosted on a SQlite local server. Did I break everything? -
How to make in django templates a bootstrap card always stay the same height
I am working on a Django project and in templates, I am using bootstrap for styling and using cards. I want all the cards to be the same height and I used min height also but it's not working. Here is my html: <section class="devlist"> <div class="py-5"> <div class="container"> <div class="row hidden-md-up"> {% for profile in profiles %} <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="{{ profile.profile_image.url }}" class="card-img-top" alt="..."> <div class="card-body" style="min-height: 441px;"> {% if profile.name|length > 13 %} <h5 class="card-title">{{profile.name|slice:"13"}}...</h3> {% else %} <h5 class="card-title">{{profile.name}}</h5> {% endif %} {% if profile.short_intro|length > 25 %} <h6 class="card-subtitle text-muted"> {{profile.short_intro|slice:"40"}}... </h6> {% else %} <h6 class="card-subtitle text-muted"> {{profile.short_intro}} </h6> {% endif %} {% if profile.bio|length > 100 %} <p class="card-text"> {{profile.bio|slice:"100"}} </p> {% else %} <p class="card-text"> {{profile.bio}} </p> {% endif %} <a href="#" style="margin-bottom:1%;" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> </div> </div> </section> How can I make all the cards of the same height irrespective of the content -
Tensor is not an element of this graph when calling in django
i’m facing a problem with TF and Django. my code is: modelSavePathName = os.path.join(data_dir, f'detector_26082021_2111.h5') detector.model.load_weights(modelSavePathName, by_name=True) modelSavePathName = os.path.join(data_dir, f'recognizer_27082021_0846.h5') recognizer.model.load_weights(modelSavePathName, by_name=True) pipeline = keras_ocr.pipeline.Pipeline(detector=detector, recognizer=recognizer, max_size=4096) imagesDF = keras_ocr.tools.read(img) pr = pipeline.recognize(images=[imagesDF ])[0] when i call pipeline.recognize(images=[imagesDF ])[0] localy it works. but when i call it in Django view i get this error: ValueError at / Tensor Tensor(“conv_cls.8_1/BiasAdd:0”, shape=(None, None, None, 2), dtype=float32) is not an element of this graph. can anyone help me please, I’m desperate. best regards -
Unsuccessful command execution on instance id(s) 'i-04e3dd1fd8a1663c3' elasticbean django deployment
i am trying to deploy my django site on aws elasticbean but when i created the envoirment it thows me error 021-09-28 07:24:43 INFO Created CloudWatch alarm named: awseb-e-vuemp6euky-stack-AWSEBCloudwatchAlarmHigh-10XFBTK55D2M0 2021-09-28 07:24:43 INFO Created CloudWatch alarm named: awseb-e-vuemp6euky-stack-AWSEBCloudwatchAlarmLow-Q0TYK7ZDH70U 2021-09-28 07:25:10 ERROR Instance deployment failed to install application dependencies. The deployment failed. 2021-09-28 07:25:10 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-09-28 07:25:13 ERROR [Instance: i-04e3dd1fd8a1663c3] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-09-28 07:25:13 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-09-28 07:26:15 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. then i run eb status i ignored it and move forward after adding cname in allowed host i run the command eb deploy then it thows me a error again 2021-09-28 07:30:11 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-09-28 07:30:12 ERROR [Instance: i-04e3dd1fd8a1663c3] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-09-28 07:30:13 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. … -
I want to create hackerrank like Website where user can solve programming questions? [closed]
Hello Everyone Can anyone help me how to create a website like hackerrank or hackerearth where user can solve programming questions, I mean I have to create only coding problem website not whole website like hackerrank has.I want to do it in Django and Python.I have read many article related to this from that I get to known that I can use unittest for checking the answer but Exactly I don't how I have to do it and what should be the pathway So please help?This is my college project!! -
How to implememt simple django quiz
I'm trying to do a "practice words in English" quiz. The user gets 4 random words from the DB and has to choose the right option. The problem with the code is that the test whether the user chose the right word or not occurs after the selection and in fact the comparison is made in front of the next set of words. View: def quiz(request): choices = Words.objects.all().values_list("id","English_word","Hebrew_word", ) choice_list = [] for item in choices: choice_list.append(item) random.shuffle(choice_list) word = choice_list[0][1] options = choice_list[:4] random.shuffle(options) if request.method == 'POST': user_choice = request.POST.get('quiz') if user_choice == choice_list[0][2]: messsge = 'V' return render(request, 'quiz.html', {'choices':options,'word':word, "messsge":messsge,}) else: messsge = 'X' return render(request, 'quiz.html', {'choices':options,'word':word, "messsge":messsge,}) return render(request, 'quiz.html', {'choices':options,'word':word,}) HTML: <h2> {{word}} </h2> {%for choice in choices %} <form method="POST"> {%csrf_token%} <br/> <input id='quizz' name = "quiz" type="submit" value={{choice.2}} class="btn btn-primary"/> </form> {%endfor%} {{messsge}} -
Django SimpleJWT
I am using a django-simplejwt and I have a custom token view for obtaining token. My problem is, how can i override the 401 Unauthorized response from the view? https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class ObtainTokenSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['name'] = user.first_name # ... return token class ObtainToken(TokenObtainPairView): serializer_class = ObtainTokenSerializer -
how to order a choicefiled in django model
I have a choice filed and i need to sort it based on the order in CHOICES tuple and this model.py : class MeetingMember(models.Model): CHOICES = ( ("H", "Host"), ("A", "Accepted"), ("R", "Rejected"), ("I", "Invited" ) ) status = models.CharField(max_length=9, choices=CHOICES, default="I") i have already tried meta ordering : class Meta: ordering = ('status',) but it is not working i need to sort it in 'Host,Accepted,Rejected,Invited' -
Navbar problem with views context, when using slug or PK. (Django)
The slug will only work on HomeView if I add it to the HomeViews context, but I only want to add it one time, I don't want to add it to every view, but I want it to work on every view. Is there anyway I can do this? app2/models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Model1(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) app1/views.py from app2.models import Model1 from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.views.generic.list import ListView class HomeView(ListView): model = Model1 ordering = ['-id'] template_name = 'app1/home.html' boolean = False model1_slug = 'app2' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if Model1.objects.filter(user=self.request.user).exists(): self.boolean = True user_model1 = Model1.objects.get(user=self.request.user) self.model1_slug = user_model1.slug else: self.model1_slug = 'app2' self.boolean = False context['model1_slug'] = self.model1_slug context['boolean'] = self.boolean return context includes/navbar.html {% if boolean == False %} <li><a class="dropdown-item" href="{% url 'start-model1' %}">Start Model1</a></li> {% elif boolean == True %} <li><a class="dropdown-item" href="{% url 'my-model1' model1_slug %}">My Model1</a></li> <li><a class="dropdown-item" href="{% url 'add-model2' %}">Add model2</a></li> {% endif %} The navbar will give nothing if I'm not at the home page. -
How Can i use Nuxt and Django for production at the same time?
I have a background in Django and a some experience in Vue. I have used Vue for almost a year now, but since I need an SSR I have to use Nuxt.However, I am still very confused with how to deploy it in the server along with Django. Should I deploy them in the same server or should I deploy them in a different server with Django server for API and Nuxt for the front end? -
Get default exam as object.id
You can get or create default object Create this method: def get_default_exam(): exam = Exam.objects.get_or_create(<fields>)[0] return exam.id Then, you can use it in default: class Student(models.Model): ... exam_taken = models.ForeignKey("Exam", default=get_default_exam()) -
I am learning about django-ads using it to create a advertisement product [closed]
I have been studying about the django-ads package from python-django . been tring to create an ads app where user can save their own ads and then we distribute it to our project, i.e. the user hepls display their own ads to the website, later we can expand the product. But I am being at this point where i am not getting what to do next. I have added the ads with their target_urls onto the database. In this exapmle below of django-ads: First step they did is insert 3 ads ,in this step i facing a problem . This step takes value in dictionary form like key-value pairs, i have data which can be processed as a dictionary type. but the template_body key is where i am getting confused. I am trying to distribute the ads in the whole website. Any suggestions will be appreciated. Thank You. django-ads - Example1.wiki Insert 3 ad show's by admin Ad Show 1 name: 'ad 1' group: 'first-group' template_body: 'my ad number 1' url_pattern: None Ad Show 2 name: 'ad 2' group: 'first-group' template_body: 'my ad number 2' url_pattern: '/test/[\w_-]+/' Ad Show 3 name: 'ad 3' group: 'second-group' template_body: 'my ad number 3' … -
I want to reflect the current date & time in rest API based on the user region but I'm unable to get it
I just tried to get the list of date and time instead of DD-MM-YYYY format but I wasn't able to. When I tried to fetch one particular id it's reflecting only the time. I want to call the particular id using the username through slug. views.py from datetime import date from django.http import request from django.http.response import JsonResponse from django.shortcuts import get_object_or_404 from rest_framework import generics, mixins, serializers from rest_framework.decorators import api_view from rest_framework.fields import JSONField from rest_framework.response import Response from rest_framework.views import APIView from app.models import Userbase import datetime from .serializers import UserDetailSerializer, UserSerializer import pytz from rest_framework import viewsets from rest_framework import status from rest_framework.renderers import JSONRenderer @api_view(['GET', 'POST']) def data_list(request): if request.method == 'GET': user = Userbase.objects.all() print(user) serializer = UserSerializer(user, many=True) # json = JSONRenderer().render(serializer.data) # print(json) return Response(serializer.data) elif request.method == 'POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'POST']) def data_detail(request, pk): # try: # user = Userbase.objects.get(pk=pk) # except Userbase.DoesNotExist: # return Response(status=status.HTTP_404_NOT_FOUND) # if request.method == 'GET': # serializer = UserDetailSerializer(user) # return Response(serializer.data) if request.method == 'GET': try: user = Userbase.objects.get(pk=pk) --here i want to call based on username print(user.timezone) serializer = UserDetailSerializer(user, data=request.data) zone … -
django get polygons inside coordinates
I have a coordinate that frontend gives me like "[[{"lat":45.36324254131911,"lng":2.471923828125},{"lat":46.667815881216754,"lng":2.471923828125},{"lat":46.667815881216754,"lng":6.50390625},{"lat":45.36324254131911,"lng":6.50390625}]]" This is a rectangle. I have a model where I am storing Polygon data from djgeojson.fields import PolygonField class MyCords(models.Model): geom = PolygonField() a single instance of Mycords.geom gives me data like: {'type': 'Polygon', 'coordinates': [[[5.328369, 45.251688], [5.910645, 44.980342], [6.328125, 45.375302], [6.075439, 45.859412], [5.471191, 45.698507], [5.328369, 45.251688]]]} Here I want to filter all the MyCords that lies in the given coordinates. How can I get this through queryset ? -
Exporting model data to csv file using Python Django not working
I am trying to create a but to export some data in my database to a csv file. It hits the correct part of the if statement but no CSV file is being downloaded. # ================================= # CSV Import/Export Functionality # ================================= @login_required def exportData(request, setCode): current_user = request.user if request.GET.get('product-type') == 'Cards': response = HttpResponse(content_type='text/csv') now = datetime.datetime.now() response['Content-Disposition'] = "attachment;filename=ExportData-" + setCode.upper() + "-" + now.strftime("%Y-%m-%d %H.%M.%S") + ".csv" writer = csv.writer(response) writer.writerow(['setCode', 'id', 'number', 'name', 'rarity', 'convertedManaCost', 'colors', 'standard', 'foil']) SQL_EXPRESSION = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" for cards in inventory_cards.objects.all().filter(user_id=current_user.id).extra( select={'int': SQL_EXPRESSION}).order_by('card_id__set_id__code', 'int', 'card_id__number').values_list( 'card_id__set_id__code', 'card_id', 'card_id__number', 'card_id__name', 'card_id__rarity', 'card_id__convertedManaCost'): writer.writerow(cards) return response elif request.GET.get('product-type') == 'Tokens': pass elif request.GET.get('product-type') == 'Sealed': pass