Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest API unable to connect with React
I have two computers. I made a to-do app in one of them and I copied all of the code to the other. But when I run the code on the other PC, react is unable to find the Django rest API. I followed this tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react Failed to load resource: the server responded with a status of 404 (Not Found) App.js:27 Error: Request failed with status code 404 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62) -
How to search by different parameters with Django REST API?
Suppose I'm developing a backend for an application that will have products or something, and that application will communicate with the server through REST API. Each product will have multiple fields like title, description, price, rating... What are some of the good ways for filtering by multiple fields? Example: Search string: gaming laptop price: from 400$ to 1000$ rating: more than 3 stars ... I was planning to have a single string that confirms pre-defined rules for searching, taking it, parse it, and returning the result. So, the URL would look something like this: www.foo.com/products/search/contains=laptop&min_price=400&max_price=1000&min_stars=3. these filters are optional. Not sure if taking a single string then parsing it is the best way. -
How to update 2 tables in one page in django
Assuming there are 2 tables in one page. table 1 shows the list of all items and table 2 shows the list of all deleted items. whenever i click delete button the corresponding row from table 1 is moved to table 2. I am not sure how to do all these in one page! -
How to solve the problem to use request.user in custom profile fields
- models.py As you can see all code here. I want the user after athenticate had filled the all profile fields but there is 'AnonymousUser' object has no attribute '_meta' error. from django.db import models from django.contrib.auth.models import User class ProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) age = models.PositiveIntegerField() city = models.CharField(max_length=50) country = models.CharField(max_length=50) def __str__(self): return self.name forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import * class UserProfileForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] class ProfileForm(forms.ModelForm): class Meta: model = ProfileModel fields = ['name', 'age', 'city', 'country'] views.py The userprofile is success and when profile request is post then the error arise def userprofile(request): if request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('App_Login:profile')) else: form = UserProfileForm() return render(request, 'App_Login/userprofile.html', {'form': form}) def profile(request): if request.method == 'POST': form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): name = form.cleaned_data['name'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] country = form.cleaned_data['country'] reg = ProfileModel(name=name, age=age, city=city, country=country) reg.save() else: form = ProfileForm(instance=request.user) return render(request, 'App_Login/profile.html', {'form': form}) -
Pull a column from sqlite3 and use those data in django dropdown
----models.py---- This model uses sqlite3 default database of django from django.db import models from django.contrib.auth.models import User class item_master(models.Model): item_name=models.CharField(max_length=200,null=False) item_price=models.IntegerField(max_length=5,null=False) ----views.py---- These are many pages in this django app... "abc.html" is the page which needs drop-down list and "showitems" is the related function. from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.template import loader from django.http import HttpResponse from django import template from app.models import item_master from django import forms from django_select2.forms import ModelSelect2Widget from django.views import generic import sqlite3 @login_required(login_url="/login/") def index(request): context = {} context['segment'] = 'index' html_template = loader.get_template( 'index.html' ) return HttpResponse(html_template.render(context, request)) @login_required(login_url="/login/") def pages(request): context = {} try: load_template = request.path.split('/')[-1] print(load_template) context['segment'] = load_template html_template = loader.get_template( load_template ) if (load_template == "test.html"): items(request) return HttpResponse(html_template.render(context, request)) elif (load_template == "abc.html"): showitems(request) return HttpResponse(html_template.render(context, request)) else: return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template( 'page-404.html' ) return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template( 'page-500.html' ) return HttpResponse(html_template.render(context, request)) def showitems(request): if request.method == "GET": showdrop = item_master.objects.all() return render(request,'abc.html',{"showdrop":showdrop}) ----abc.html---- HTML code for the front end <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" /> <select id="selectitem" class="form-control" > <option selected disabled="True">--- select --- </option> {% … -
Django Product stock goes to 0 but we can still pay | other errors
If my product stock is 0 make sure they can't pay or continue even if it's already in the cart. For ex: We deleted this product from your cart due to it being out of stock or something like that or redirect them back to the home page. If you can explain or give me a tutorial that would help. Also if anyone can checkout my repository. In my cart.html I have it where if they want than more than 1 they can press the + button but they can keep adding more even if we don't have that much in stock it still goes through and they can pay. I know this one is basic but I can't seem to figure out how to do this lol so if anyone can please help I would appreciate that! If anyone wants to fix stuff or add stuff that would help plz do so lol. This is based on a paid course. My github: https://github.com/Gabriel7553/my_shop -
How to convert bytes to json in python
I'm trying to convert bytes data into JSON data. I got errors in converting data. a = b'orderId=570d3e38-d6486056e&orderAmount=10.00&referenceId=34344&txStatus=SUCCESS&txMsg=Transaction+Successful&txTime=2021-06-26+12%3A03%3A12&signature=njtH5Dzmg6RJ1KB' I used this to convert json.loads(a.decode('utf-8')) and I want to get a response like orderAmount = 10.00 orderId = 570d3e38-d6486056e txStatus = SUCCESS -
Why MERN better than React+Flask or React+Django?
I am a student and excited about ML stuff. But most of the time when I reach out to my fellow mates for any project they just tell me that they prefer MERN over React+Flask or React+Django. I haven't got any satisfying answer to this thing though that ,why they prefer MERN, as for me if I want to integrate my ML model with my website I would prefer React+Django/Flask for it. -
what are the best practices in accessing multiple apis in azure active directory
We have created an graphql api in django-graphene. In this api, we have use django-graphql-auth to provide authentication to the user. We have also vue js client application that will let sign up and sign in the user with the help of our created api. However, we've decided also to integrate microsoft to identity platform in order for us to let the user sign in using their microsoft account and we are planning to use microsoft graph. this means, that the user will have two tokens, one for microsoft graph and for our created api. How we should integrate this two apis? -
gunicorn Serve Error(500) in django 3.2 app on localhost
I'm trying to serve my Django 3.2 application using gunicorn on my localhost. First time, it ran correctly. Later, I changed DEBUG parameter to False in settings.py and I run it again. This time it gives me a server error. In terminal there is no error. See the pictures below. Why is this happening ? How to fix this ? Error Page settings.py terminal -
How to send two pk in one url link when Update and Delete
my superb Internet friends. I have been creating an easy pfc calculator Django app as a beginner. While making it, I have got an error, which is "Generic detail view CommentUpdate must be called with either an object pk or a slug in the URLconf." I don't even know why this error showed up coz I think my way in urls.py is correct. If you know how to solve this error, please leave your comment below. Any comments help me and thanks for your time in advance!! # urls.py # path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'), path('blog/<int:blog_pk>/comment/update/<int:comment_pk>/', CommentUpdate.as_view(), name='comment_update'), path('blog/<int:blog_pk>/comment/delete/<int:comment_pk>/', CommentDelete.as_view(), name='comment_delete'), <div class="comment-right"> {% if request.user == blog.user %} <a href="{% url 'comment_update' blog.id comment.id %}" class="far fa-edit"></a> <a href="{% url 'comment_delete' blog.id comment.id %}" class="far fa-trash-alt"></a> {% endif %} </div> # view.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() form = CommentForm() comments = Comment.objects.order_by('-created').filter(blog=blog.id) number_of_comments = comments.count() if blog.link_1 is not None or blog.link_2 is not None: link_1 = blog.link_1 link_2 = blog.link_2 context = { 'blog': blog, 'link_1': link_1, 'link_2': link_2, 'form': … -
【Django】Can't Create Objects while Deploying on Heroku
I was trying to deploy a web that can get titles from a youtube playlist by pytube. Although it works fine at local, it can't work while I deployed it on Heroku. I've checked some possible problems, it can get titles from a playlist, but can't create objects. I also tried to create through admin and it worked. The logs of the web: 2021-06-26T02:01:39.314791+00:00 app[web.1]: techno 2021-06-26T02:01:41.049869+00:00 heroku[router]: at=info method=POST path="/add/" host=t3chn0-l0ver-sharing.herokuapp.com request_id=eaa2092e-29f0-4d78-89ec-44ec2638d0e6 fwd="114.32.78.170" dyno=web.1 connect=5ms service=2437ms status=302 bytes=407 protocol=https 2021-06-26T02:01:40.969867+00:00 app[web.1]: ['German Underground Techno | Dark & Hard | Fear N Loathing in Berlin [FNL043]', 'Amelie Lens - Stay With Me'] 2021-06-26T02:01:40.970261+00:00 app[web.1]: List:['German Underground Techno | Dark & Hard | Fear N Loathing in Berlin [FNL043]', 'Amelie Lens - Stay With Me'] 2021-06-26T02:01:40.970336+00:00 app[web.1]: ready to add 2021-06-26T02:01:41.023841+00:00 app[web.1]: len:0 2021-06-26T02:01:41.035167+00:00 app[web.1]: can't add 2021-06-26T02:01:41.035203+00:00 app[web.1]: ready to add 2021-06-26T02:01:41.041182+00:00 app[web.1]: len:1 Whole program: https://github.com/cojemma/techno_web -
pyhon based amazon web scraper working fine on local machine but getting blocked after deployment
I have built an Amazon product price tracker and the code works perfectly fine on Django local server but after deploying it, it is getting blocked by amazon. what could be the cause and how can I solve it? utils.py from bs4 import BeautifulSoup import requests from django.conf import settings # Windows 10 with Google Chrome user_agent_desktop = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\ 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 '\ 'Safari/537.36' headers = { 'User-Agent': user_agent_desktop} def getproduct(url): result = requests.get(url, headers=headers) soup = BeautifulSoup(result.text, 'lxml') print(soup) price = 0 deal_price = 0 title = soup.find('span',attrs={'id':'productTitle'}).text.strip() ''' other scrapping code ''' return product -
bulma sass compiler ruturns error on edit the .scss file in django project
I'm working on a django project, and I'm using bulma. I run python3 manage.py sass-compiler --watch and when I edit the mystyles.scss file, sometimes I get some errors like in this picture and it stops, but sometimes there is no error or stoping. Where is the problem? -
How to send two pk when Update and Delete
my superb coding friends, I want to ask you how to send two pk(blog's and comment's). I want to let users edit their comments and delete them if they want. But, to do so, I need to send two pk which I don't know how to. I googled and tried what a website said, but doesn't work well. Any comments help me and thanks for your time in advance!! Here are the codes I wrote... # urls.py # the two HTML names are comment_update.html and comment_delete.html from django.urls import path from . import views from .views import BlogCreate, BlogUpdate, BlogDelete, BlogList, CommentUpdate, CommentDelete # blogs urlpatterns = [ path('', views.index, name='latest_blogs'), path('my_blogs/', views.my_blogs, name='my_blogs'), path('my_blogs/my_blog_search', views.my_blogs_search, name='my_blogs_search'), path('drafts/', views.drafts, name='drafts'), path('blog/<int:pk>/', views.blog, name='blog'), # path('blog/<int:pk>/comment/', views.add_comment, name='add_comment'), path('blog/<int:blog_pk>/comment/update/<int:comment_pk>/', CommentUpdate.as_view(), name='comment_update'), path('blog/<int:blog_pk>/comment/delete/<int:comment_pk>/', CommentDelete.as_view(), name='comment_delete'), path('create/', BlogCreate.as_view(), name='blog-create'), path('update/<int:pk>/', BlogUpdate.as_view(), name='blog-update'), path('delete/<int:pk>/', BlogDelete.as_view(), name='blog-delete'), path('all_blogs/', BlogList.as_view(), name='all_blogs'), path('all_blogs/all_blogs_search/', views.all_blogs_search, name='all_blogs_search'), ] # views.py @login_required def blog(request, pk): blog = get_object_or_404(Blog, pk=pk) if request.method == 'GET': form = CommentForm() elif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.user = request.user comment.save() comments = Comment.objects.all().filter(blog=blog.id) number_of_comments = comments.count() # if request.method == 'POST':+ # form = CommentForm(request.POST) … -
Validation of an inline formset dependent on one field from the parent form
I want to use custom validation in a django inline formset (form_date_event) so that I get different validation according to one value on the parent (form_event) form. Specifically, I'd like the form_date_event inline formset to accept an empty venue if the type of the form_event is 'recording release'. How can I achieve that? The type = cleaned_data.get('type') below doesn't work, I suppose because it's getting the clean data of the formset, not of the parent form. models.py: class Event(models.Model): EV_TYPE = ( ('performance', 'performance'), ('recording release', 'recording release'), ('other', 'other'), ) title = models.CharField(max_length=200) type = models.CharField(max_length=20, choices=EV_TYPE, default="performance") class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) forms.py: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'type', 'title', ] views.py: class BaseDateEventFormSet(BaseInlineFormSet): def clean(self): cleaned_data = super().clean() type = cleaned_data.get('type') def event_edit_view(request, id): event = get_object_or_404(Event, id=id) form_event = EventForm(request.POST or None, instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), formset = BaseDateEventFormSet) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), queryset=dateEvent.objects.filter(event__id=id)) -
How can i use UpateView and ListView together?
I have a form to update, but this page also has a list of objects to display, and I don't know how to combine functionality of UpdateView and ListView. I read about mixins but did not understand how to use them with UpdateView views.py class VacancyEdit(UpdateView): model = Vacancy template_name = 'vacancies/vacancy-edit.html' fields = ['title', 'skills', 'description', 'salary_min', 'salary_max'] pk_url_kwarg = 'vacancy_id' success_url = '/' context_object_name = 'Application' -
React Native, Expo Video: Encountered a fatal error during playback: The server is not correctly configured
I'm having trouble with video playback using expo video in my React Native app. Originally playback worked fine when I temporally used dropbox to serve the media files. Now, I'm serving them on my own backend written with Django and I get this error: Encountered a fatal error during playback: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". What's going wrong here? Thanks! <Video ref={video} style={styles.backgroundVideo} source={{ uri: 'http://127.0.0.1:8000/media/q1intro.mp4', }} resizeMode="contain" shouldPlay onPlaybackStatusUpdate= {(playbackStatus) => _onPlaybackStatusUpdate(playbackStatus)} /> -
Update templates with external API data in django
[example] i have cities in my datatable and want to get data for each city (temp, humidity etc) from API for each city. in the view i can print this data for each city but have problem to do this in datatable (templates). Django templates -
How to add data to a Django IntegerField Model
I am creating an application that gives users donations and points after they fill out the form on my donate.html. In the donate view, I have some code that goes with a different model so please ignore that. I want to know how I can add data to the django integer field. For example if the integer field is equal to 3 and I add one I want it to be equal to 4. Can someone please help? My code is down bellow. Donate View: def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, ) ins.save() return render(request,'donate.html') Model: (I want to add to this data after the ins.save) class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) -
POST request from website server to a game's sqlite database in Python
My friends and I are writing a game. The registration is located on the website and the login is in the game application. I want to send a POST request from the website to the game's database which contains the email, username, and password. The website will use Django to accept registration and send a POST request using it. The game's server will use Flask and SQLAlchemy to put it in their database. Now the problem is, how can I achieve this goal without having people randomly emulate data using 3rd party POST requests? This way is very insecure. What should I do? -
How to create an soft link to a specific django admin table
How do I create a link to a django admin table using the url tag? I have been trying to create a link to a django admin table. This table was registed in the app called store inside a module called admin.py, and was refering to a model called Products. It's possible to access this table at link /admin/store/products/. I would like to know how do I create a link dynamically without writing the hardcoded link in the template. -
How to catch a subclass of DRF ValidationError?
I have a custom error class subclassed from DRF's ValidationError. I can raise it, but I can not catch that error subclass, only ValidationError. from rest_framework import serializers, status class CustomValidationError(serializers.ValidationError): status_code = status.HTTP_400_BAD_REQUEST default_detail = "Something did not go well" default_code = "custom_error" class CustomSerializer(serializers.Serializer): custom_data = serializers.JSONField() def validate_custom_data(self, data): raise CustomValidationError() try: s.is_valid(raise_exception=True) except CustomValidationError as exc: print("caught custom error") except serializers.ValidationError as exc: print("caught default DRF error") # output is always # "caught default DRF error" I feel like I'm missing something very basic here... can anyone help? -
Querying a data with Django ORM to return a specific data that belongs to a user
so I'm trying to build a Ledger App. When new users sign-ups, they create a new Business account that is linked to them (ForeignKey). Here is my model: User = get_user_model() class Business_Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) business_name = models.CharField(max_length=50) Type_of_service = models.CharField(choices=SERVICE_CATEGORIES, max_length=50) business_email_address = models.EmailField(max_length=254) class Meta: verbose_name = "Business_Account" verbose_name_plural = "Business_Accounts" def __str__(self): return self.business_name Now, I want to make a get request view that can query and returns a business account that belongs to a particular user. My current view just returns all the business accounts available in the database irrespective of which user is login. Here is my view: class AddBusinessAcctView(APIView): def get_object(self): try: return Business_Account.objects.all() except: raise status.HTTP_404_NOT_FOUND def get(self,request): queryset = self.get_object() serializer = BusinessAcctSerializer(queryset, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) Now, How can I query business accounts that belong to a particular user?. Thanks in advance -
Is it possible to integrate an old/legacy Django application into Zappa for serverless integration?
I am trying to find a way to integrate our company's Django Web app into Zappa so we can go completely serverless with our REST API. The problem is that our app has existed for several years, making it a lot heavier than the brand new apps that all of these Zappa tutorials init over. Is there a format that Zappa requires for integrating an old Django app into its framework? I have no wait of knowing how much refactoring will be required for Zappa to know how to transition our API into lambda functions. When I tried running Zappa deploy in our root directory, I got the following error, which probably means our app is poorly optimized for the Zappa system: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 896, in deploy function_name=self.lambda_name File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/core.py", line 1520, in get_lambda_function response = self.lambda_client.get_function(FunctionName=function_name) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 386, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/botocore/client.py", line 705, in _make_api_call raise error_class(parsed_response, operation_name) botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the GetFunction operation: Function not found: arn:aws:lambda:us-east-1:253119149513:function:src-dev During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 3422, in handle sys.exit(cli.handle()) File "/home/ubuntu/SkalaControl/env/lib/python3.7/site-packages/zappa/cli.py", line 588, …