Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send data to "views.py" in django with some data
Here is My html from where i am sending data <div class="advanced-search"> <!-- <button type="button" class="category-btn">All Categories</button> --> <select class='category-btn col-12' id='Catagory_search'> <option value="Shop">IN SHOP</option> <option value="Blog">IN BLOG</option> <option value="Faq">IN FAQ</option> </select> <form action="" class="input-group" style="float: right;" id='AdvancseSearch'> <input type="text" name='search' placeholder="What do you need?"> <button type="submit"><i class="ti-search"></i></button> </form> </div> Here the Ajax With which i am sending GET request with data (search) $('#AdvancseSearch').on('submit', function(e) { ctg = document.getElementById('Catagory_search').value $.ajax({ type: 'GET', async: true, url: "/Search/serach/" + ctg, data: { 'search': $('input[name=search]').val() }, encode: true, }) }) The views.py function which will redirect def Search(request,ctg): search = request.GET.get('search') if ctg == "Shop": d = Item.objects.filter(item_titile__icontains=search) send_dict = {'items':d} return render(request,'home/product.html',send_dict) The problem is that that when i send data to my views.py it succesfully send data "search" but it will not RENDER me to my desire (home/product.html) page it stay on current page -
How to chain Django querysets and sort the result by different fields of those querysets
The reason I need this is to show activity thread in reverse chronological order. I achieve that by chaining multiple objects into one and then displaying in one place. Currently I have: contacts = User.contact_created_by.all() companies = User.company_created_by.all() tasks = User.tasks_created_by.filter(isComplete=True) activity = sorted( chain(contacts, companies, tasks), key=lambda instance: instance.created_on, reverse=True) But I need tasks to be sorted by "completion_date" and not by "created_on" date in the resulting object. I tried this for lambda function: key=lambda instance: instance.complete_date if (isinstance(instance, Task)) else instance.created_on, reverse=True) but since "contact" and "company" models do not have "complete_date" fields, I get an error. Basically the problem is to combine different objects and sort them by different fields (but same type - date!). For example, I further plan to add "event" object to the project which would need to be shown in activity thread, with some type of "event_date". -
How does one disable USE_THOUSAND_SEPARATOR for only one variable in a template?
My settings.py has USE_THOUSAND_SEPARATOR = True because that's generally what I want in my templates. However, what can I do to prevent this default behaviour for only one of my variables in a template? {{ project_id }} currently prints "9,324", but I want it to display "9324" instead. Cheers! -
Why i am not accesing reset passsword URL before login can you tell me how i access
How i access below urls before login i accessed after login below urls anyone tell me what mistake i doing i dont know please tell me how i solve this bug.................................................................................................................................. urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="registration/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="registration/password_reset_done.html"), name="password_reset_complete"), -
Django - request.get.data get only ID instead of Object
I'm having issue when try to update related data in Django. the error is Field 'id' expected a number but got a bunch a object. My Question how do i get only id instead of objects. For Example: { "id": 7, "interviewer": "fdafddfafdsa", "interview_date": "2020-05-05", "interview_phone": "1321321", "created_at": "2020-07-03T18:21:52.785170Z", "partner": { "id": 1, "name": "fda", } }, I want to get only id of partner. In My ModelViewset class IncidentViewset(viewsets.ModelViewSet): queryset = Incident.objects.all() serializer_class = IncidentSerializer def create(self, request, *args, **kwargs): partner_id = request.data.ge('partner') # return HttpResponse(partner_id) try: instance = Incident.objects.get(partner_id=partner_id) except Incident.DoesNotExist: instance = None serializer = IncidentSerializer(instance, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) Any help will be appreciate, thanks... -
Can Django display data from multiple tables (Models/Classes) on a single page?
This is based on the Django Tutorial (https://docs.djangoproject.com/en/3.0/intro/tutorial01/) to build a "Polls" app. It's essentially a Question model and a Choice model. The Choice model is linked to Question through a foreign key (named 'question'). After completion of the tutorial, I thought I'd try to add a specific functionality to the app: On a single html page, display a list of all the questions, with their associated choices underneath each question. (Displaying the number of votes for each choice as well would be a plus but not necessary at this point.) Something like this would be an ideal page display. Right now, I can display ALL questions (with NO choices) on a page -OR- ONE question with ALL associated choices on a page. I cannot seem to display ALL the questions AND their choices on a single page. The below is based on the similar questions and responses I could find as well as the djangoproject.com documentation. models.py: import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text <...etc: additional code here about pub_date...> class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def … -
Check the uniqueness of email. registration django
I am trying to create a registration on django. I can’t check the uniqueness of the email field during registration. ursl.py path('accounts/register/', MyRegisterFormView.as_view(), name="register"), forms.py class Register(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] views.py class MyRegisterFormView(FormView): form_class = Register success_url = "/accounts/login/" template_name = "registration/register.html" def form_valid(self, form): form.save() return super(MyRegisterFormView, self).form_valid(form) def form_invalid(self, form): return super(MyRegisterFormView, self).form_invalid(form) How can this be realized? if User.objects.filter(email=email).exists(): messages.error(request, "Эта почта уже зарегестрированна") I understand that you need to compare the email with the filter and if it matches, return an error, but I can not implement this. How can I access the email form field in views? -
Is django + database enough for complete backend development?
I have been learning djnago and wondered if this is the only thing to matser backend...i know there are other frameworks such as node and ruby.but considering the fact that i want to use only django as my backend framework are these neccessary to learn ..if not what all should i learn along with django for a complete backend package keeping the framework as django. -
why only one variable or form passing to the template django
my form is passing but not the brand here is my views.py ''' class index(View): template_name = 'homepage/columntemplate.html' #form_class = MyForm def get(self, request,*args, **kwargs): #for _ in range (10): # value = randint(0,10) brand = Brand.objects.get(pk=randint(1,2)) brand_listing ={'brand' : brand} return render(request, self.template_name, brand_listing) def get(self, request, *args, **kwargs): form = Search(request.GET or None) if form.is_valid(): form.save() content = {'form' : form} return render(request, self.template_name, content) ''' my template has both tags {{brand}} and {{form}} -
Expressions can only be used to update, not to insert
i got this issue when trying to create object using Factory boy and unittest.mock for mocking payment self = <django.db.models.sql.compiler.SQLInsertCompiler object at 0x7f5aa2913400>, field = <django.db.models.fields.CharField: card_id> value = <MagicMock name='call_tap_api().get().resolve_expression()' id='140027256369728'> def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, 'resolve_expression'): value = value.resolve_expression(self.query, allow_joins=False, for_save=True) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' > 'can only be used to update, not to insert.' % (value, field) ) E ValueError: Failed to insert expression "<MagicMock name='call_tap_api().get().resolve_expression()' id='140027256369728'>" on tap.TapSubscription.card_id. F() expressions can only be used to update, not to insert. /usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1171: ValueError -
Can i host a django website on google drive? If yes how?
I have a dynamic django website and wants it to lauch it using google drive. -
Fixing Bug to get sold quantity of an item not total order with the item to reflect in Template
I am trying to get the total no. of a sold item after payment is made. When the order is paid ordered = models.BooleanField(default=False) become True I have reach to the point where I am getting the total no. of orders with the item not the total quantity of the order. I have also tried to add the quantity in the order item but I get a 'Item' object has no attribute 'orderitem' so i commented it for your reference I know the solution might be simple but I can't figure it out Here is the item model class Item(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title @property def count_sold(self): return self.orderitem_set.filter(ordered=True).count() # return self.OrderItem.quantity_set.filter(ordered=True).count() Here is the OrderItem model: class OrderItem(models.Model): ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) Here is the template <tr> td>No. of Sold:</td> <td>{{ item.count_sold }}</td> </tr> -
Django mocking HTTP requests for testing purposes error
I am trying to test some HTTP reqs on Django. The function that is making the requests (lets say it is called reqs() ) is this: try: response = requests.request('POST', url, data=json.dumps(payload), headers=headers, params=querystring) data = response.json() if response.status_code == "200": alpha.pending_sync = False alpha.latest_sync = datetime.now(timezone.utc) alpha.save() except requests.exceptions.RequestException as e: app_logger.exception("Failed sync, error: %s" % e) Now on the test part i wrote this one: with patch('requests.request') as mock_request: mock_request.return_value.status_code = "200" reqs(alpha) mock_request.assert_called() Everything works fine but there is a problem with alpha.save() and mock.response. I get an error django.core.exceptions.FieldError: Aggregate functions are not allowed in this query. Probably i need to mock a response so the alpha.save() takes that response and not some MagicMock stuff. Also i found this one ref but i did not manage to get anything working. Any ideas ? -
How to convert blob into image to preprocess and recognition in flask or django?
I am working on a Project which involves real-time video streaming and gesture recognition. however, I found lots of resources to get a real-time video stream from client-side to server-side, but nothing works fast and simple to implement. I have tried AIORTC, but I don't understand. I don't know how to use webRTC in Django or Flask for such a task, please help me if you have any kind of idea about webRTC with python. Or help me to resolve this issue, I am trying to get frames from javascript to flask as a blob, but I don't know how to recreate image from a blob, I have tried base64.b64decode() but it doesn't work. here is my getImage.html file <!DOCTYPE html> <html> <head> <title>Post an Image test</title> <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> </head> <style> /* mirror the image */ video, canvas { transform: scale(-1, 1); /*For Firefox (& IE) */ -webkit-transform: scale(-1, 1); /*for Chrome & Opera (& Safari) */ } </style> <body> <video id="myVideo" height="480" width="640" autoplay></video> <script> let v = document.getElementById("myVideo"); //create a canvas to grab an image for upload let imageCanvas = document.createElement('canvas'); let imageCtx = imageCanvas.getContext("2d"); //Add file blob to a form and post function postFile(file) { let formdata … -
i want to Retrieve data from Django API and store it in database
i am new in django restframework.get request works fine the data from database is retrived in client but while doing the post request no any data is added. i want to retrieve the data from react axios from django api and store it in database. it is not showing any error but it is also not adding the json data in database. here is views.py class formAPI(APIView): def get(self,request): if request.method=='GET': formData=Form.objects.all() serializer=FormSerializer(formData,many=True) return Response(serializer.data) def post(self,request): if request.method == 'POST': data_Serializer = FormSerializer(data=request.data) if data_Serializer.is_valid(): data_Serializer.save() return Response(data_Serializer.data,status=status.HTTP_201_CREATED) return Response({'key': 'value'}) here is models.py from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Form(models.Model): Province=models.CharField(max_length=100,null=False) District=models.CharField(max_length=100,null=False) PalikaType=models.CharField(max_length=100,null=False) PalikaName=models.CharField(max_length=100,null=False) Ward_No=models.CharField(max_length=100,null=False) Ward_Office_Address=models.CharField(max_length=100,null=False) Ward_Contact_No=PhoneNumberField() X_Cords=models.FloatField(null=False) Y_Cords=models.FloatField(null=False) Chairperson_Name=models.CharField(max_length=100,null=False) Chaiperson_Contact_No=PhoneNumberField() Secretary_Name=models.CharField(max_length=100,null=False) Secretary_Contact_No=PhoneNumberField() Area=models.FloatField(max_length=100,null=False) Total_Households=models.IntegerField(null=False) Total_Population=models.IntegerField(null=False) Total_Male_Population=models.IntegerField(null=False) Total_Female_Population=models.IntegerField(null=False) Website= models.URLField(max_length=200) Email=models.EmailField(max_length=254) location= models.PointField(srid=4326,null=False) def __str__(self): return 'PalikaName: %s' % self.name here is the data to be stored { Province: "province 1", District: "bhaktapur", PalikaType: "gaupalika", PalikaName: "madhyapur gaupalika", Ward_No: "5", Ward_Office_Address: "balkumari", Ward_Contact_No: "+9779818523950", X_Cords: 85.385252, Y_Cords: 27.675952, Chairperson_Name: "kumar sanu", Chaiperson_Contact_No: "+9779815523950", Secretary_Name: "ranja", Secretary_Contact_No: "+9779813523950", Area: 784.0, Total_Households: 422, Total_Population: 32, Total_Male_Population: 224, Total_Female_Population: 124, Website: "http://madhyapurthimimun.gov.np/en", Email: "info@madhyapurthimimun.gov.np", } here is urls.py from django.contrib import admin from … -
Access a single object from Database ListView using Django
I have a class that passes in a django ListView. From this ListView I can access my DB items. My problem is that accessing the db using the list view will load all the entries. what if I just want one entry, say the 5th entry for example. Maybe listView is the wrong type of view to be using? my code below work and shows my DB entries on-screen as a list. models.py from django.db import models class Datadata(models.Model): text = models.TextField() views.py class HomePageView(ListView): model = Datadata template_name = 'hello.html' templates/hello.html {% for post in object_list %} <h1>{{ post.text }}</h1> {% endfor %} -
How to add href in HTML by using Python loop for each member in loop?
[help me in this, i tried to loop my href link for each member in list but somehow i didn't get my solution https://i.stack.imgur.com/mkDm0.jpg -
Django: Database
Before i start planning on how my database schema will look like, i was wondering Let's say for example i decide to make a web app with lots of models, one of those models holds mp3 audio. Won't my web app become too heavy and slow if all that information is stored within the web app itself? Is there a way i can use an external database to supply the data, if true(No pun intended) what server would you recommend to me and which SQL type NB im looking for something highly scalable -
How to remove the forms in django formset that successfully passed validation?
I have a survey where people answer a bunch of control questions (to get if they understand instructions correctly). So each participant has a bunch of instances from Question model, that contains the answer field. And the system does not let them go through unless they provide a correct answer (using Validator) Let's say they have 10 questions, which I show them as a formset. In views I do it like that: class MyView(View): def get_queryset(self): return self.participant.cqs.filter(answer__isnull=True) def get_formset(self, data=None): return cq_formset(instance=self.participant, data=data, queryset=self.get_queryset()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = self.get_formset() return context (basically just filter out all questions that which are not answered yet (answer__isnull=True). So let's say I have 10 questions with no answers at the beginning. They are shown, a person answers 5 out of 10 correctly, they are saved (not shown here), and the page should be re-shown again with the rest 5. But it does not work. The correctly answered questions are shown again with the 'wrong' ones. What am I doing wrong? Apparently it's because the formset does not request a new queryset after it fails validation. TL;DR: how to removed the forms in django formset that successfully passed validation? -
How to make django-organizations' custom invitation work
I am trying to make the Django-organization's custom invitation work. But it's throwing an error. I am unable to find the reason. Below is my code: My urls.pyfile from django.urls import path, include from organizations.backends import invitation_backend urlpatterns = [ path('accounts/', include('organizations.urls')), path('invitations/', include(invitation_backend().get_urls())), ] In my settings.py file I have added the 'organizations' app and my custom app 'integration' in the installed app section. There needs to be added a backend for the custom invitation which is guided in the following link: https://django-organizations.readthedocs.io/en/latest/custom_usage.html#creating-the-backend Here is the specified backend. INVITATION_BACKEND = 'integration.backends.CustomInvitations' My backends.py file from organizations.backends.defaults import InvitationBackend class CustomInvitations(InvitationBackend): def invite_by_email(self, email, sender=None, request=None, **kwargs): try: user = self.user_model.objects.get(email=email) except self.user_model.DoesNotExist: user = self.user_model.objects.create(email=email, password=self.user_model.objects.make_random_password()) user.is_active = False user.save() self.send_invitation(user, sender, **kwargs) return user And here is the error occurring: Traceback (most recent call last): File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\organizations\mixins.py", line 111, in dispatch return super(AdminRequiredMixin, self).dispatch(request, *args, File "H:\Hobby\Project\django_org\orgenv\lib\site-packages\django\views\generic\base.py", line … -
python condition that checks if attriibute is not none errors that it is none
I have the following condition that checks to see if an object has populated value for the id attribute: if getattr(instance, 'id', True): asdf = instance.id This should filter any instances that do not have an ID. However I get the error: 'Session' object has no attribute 'id' on line: asdf = instance.id How can the None instance.id line ever be reached? -
How to chose variables in Python program from a ReactJs app
I have a python program that connects to an API and gets some data that it processes and then returns. The data is dependent on some variables in the python program. I also have a ReactJs front-end that I'm writing to have buttons where the variables can be chosen. I'd like the variable choice to be sent to my python program and the result of the data processing to then be sent back to the react front-end to be seen by the user. I'm a complete beginner so don't even know if this is possible. I've seen something about flask serving react but I'm not sure if this is applicable to what I'm trying to do. Is flask the way to go or is what I'm trying not possible? Thank you!! -
mock http request on django for testing purposes
I am trying to test some async celery tasks that perform some HTTP requests. This is the part of the async task (sync_contact.py) that performs the HTTP reqs try: response = requests.request('POST', url, data=json.dumps(payload), headers=headers, params=querystring) data = response.json() if response.status_code == "200": user.pending_sync = False user.save() except requests.exceptions.RequestException as e: app_logger.exception("Some log info here") Now on the testing part. I mocked a user and the HTTP req. I call the task which calls the mocked HTTP request. Everything fine by then. What i would like to check is that in the main functionality when the response is 200 the user.pending_sync changes from True to False but i cannot replicate this change on a test. with patch('requests.request') as mock_request: sync_contact(user) mock_request.assert_called() mock_request.return_value.status_code = 200 Any ideas ? -
I am trying to make friend system in django and getting problem in database
I am making a friend system when I make a friend that works successfully but when I add the following table I get an error like these and please if any can tell me how I can able to track who is following me. I am attaching the code below. Here I am using a friend model for making collecting friends and followers and change_friends function in view for adding or removing friends django.db.utils.OperationalError: no such column: users_friend_following.friend_id models.py from django.contrib.auth.models import User class Friend(models.Model): users = models.ManyToManyField(User,related_name='user') following = models.ManyToManyField(User,related_name='following') current_user = models.ForeignKey(User, related_name='owner', null=True,on_delete=None) @classmethod def make_friend(cls,current_user,new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) friend.following.add(new_friend) @classmethod def loose_friend(cls,current_user,new_friend): friend,created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) views.py from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from .forms import UserRegisterForm from .models import Friend def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created Login Now!') return redirect('login') else: form = UserRegisterForm() return render(request,'users/register.html',{'form':form}) def show_friends(request): users = User.objects.exclude(id=request.user.id) try : friend = Friend.objects.get(current_user=request.user) following = Friend.objects.get(current_user=request.user) followings = following.following.all() friends = friend.users.all() except Friend.DoesNotExist: friends=None followings=None … -
Django view processing too slow
In my Django App I have a view that takes too much time to deliver and I can’t realize exactly why. Maybe there is a way to optimize this process. The scheme I load a page regularly with View 1 and when that page is ready $(document).ready(function() I load a Json with the rest of the data via AJAX from View 2. That View 2 is taking too much to deliver the result although we are talking of only around 180 queryset lines. Even more, I have server cache setup so the actual database is not consulted. Both server cache and general app server works fine, the rest of my app’s views deliver results in low times. You can check: www.kinemed.com.ar The AJAX call I guess the problem isn’t here, but just in case. $(document).ready(function(){ $.ajax({ url:'/website/some/', type:'GET', data: {}, success:function(data){ window.data = JSON.parse(data); makeMenu(data); }, error:function(){ console.log('something went wrong here'); }, }); }); The View 2 As you can see. The “Productos” queryset is loaded from cache, but event If it wasn’t, the amount of data is low. The full “ProductosBase” model hast around 600 items and after filtering we get only around 180 items. @transaction.atomic def ShopSegundoPlanoView(request): productos …