Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why flutter is unable to send data using POST method to django rest api?
This is my part of code in auth.dart: Future<void> signup(String username,String email, String password) async { final url = 'https://ymukeshyadavmrj.pythonanywhere.com/register/'; try { final jb = jsonEncode({ 'username': username, 'email':email, 'password':password, 'password2':password, }); print(jb); final response = await http.post(url,body:jb); final responseData = json.decode(response.body); if (responseData.containsKey('code')) { throw HttpException(responseData['message']['message']); } _token = responseData['access']; print("Token =======$_token"); _refreshToken = responseData['refresh']; It is returning null on printing _token after assigning it responseData['access']. Note: I am using jwt authentication for my project and api is working fine in Postman. -
Django - JQuery autocomplete custom select from multiple fields
I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}". Here is my python code: if 'term' in request.GET: tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term')) companies = [] for ticker in tickers: companyTicker = ticker.ticker + " - " + ticker.name companies.append(companyTicker) return JsonResponse(companies, safe=False) and here is my javascript: <script> $( function() { $( "#ticker3" ).autocomplete({ source: '{% url "financials:get_financials" %}' }); $( ".selector" ).autocomplete({ select: function ( event, ui ) { ticker.ticker } }); $( ".selector" ).on( "autocompleteselect", function( event, ui ) { ticker.ticker }); } ); </script> Any help greatly appreciated! -
Unable to assign a Foreign Key in DJango
I am trying to save data into a mysql database using 2 tables main and public, but am unable to store data into the public table. ERROR: ValueError: Cannot assign "4": "public.unq_id" must be a "main" instance. Models.py: class main(models.Model): unq_id = models.BigAutoField(primary_key=True) email = models.CharField(max_length=80) password = models.CharField(max_length=256) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) dob = models.CharField(max_length=80) phone = models.BigIntegerField(default=0) status = models.CharField(max_length = 12, default = 'active') def __str__(self): return self.unq_id def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password) class public(models.Model): unq_id = models.OneToOneField(main, on_delete=models.CASCADE, primary_key = True) lang = models.CharField(max_length=80) expert = models.CharField(max_length=80) country = models.CharField(max_length=80, default = "None") Views.py: Email1=request.POST['Email'] a = main.objects.filter(email = Email1).exists() if a is True: error = "Email taken" return render(request, 'Main/registration.html',{'error':error}) password1=request.POST['password'] password = pbkdf2_sha256.encrypt(password1,rounds=12000,salt_size=32) Fname=request.POST['Fname'] Lname=request.POST['Lname'] DOB=request.POST['dob2'] lang= request.POST['lang'] phone=request.POST['phone'] c = main.objects.filter(phone = phone).exists() if c is True: error = "phone number taken" return render(request, 'Main/registration.html',{'error3':error}) country=request.POST['country'] r = countrycode.objects.filter(country = country).exists() if r is True: s = countrycode.objects.get(country = country) country = s.code main2=main(email=Email1,password=password,first_name=Fname,last_name=Lname,dob=DOB,phone=phone) main2.save() mainobj= main.objects.get(email = Email1) public2=public(lang=lang,expert="false",country=country,unq_id=mainobj.unq_id) public2.save() When I look in my database, the mainobj gets stored but the public object doesn't get saved; despite having the same "unq_id" Please do help , thank you -
Why the hell django custom auth is tough for beginners?
I recently got my first freelancing project in django - the requirement is simple ( i dont wanna say fully). It has a simple auth and dashboard has few functions thats it ! But the problem here is - clients asking for registration with the following fields: Name Phone Email And other defaults like password etc ! I have seen 100's of youtube videos, everyone is using default django auth but no one is clearly explaining how to use custom user model to authenticate ? Please someone help me to understand what are the steps to be followed ! Figured out steps: - We need to use AbstractBaseUser & UserManager in customusers model and create two class inherit - Then need to admin respective admin things and add as per documentation But how to perform email verification, and if i use above things - then will i be able to use all auth functions in django like to check if authenticated etcs ? How the permissions works if i use to custom model - like this there are 1000's questions with unknow answer ! Totally getting frustrated as a beginner freelancer Please help -
Google Cloud App Engine Deploy Fail (Django)
I'm trying to deploy my app but I keep getting this error on the website: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. The error logs for this are: 2021-07-15 12:36:04 default[20210715t122912] [2021-07-15 12:36:04 +0000] [20] [INFO] Worker exiting (pid: 20) 2021-07-15 12:36:04 default[20210715t122912] [2021-07-15 12:36:04 +0000] [23] [ERROR] Exception in worker process 2021-07-15 12:36:04 default[20210715t122912] Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from booking.wsgi import application File … -
Can someone please explain me what exactly going on here? (Django dependent dropdown + ajax)
I am following a tutorial on the dependent dropdown in Django. However not able to understand some lines of code... https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html snippet def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() # have to understand this line of code if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') -
Ajax seems to execute only once
I'm using Jquery's ajax method to update the data on the screen (go to the next data item in the database). When I click the next button I want it to go to the data record with the next id (current_id + 1). It works on the first click but not after that, I'm pretty new to Django and WebDev so let me know if you need any more context. Here's the jquery code: {% block javascript %} <script type="text/javascript"> $(document).on('click','#next',function(){ var id = "{{record.id}}"; console.log(id) $.ajax({ url : "{% url 'next' %}", data : {'id':id}, dataType: 'json', success : function(data){ console.log("success"); console.log(data); $("#word").text(data['word']); $("#meaning").text(data['meaning']); } }) }) </script> {% endblock %} Here's the code for the view that handles the request: def next(response): id = int(response.GET.get('id',None)) record = Words.objects.filter(id = id+1).first() data = { 'word' : record.word, 'meaning' : record.meaning } return JsonResponse(data) -
using class base view facing a issue of reverse not found
i am using a class base d view for section.html in which i trying to implement add to cart functionality with the help of forms but after clicking add to car but it showing error Reverse for 'section' with no arguments not found. 1 pattern(s) tried: ['(?P<subject_id>[0-9]+)/Sections/$'] here is my views.py @method_decorator(login_required, name='dispatch') class Sections(View): def post(self, request, subject_id): sections =request.POST.get('section') print(sections) return redirect('subjects:section') def get(self, request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) # retrieve the subject sections = subject.section.all() # get the sections related to the subject return render (request, 'sections.html',{"section_list" : sections }) my urls.py urlpatterns = [ path('<int:subject_id>/Sections/', Sections.as_view(),name='section'), ] my section.html <ul class="sec"> {% for section in section_list %} <div class="card col-11"> <div class="card-header"> {{ section.title }} </div> <div class="card-body"> <h5 class="card-about">{{ section.about_section }}</h5> <br> <i class="price fas fa-rupee-sign"> {{ section.price }}</i> <br> <br> <i class="icon text-white fas fa-chalkboard-teacher"> {{ section.teacher }}</i> <i class="icon text-white fas fa-clock"> {{ section.content_duration}}</i> <i class="icon text-white fas fa-tags"> {{ section.subject.name }}</i> <form action="#" method="POST"> {% csrf_token %} <input hidden type="text" name="section" value="{{section.id}}"> <input type="submit" class="btn btn-outline-primary" value="Add To Cart"> </form> </div> </div> {% endfor %} </ul> my section model is contected with another models name subject with foriegn key -
Question about getting an IP address in Genie
I am a novice in Django and I got this code from a specialist, but I do not know how it works and how anyone can explain how it works? def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip -
Annotate Sum in Django
gap_condition = Feedback.objects.filter(Q(register_date__gte='2020-05-01')) \ .annotate(gap=(Cast('create_at', DateField()) - F('register_date'))).values('student_id') register_gap = Student.objects.values('teacher').distinct().order_by('teacher').annotate( gap_chart=Sum('???', filter=Q(id__in=gap_condition)) ).values('teacher', 'gap_chart') First, the gap is output as a queryset. I would like to add the 'gap' obtained above in place of the question mark. However, when I get annotate sum in Django, I get an error saying that I can only select fields from the model I am using. Is there a way to reference fields from other models? The final thing I want to find is the difference between the register date of the students assigned to each teacher and the date the register date was entered into the computer. -
Django Inline Formset Factory Unrequire a field
I'm working on restaurant management system. I'm Taking orders, and add order items to orders with inline formset factory.But for some reason extra fields require an input, and it's annoying because I can't submit my form unless I fill all the fields.I'm pretty new to formsets so any help/suggestion is appreciated. Here is my views.py : class OrderOrderItemView(SingleObjectMixin, FormView): model = Order template_name = 'order/add-order_item.html' def get(self, request, *args, **kwargs): self.object = self.get_object(queryset=Order.objects.all()) return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object(queryset=Order.objects.all()) return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return Order_OrderItemFormset(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): orderitem_instance = form.save() for order_item in orderitem_instance: food = order_item.food_size.food order_item.food = food order = Order.objects.get(id=order_item.order.id) order_item.total_cost += str(float(order_item.food_size.price) * float(order_item.quantity)) order.total_cost = float( order_item.total_cost) + order.total_cost order.save() order_item.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('menu:detail-order', kwargs={'pk': self.object.pk}) And my forms.py: Order_OrderItemFormset = inlineformset_factory( Order, Order_Items, fields=('food_size', 'quantity'), extra=5, can_delete=False) -
Django model inheritance column check
I'm working on a game website with multiple different gamemodes. I have basemodel that I want to generate unique join link for each model that inherits from basemodel.py. from django.db import models import random import string class Room(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) description = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) @classmethod def generate_join_code(cls): while True: unique_code = ''.join(random.choices(string.ascii_uppercase, k=6)) if cls.__name__.objects.filter(join_code=unique_code).count() == 0: break return unique_code join_code = models.CharField(max_length=6, default=generate_join_code) class Meta: abstract=True And the other file that inherits from the Room model: from core.basemodel import Room class tttRoom(Room): pass I can't find a way to pass a specific model name into generate_join_code. It has to check the current model that it works on and I need a way to pass that information into it. And when I run python manage.py makemigrations it raises AttributeError: module 'core.basemodel' has no attribute 'generate_join_code'. Is there any way to create join_code automatically or I need to create it each and every time I add a new model? I don't need the join_code to be unique for all the database but just for that table that uses it. Thanks in advance -
Running Django applications on white ip
I got a white ip from my ISP, it's 195.214.223.143 I have an application with microservices, which all I want to run on this IP. I have a main server app (which I will deploy with nginx and gunicorn) and 6 microservices (user-service, session-service, mail-service and so on), which I want to deploy only with gunicorn (just cause endpoints from these services can be called only through main server, so I don't really care about outside attack). Now for tests I try to run services only with gunicorn (I use a dedicated laptop for this purpose). I use such a command to run every service "gunicorn --bind 0.0.0.0:PORT --workers 4 APPNAME.wsgi" (4 workers cause I have cpu with 2 cores (i3)) So I set this in every project: ALLOWED_HOSTS = ['195.214.223.143', '127.0.0.1', '0.0.0.0'] I also use TP-Link router and I used "Port Forwarding" tab in settings to forward ports (8000, 5000, 5001, 5002, 5003, 5004, 5006). So when I run all this stuff I can reach my app with localhost url and with http://195.214.223.143:5001 (that's url for my main server). But trouble is that I can't get stable using of my ip on another devices. Sometimes I can open my … -
set category in product using apis rest framework
I want to set category in product using category that exist not creating a new one but i get this response. "category": "slug": "product category with this slug already exists." this is view : def creat_product_view(request): user = request.user product = Product(user=user) data = {} if 'category_slug' in request.data: try: category = ProductCategory.objects.get(slug=request.data['category_slug']) except ProductCategory.DoesNotExist: data['response'] = 'category dose not exist' return Response(data=data, status=status.HTTP_404_NOT_FOUND) request.data['category'] = CategorySerializer(category).data else: request.data['category'] = CategorySerializer(ProductCategory.objects.get(slug='another')).data serialized_data = ProductSerializer(product, data=request.data) if serialized_data.is_valid(): product = serialized_data.save() data['response'] = 'successfully created' data['title'] = product.title data['cost'] = product.cost data['description'] = product.description data['slug'] = product.slug else: data = serialized_data.errors return Response(data=data) serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = ProductCategory fields = "__all__" class ProductSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='email' ) category = CategorySerializer(many=False) class Meta: model = Product fields = "__all__" -
Display ManyToManyField in Django Admin Detail view
I have a model Order which has a ManyToManyField of CartItems. I want to display this in the django admin panel. I tried the following approach: (admin.py) class OrderDisplay(admin.ModelAdmin): list_display = ['get_items'] fieldsets = ( (None, {'fields':('user','completed','time_created')}), ) def get_items(self, obj): return "\n".join(item.item.name + "-" + str(item.quantity) for item in obj.items.all()) By adding get_items in list_display its being displayed as the title of orders in the list. I want the list of items to be displayed when the admin clicks on the order, not on the title. How can I display a ManyToManyField in the DetailView -
create custom user permissions manually django
i'm trying to create custom permissions , for every user(admin) we have several permissions like (delete,creaet,post,update,view a specific part of the app) , every users have multiple permissions class UserPermission(models.Model): type_of_permission = models.CharField(max_length=30,unique=True) active = models.BooleanField(default=True) def __str__(self): return self.type_of_permission class Meta: db_table = 'user_permission' class UserAccount(AbstractBaseUser): username = models.CharField(max_length=80,unique=True) active = models.BooleanField(default=True) permis = models.ManyToManyField(UserPermission) class Post(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) title= models.CharField(max_length=80) for example we have type_of_permission = create new post , active = True type_of_permission = delete posts , active = False and so on ,and a user wants to delete a post , i want to filter users by if request.user has delete posts active = False then dont allow that user to delete the object def delete_posts(request,id=id): obj = get_object_or_404(Post,id=id) #how to filter if the requested user have permission to delete post obj.delete() #if not have permission then messages.error(request,'you dont have permission to delete') is it possible to define permissions manually please ? -
Django filter a related model only if a foreign key is not saved as an attribute
I have the following models: class Route(Model): first_stop = models.ForeignKey( Stop, help_text="The departure point", ) last_stop = models.ForeignKey( Stop, help_text="The destination point", ) class Stop(Model): location = models.CharField(max_length=100) route = models.ForeignKey( Route, related_name="stops", related_query_name="stop", help_text="the route that this stop belongs to", ) a route has at least two stops and references to the first and last stops are kept as attributes. I'm trying to filter routes that pass through a specific location but not just on the first or last stop. If the location is only present on its first or last stop then that route should be excluded. If the location is present on an intermediate stop(not first_stop or last_stop) then that route should be included regardless of whether that location is also present on its first or last stop or not. if a route has only two stops then it should be excluded. I made a solution but it's very verbose and ugly and probably inefficient: routes_to_exclude = [] for route in result: # result is a queryset matched_stops = False for stop in route.stops.exclude( pk__in=(route.first_stop_id, route.last_stop_id) ): # to make sure the desired location isn't only on the first or last stop if str(stop.location) == desired_location: matched_stops … -
PyNamecheap update the contact info
recently I'm using PyNamecheap to register domains as it's registering, but I want to configure my domain contacts information for each Registrant, Administrative, Technical and Billing user. but it doesn't provide the option as looked into their code they are just looping through users contact_types = ['Registrant', 'Tech', 'Admin', 'AuxBilling'] and creating with the same details for all account types. and also there isn't any update userinfo method or anything. is there any way to update or customize them while creation and also later to update. -
Pagination not working in DRF even while extending the class from generics
Pagination does not seem to work for me. I am even extending my class from generics, but still it doesn't seem to work. Here is the code for my class class RequestInvite(ListCreateAPIView): authentication_classes = () permission_classes = () serializer_class = RequestInviteSerializer http_method_names = ['post', 'get'] queryset = User.objects.all() And here is the code snippet for my settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 20 } Haven't used any custom pagination class Even defined a default pagination class Still the pagination just does not seem to work. -
How do i render my list of complaints into cards to be able to view them?
I have built a complaint management system, where the system can accept complaints from the users, view and edit them. The user right now is able to submit the complaints and these get stored in the admin panel. For the view complaints page, I have these cards through which they can view the complaints. How do I do that so that only a certain number of cards are seen on the screen. For eg: If there are two complaints, then the user sees two cards and so on. Also how di I display the information in these cards? I'm guessing it'll be through a list and a for loop and stuff but I don't know how. What should I write in the views.py and the forms.py? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return … -
How To Render An HTML With Css + JavaScript File In Django
Hay, I Have An HTML with Css + JavaScript Page When I Try Rendring This Page In Django Like This: def about(request): return render(request, 'about/index.html') but I Only Get The Html Content Without The Css And JavaScript. I Thought This Might Be Because Of The Statics.. So I Run: python manage.py collectstatic But I Get This: 0 static files copied to 'C:\Users\Ammar\Desktop\Python Learning\vidly\static', 128 unmodified. What Should I Do, I Wish Someone Can Help. -
Extending Django admin delete confirmation page
I am wondering if it is possible to extend Django Admin's delete confirmation page for specific app and model. I want the functionality that enable user to delete all records like that of django admin interface. it is possible to extends delete confirmation.html in my app -
AnonymousUser' object has no attribute '_meta when login by email
I had correct working form to register and login user using username. I add field email to above forms and change to login by email field. Now registered working but login is not. In view sign_in authentication have None value. I have a error 'AnonymousUser' object has no attribute '_meta'. views def sign_up(request): context ={} who ={"teacher": Teacher, "student": Student} form = UserSignUpForm(request.POST or None) context['form'] = form if request.method == "POST": if form.is_valid() and request.POST.get("who"): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() person = who[request.POST.get("who")] person(user=user).save() messages.success(request, f'{user.email} registered succesfull') return render(request, 'registration/sign_up.html', context) return render(request, 'registration/sign_up.html', context) def sign_in(request): context = {} form = UserLoginForm(request.POST or None) context['form'] = form if form.is_valid(): print('test1') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) print(f'email: {email}') print(f'user: {user}') login(request, user) return redirect('/') else: print('test3') attempt = request.session.get('attempt') or 0 request.session['attempt'] = attempt + 1 return render(request, 'registration/sign_in.html', context) return render(request, 'registration/sign_in.html', context) forms class UserSignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserSignUpForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True who = forms.ChoiceField( choices=[('student', 'Student'), ('teacher', 'Teacher')], label="", required=True, widget=forms.RadioSelect( attrs={'style':'max-width: 20em; ', 'autocomplete':'off', }) ) password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Minimum 8 characters")], widget=forms.PasswordInput(attrs={'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", … -
Is Django automatically apply idexing to pk for fast lookups?
I go through some of the blog post and found i can improve my lookup speed using index, and also in some discussion i found that database usually apply auto indexing to the id or pk of the table without running any manual command. I am currently on two projects which has two different dbs Postgres and MySQL any other suggestion for improving the lookup speed for both the dbs will appreciated. -
why we use * args and **kwargs in super.save()
**As i know, *args is a tuppple and **kwargs is a dictionary and the super.save() is used to override the built-in save method and to ensure that the save() is called but i can't understand why we use in here as parameters ** def save(self,*args,**kwargs): super.save(*args,**kwargs)