Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to realize sending otp on the phone?
I am trying to implement phone registration using twilio, python and django I can`t comprehend how i have to realize mechanism , that takes input from user for texting him Generating otp and sending to user: from twilio.rest import Client import random otp=random.randint(1000,9999) account_sid = '' auth_token = '' client = Client(account_sid, auth_token) client.messages.create(from_='+', to='+', body='Your OTP is -'+str(otp)) When user inputs his phone number, it sends to the server But how i can place his number at to =" _HERE_ " , when he sends it to the server and how i can call this file then? -
How to limit the number of entries in django database ? Using the default database (sqlite3)
How can i specify number of entries in my django database (sqlite3). For example my model is: from django.db import models class About(models.Model): firstname = models.CharField(max_length=500) lastname = models.CharField(max_length=500, blank=True) address = models.TextField() details = models.TextField() class Meta: verbose_name_plural = 'About' def __str__(self): return self.firstname Now i want to store data of only 2 members in my database. And after adding the data of both users in database from django admin panel, if i try to store data of 3rd member than it should show that database limit is crossed you can't store this data, delete previous data first. Is it possible to limit entries form django models.py . -
How to add an executable to PATH in Azure's Kudu?
I need to add the gecko driver in order to run a headless browser on Azure as part of my website, but I need to add the geckodriver to PATH (apparently I can't manually input the location of the geckodriver file in Python?) I know I have to use the applicationHost.xdt file and add it to /home/site folder, but my Kudu page doesn't allow me to add files (I can create the file using 'touch', but I can't edit it). This is how my Kudu page looks like: https://imgur.com/a/99oHUoC This is my applicationHost.xdt: <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <system.webServer> <runtime xdt:Transform="InsertIfMissing"> <environmentVariables xdt:Transform="InsertIfMissing"> <add name="geckodriver" value="geckodriverL" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> <add name="PATH" value="%PATH%;%HOME%\site\wwwroot\cpu" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> </environmentVariables> </runtime> </system.webServer> </configuration> This is the error I get from Django: WebDriverException at / Message: 'geckodriverL' executable needs to be in PATH. Request Method: GET Request URL: http://site.azurewebsites.net/ Django Version: 2.2.6 Exception Type: WebDriverException Exception Value: Message: 'geckodriverL' executable needs to be in PATH. Exception Location: /antenv/lib/python3.7/site-packages/selenium/webdriver/common/service.py in start, line 83 Python Executable: /opt/python/3.7.4/bin/python3.7 Python Version: 3.7.4 Python Path: ['/opt/python/3.7.4/bin', '/home/site/wwwroot', '/antenv/lib/python3.7/site-packages', '/opt/python/3.7.4/lib/python37.zip', '/opt/python/3.7.4/lib/python3.7', '/opt/python/3.7.4/lib/python3.7/lib-dynload', '/opt/python/3.7.4/lib/python3.7/site-packages'] Server time: Fri, 18 Oct 2019 14:39:59 +0000 -
jQuery: if statement to select an option value
My aim is: If I type a value bigger than 60, then I would like the option "Long" to be selected. If I type a value less than 60, then I would like the option "Short" to be selected. With help of of jQuery, I would like for "result" to be automatically changed given the field "value" I have a form, contains an input integer field, with id "value", and form has a option field with id "result". Below is my try, but it does not work. Thanks for your input. var value = $('#value'); $(value).change(function() { debugger; if (Number($(this).val()) > 60) { $('#result').prop('value') = "Long"; } if (Number($(this).val()) < 60) { $('#result').prop('value') = "Short"; } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label for="value" class="col-form-label col-sm-4">Value</label> <div class="col-sm-7"> <input type="number" name="value" class="numberinput form-control" id="value"> </div> </div> <div><i>Result:</i></div> <div id="result" class="form-group row"> <div class="col-sm-12"> <select name="result" class="select2 form-control" style="width: 100%;" id="result"> <option value="Long">Long</option> <option value="Short">Short</option> -
Passing data from function to template in a Django view
I have an ordinary view, which renders a template with some variables. In this example, two values called x, y are retrieved from a form. I would like to render on my template the addition of those two numbers, so i tried this: def myview(): if request.method == 'POST': form = MyForm(request.POST) # check whether it's valid: if form.is_valid(): x = request.POST['x'] y = request.POST['y'] MyFunction(x, y) send = form.save() send.save() messages.success(request, f"Success") //Some other operations here.. return render(request, "main/mytemplate.html", context={"mydata": mydata}) def MyFunction(x, y): mydata = x*y return mydata This problem gives an error, of course, because MyData is a variable defined inside a function, so myview can't see it. Is there a way to pass the variable to the view? I know that i could do the same operation all inside the view, without defining a function, but i would rather use a function since it makes the code easier to read. -
Django only get object if one of it's subobjects meets condition
So I have two models: class Business(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) class Appointment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="appointments") And in my view I have the following context: def home(request): [...] context = { 'business':Business.objects.order_by('name'), } [...] Now I would get all businesses there are with their submodels "Appointment". But what I want is only businesses where on of the existing submodels "Appointment" fullfillsauthor == request.author Also the submodels "Appointment" of a Business should only be the "Appointments" where their author equals request.author -
ConnectionResetError: [Errno 104] Connection reset by peer in Django and Postgresql
I am facing a problem with only a single url which gives connection refused by peers. I have a Django project deployed in server.Earlier it was working fine but now it is giving me this error and on web page it is showing blank screen.I am sending the correct response from views and able to display in text form but it is not rendering with Django template special functions.I tried many things which are available on stack overflow and many other websites but nothing is working.I also tried re-installing Django and also tried to change the url and restarted server many times but nothing worked.I am using a Amazon-ec2 centos server,Django version 2.1 ,python version is 3.7.3.Stack Trace Traceback (most recent call last): File "/usr/lib64/python3.7/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib64/python3.7/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib64/python3.7/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/lib64/python3.7/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib64/python3.7/socketserver.py", line 799, in write self._sock.sendall(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 60208) Traceback (most recent call last): File "/usr/lib64/python3.7/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib64/python3.7/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib64/python3.7/wsgiref/handlers.py", line 279, … -
Django User model not working after being overrided
Explanation I have extended Django User model and add some fields to that. Then I have saved the model and replaced it with the last User model using StackedInline. For this purpose I am using django_rest_framework. More specifically here is my code: Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # TODO: add Upload directory to the avatar avatar = models.ImageField() university = models.CharField(max_length=100, default="") discipline = models.CharField(max_length=100, default="") joined_at = models.DateTimeField(auto_now=True) class UserProfileInline(admin.StackedInline): '''Stacked Inline View for UserProfile''' model = UserProfile class UserAdmin(BaseUserAdmin): inlines = ( UserProfileInline, ) Post Request: Problem I can see the additional fields that I have added in the User model in django-admin, but whenever I want to send a post request to create a new user, the additional fields are ignored! (while I have put the data in the post request, but it shows blank in admin) Question How can I fix or edit my model that it works properly? -
Checking condition before inserting data to a table in Django
I have 5 tables User(i.e Employee), Positions and Emp_position(which is a relationship table between the Employee and Positions). I have a department table which contains the list of all departments in my company and a relationship table Works_in which maps User(Employee) to a department. Now in the Works_in table when I am mapping User(Employee) to a Department I want to check whether the data that I am inserting in Works_in(relationship) table. That is mapping an employee to a department already has a manager mapped to it or not. Example : Employee Himanshu Bassi BB Position Developer Manager Tester Emp_position(relationship table) Employee Position Himanshu Developer Bassi Manager BB Manager Department Web UI Data Analysis Machine Learning Works_in Employee Department Himanshu Web UI Bassi Web UI BB Web UI # this is wrong, which needs to be checked Each Employee will be mapped to a Department, But a department should not have multiple manager. Over here since Bassi and BB are manager we don't want them to be mapped to same department. So for that purpose I want to check before the data BB Web UI was being inserted to our Works_in table whether the department that is going to be mapped … -
How to use PyPDF2 to insert *.png image file into a .pdf file
here is my code: input_file = "example.pdf" output_file = "example-drafted.pdf" watermark_file = "draft.pdf" with open(input_file, "rb") as filehandle_input: pdf = PyPDF2.PdfFileReader(filehandle_input) with open(watermark_file, "rb") as filehandle_watermark: watermark = PyPDF2.PdfFileReader(filehandle_watermark) first_page = pdf.getPage(0) first_page_watermark = watermark.getPage(0) first_page.mergePage(first_page_watermark) pdf_writer = PyPDF2.PdfFileWriter() pdf_writer.addPage(first_page) with open(output_file, "wb") as filehandle_output: pdf_writer.write(filehandle_output) in my above code : watermark_file = "draft.pdf". i want this watermark_file to be used as "draft.png" -
How to use filter value as variable in django orm
I want to use tmp_id as a value of row id in extra method . code: order_obj = table.objects.filter() .annotate( tmp_id=F('test_data') ) .extra( select={"select id from data where row_id = {{here i want to use tmp_id}} limit 1"} ) can anyone tell me how to do it ? -
How can I render this formset as a Crispy form?
I've been having trouble getting my image formsets to upload correctly in Django. I'm using crispy forms, and all other elements on the form and page work fine. Here's what the form looks like: For context, the form should look like this: As you can see, crispy forms isn't rendering. I originally dismissed this as a purely graphical issue, but the HTML source code shows that the FormHelper elements (enctype, layout_class, field_class etc...) aren't loading either, which impedes the image upload functionality. <form class="form-horizontal" method="post" > ... </form> I've walked through the code and the tutorial I used line by line, but I can't find where the problem lies. views.py class CarCreate(generic.CreateView): model = Car slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CreateCarForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) self.request.POST: data['images'] = CarImageFormSet(self.request.POST, self.request.FILES) else: data['images'] = CarImageFormSet() return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.seller = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.save() return super(CarCreate, self).form_valid(form) def get_success_url(self): # return reverse_lazy('showroom:cars', kwargs={'slug': self.object.id}) # Throws an error return reverse_lazy('showroom:cars') forms.py class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller', 'id'] def … -
How to calculate x^2 in sympy gamma
I am very new to coding in Python and using the django. My question: is it possible to calculate x^2 in sympy gamma?In my program x**2 is working but x^2 is not working. ^ is not working. my code is- from django.shortcuts import render, redirect from django.http import HttpResponse from sympy import * from sympy.parsing.sympy_parser import * import sympy as sp # Create your views here. def index(request): if request.method == "POST": x = symbols('x') init_printing() transformations = (standard_transformations + (implicit_multiplication_application,)) eq = parse_expr(request.POST['equ'], transformations=transformations) sympifyy = latex(sympify(eq, evaluate=False)) sympifyy1 = Eq(eq) derivative = latex(sp._eval_derivative(eq,x)) integration = latex(sp.integrate(eq, x)) # integration = integrate(eq, x) # pretty(latex(Integral(eq, x)),use_unicode=False) # print(pretty(Integral(sqrt(1/x), x), use_unicode=False)) rootss = solve(eq) limits = limit(eq, x, 0) seriess = latex(series(eq, x, 0, 10)) data = { 'Sympify' : sympifyy, 'Sympify1' : sympifyy1, 'Derivative' : derivative, 'Integration' : integration, 'Roots' : rootss, 'Limit' : limits, 'Series' : seriess } return render(request, 'index.html', {'data':data}) return render(request, 'index.html') -
What's the difference between handling requests in Django 3 ASGI mode vs WSGI mode?
Django 3 should be released soon and it will be able to work in ASGI mode. ASGI mode seems to make Django more efficient when handling requests than in WSGI mode (more requests can be handled per time unit if I believe correctly). How is it accomplished? Is it like that Django can handle at the same time multiple requests, but most of them will be waiting on events like fetching data from a database or other IO operations? -
Not able to access the URL of the tenants though service is running fine
I am working on django-tenants module to create multi-tenant application for my customers. In my requirement : a user can belong to more than one customer and it can have different roles so I found this as an ideal way to do it. Now the issue is I have created the separate schema for each tenant but I am not able to access any URL though service is running fine.It is showing me error of page not found. I tried the steps mention by tomturner who is one of the contibutor of django-tenants. Below is the link which i followed: https://github.com/tomturner/django-tenants/blob/master/docs/install.rst Everything is perfect in database but why URL is not accessible that I am not able to figure it out. from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField(max_length=100) class Domain(DomainMixin): pass My domain name of tenant s1 is singh.co, so i should be able to access the tenant url using http:///singh.co:8000. But I am getting 404 error. Not able to identify problem. I am using python 3.7.3 with below packages. Django - 2.2.6 django-tenants- 2.2.3 -
How to fix: 'TypeError: expected string or bytes-like object' when doing unit test on a views.py function
I'm writing a test for a function that returns a JSONResponse. The function works fine on the website but the test always raises a TypeError. It looks like the program fails to get an entry from the database and returns an error instead. views.py: def check_availability(request, id): if request.method == "GET": response_data = {} event_date = request.GET.get('event_date', False) check = None try: try: speaker = Pembicara.objects.get(id = id) filtered = Booking.objects.filter(speaker = speaker) check = filtered.get(event_date = event_date) except ObjectDoesNotExist as e: pass except Exception as e: raise e if not check: response_data['available'] = 'ok' else: response_data['available'] = 'no' except Exception as e: raise e return JsonResponse(response_data) tests.py: def test_date_availability_is_checked(self): p = self.createPembicara() c = Client() date = datetime.date.today() # request = c.get('/profile/1/check_availability/', event_date=date) b = self.createBooking() request = c.get('/profile/1/check_availability/', event_date='1999-12-20') self.assertEqual(request.status_code, 200) self.assertJSONEqual(request.content, {'available': 'ok'}) terminal: Creating test database for alias 'default'... System check identified no issues (0 silenced). ./Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/BookaSpeakers/static/ warnings.warn(u"No directory at: {}".format(root)) E....... ====================================================================== ERROR: test_date_availability_is_checked (speaker_profile.tests.ProfileTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/tests.py", line 69, in test_date_availability_is_checked request = c.get('/profile/1/check_availability/', event_date='2000-12-20') File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 535, in get response = super().get(path, data=data, secure=secure, **extra) File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", … -
Django communicating with another python application?
Is it possible to have django running on the server and one application from django inter communicating with another python process say that I developed and fetching a response from it or even make it just do a particular action? It can be synchronous or asynchronous; I have some idea of being asynchronous where some package like hendrix, crossbar.io or even celery can be used. But I don't understand what would be the name for this inter-communication and how should I plan the architecture for this. Going around my head I have the two following situations I'm seeking a plan to be developed: 1. Say I have django and an e-mail sender with the python package smtp. A user making a request to a view would make django execute my python module I developed for sending an email to a particular user (with a smpt server from google/gmail). It could be synchronous or asynchronous. OR 2 I have django (some application) and I want it to communicate with some server I maintain; say for making this server execute some code or just fetch a file (if it is an ftp server). Is this an appropriate situation to point to the … -
Pushed Django project to GitHub with Pycharm - now not working
Sorry for the generic question; I'm not sure how to best classify the problem. I had a Django project that I was working on locally, then I pushed up to GitHub to collaborate with someone (I'm completely new to GitHub). I did this using pycharm and the project was copied into a subdirectory of PycharmProjects. It seemed to work fine. I didn't work on it for a week or so, during which time I upgrated to Catalina. I've come back to work on the project and it's completely broken! I can't get the development server up and running from either the PycharmProjects directory or my original working directory on the desktop. I suspect in the PycharmProjects folder it's a path or dependency problem, but I didn't change anything in my original folder. I can activate the virtual environment, then I get these errors: (ll_env) Davids-MacBook-Pro-2:POM_Journal_Club davidhallsworth$ python manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax (ll_env) Davids-MacBook-Pro-2:POM_Journal_Club davidhallsworth$ python3 manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent … -
drf saving objects in database
I am overriding post() method of generic views in DRF but. When I send request it saves two objects in django admin instead of one. class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer # def perform_create(self, serializer): # serializer.save(user=self.request.user) def post(self, request, pk=None, *args, **kwargs): try: user = self.request.user product = Product.objects.get(pk=request.data['product']) quantity = int(request.data['quantity']) except Exception as e: print(e) return Response(status=400) existing_cart_product = Cart.objects.filter(user=user, product=product).first() if existing_cart_product: existing_cart_product.quantity += quantity existing_cart_product.save() else: new_cart_product = Cart.objects.create(user=user, product=product, quantity=quantity) new_cart_product.save() serializer = CartSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user=self.request.user) return Response(serializer.data) if I send post request it saves two objects in admin panel. For example { "product": 1, "quantity": 1 } here two objects are saved with one post request. If again I am going to post same product and same quantity. The objects number will be 3 but last one that is checked in here quantity is 2. More clearly, When I post same product and same quantity it is incremented by one and last checked one's quantity is also incremented by one. The problem is I do not need that one. I need to save only one object when I post and If I add same product the quantity should be incremented by … -
django-rest-swagger UI doesn't have form for POST request body (function based view)
I have this function-based view with django-rest-swagger decorated. However, I can't find place in UI that allow me to post the payload (request.body). I saw a couple solutions about doing it with class-based view, but I was wondering if there is a way to do it with function-based view. Thank you in advance! @renderer_classes([JSONRender]) @api_view(['POST']) def some_method(request): body = json.loads(request.body) return JsonResponse({'status': 'ok'}) -
I am trying to create a graphql mutation , where i cannot add the categoryNode as a input feild to AddEquipment mutation
category model this my category model class Category(models.Model): _id = models.ObjectIdField(primary_key=True) name = models.CharField(max_length=100) Category node I've created a category node using relay class CategoryNode(DjangoObjectType): class Meta: model = Category filter_fields = ['name', 'equipments'] interfaces = (relay.Node,) add equipmemt mutation while mutation i need to add a category object to equipment object in mutation inputs class AddEquipment(relay.ClientIDMutation): class Input: name = graphene.String(required=True) category = graphene.Field(CategoryNode) equipment = graphene.Field(EquipmentNode) @classmethod def mutate_and_get_payload(cls, root, info, **inputs): equipment_instance = Equipment( name=inputs.get('name'), category=inputs.get('category') ) equipment_instance.save() return AddEquipment(equipment=equipment_instance) by this code iam getting error like this class AddEquipment(relay.ClientIDMutation): class Input: name = graphene.String(required=True) category = graphene.Field(CategoryNode) equipment = graphene.Field(EquipmentNode) @classmethod def mutate_and_get_payload(cls, root, info, **inputs): equipment_instance = Equipment( name=inputs.get('name'), category=inputs.get('category') ) equipment_instance.save() return AddEquipment(equipment=equipment_instance) -
How can I run my python selenium scripts using browser?
I've written python selenium script on Django framework. Now I have no clue how can i run the test case using browser. I can execute the test case through terminal. Now i need to execute the same test case through browser. Like with URL i need to start executing the test case -
Is there any way to get the step-by-step solution in SymPy by myself coding?
2x^3+x^2-x+y : Steps for Derivative: 1. The derivative of the constant y is zero. 2. Apply the power rule: x2 goes to 2x 3. The derivative of a constant times a function is the constant times the derivative of the function. - Apply the power rule: x goes to 1 - So, the result is: −1 4. The derivative of a constant times a function is the constant times the derivative of the function. - Apply the power rule: x3 goes to 3x^2 - So, the result is: 6x^2 The answer is: 6x^2 + 2x − 1 -
Django fixture 'python manage.py loaddata' in a UTF-8 format?
I currently have a fixture file in a json format and it's based on utf-8. So when I view the file in VSC, I can successfully read the Korean letters. However, when I try to fill in the Django DB (SQLite) with the python3 manage.py loaddata (fixturefilename) command, and try to view the DB contents with the following view method, def see_list(request): if request.method == 'GET': all_list = [item for item in Item.objects.all().values()] return JsonResponse(all_list, safe=False) I only see \ud544\uc694\u2461 these kinds of output and no Korean. Is there a way to loaddata based on utf-8? -
Add model field to non-model serializer in Django
I'm using Django 2.x I have a serializer for validating the request. (Not ModelSerializer) class ExecuteSerializer(serializers.Serializer): database = serializers.IntegerField(required=True) query = serializers.CharField(required=True) user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) def validate(self, attrs): user = attrs.get('user', None) try: database = Database.objects.get(pk=attrs.get('database', None), collection__user=user) except Database.DoesNotExist: raise ValidationError({ 'database': ['Does not exists'] }) attrs['database'] = database return attrs database is reference to the Database model. I want user to pass the database id in the database field but got is converted to database object after validation. I tried to override the validate() method and assign the database object to the database field but it gives error TypeError: int() argument must be a string, a bytes-like object or a number, not 'Database'