Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use exchanged token with OAuth2 - social-auth-app-django
I'm trying to implement OAuth2 authentifications using social-auth-app-django. My backend can exchange an authorization token that I get from a frontend using providers SDK, I will give Apple as an example: My iOS app gets an authorization token from the user using "Sign in with Apple". I then sends this token to the backend so I can exchange it using this view: @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token_view(request, backend): serializer = SocialSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print("Backend:", backend) print("Token:", serializer.validated_data['access_token']) # set up non-field errors key # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views try: nfe = "non_field_errors" except AttributeError: nfe = 'non_field_errors' try: # this line, plus the psa decorator above, are all that's necessary to # get and populate a user object for any properly enabled/configured backend # which python-social-auth can handle. user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: # An HTTPError bubbled up from the request to the social auth provider. # This happens, at least in Google's case, every time you send a malformed # or incorrect access key. return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) print() return Response({'token': token.key}) else: # user is not active; at some point they deleted their … -
PostgreSQL or Firebase Firestore DB for Django E-Commerce Web App (and Android & iOS App)
I am building an e-commerce website with customers and sellers with Django (as well as iOS and Android apps with React Native). I want to use the Firebase Firestore Database but I can't get it to work with Django (there are also almost no tutorials online..). For PostgreSQL there are a lot of tutorials online and I've already once used it in another Django project. Which is better for a Django e-commerce website (and React Native mobile apps)? -
Django Limit the Number of objects in a model
i am working on a django-cms project and (i have to make a image model which can only make 3 objects not more than that if someone tries there should be a message: Max Objects Have been Created) so, how can i limit the number of objects in a model ? Thank you, I will Really appreciate you feedback. -
Create an account from django-admin
In my CRM, the owner of the company gives the first password and email for new employees. Employee can change them later (I don't need to show them in admin, which is not allowed by django by default). But how to show the fields for giving the first password in admin? For examplle fields - "Password for new user" and "Again password for new user" models.py class CustomUser(AbstractUser): [...] def __str__(self): return self.email admin.py from django.contrib import admin from .models import CustomUser admin.site.register(CustomUser) I need this effect: -
Pyscript in Django application
I am wondering if we could use pyscript on HTML pages inside a Django project. I'd tried to use it but unfortunately, it doesn't work. Any suggestions? -
How do I preserve search result in Django pagination
I am new to Django and I have develop form with Country and State field from the Profile Model. And I want a situation where if I search for country and a particular state, a list of persons belonging to that country and state should be display and paginated. And if the records are in multiple pages then I should be able to click on individual pages that follow to view the searched results on those pages without loosing the search results. Here is my views code with pagination. def search_applicants(request): form = ApplicantsSearchForm(request.GET or None) if form.is_valid(): list_submited = Profile.objects.filter( nation__icontains=form.cleaned_data['nation'], state__icontains=form.cleaned_data['state'] ) else: list_submited = submited_apps.objects.all() paginator = Paginator(list_submited, 5) page = request.GET.get('page') paged_listApps = paginator.get_page(page) context = { 'list_applicants':paged_listApps, 'form':form, } return render(request, 'user/list_applicants.html',context) You may wish to understand that I have got the pagination of all records from the Profile Model but any time I perform a search and try to click on the pagination tabs the search result is get scattered and returns to all the list items in the database. Someone should kindly help. Thank in anticipation to your answer. -
Django Migration from Github actions
Hello I have a database in Google Cloud Platform and I am trying to figure out how to run a django migration from github actions once I have deployed my app to GCP's App engine. I have tried using cloud_sql_proxy, but cannot get it to connect to my database. I would whitelist github actions ip address but I am not really sure what the ip addresses is either. Here is the config I currently have: # .github/workflows/deploy # https://cloud.google.com/python/django/appengine # https://github.com/actions-hub/gcloud: name: deploy-app-to-gcp on: push: branches: [ main] paths: - '**' jobs: migrate: name: Migrate Database runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: get env file run: echo "${{secrets.ENV_FILE}}" | base64 --decode > ./env_variables.yaml - name: Set up Python 3.9 uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Get Cloud SQL Proxy run: | wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy chmod +x cloud_sql_proxy - name: migrate Database env: DATABASE_CONNECTION_ADDRESS: 127.0.0.1 run: | pip install ruamel.yaml set -a; eval $(python -c 'from pathlib import Path;from ruamel.yaml import YAML; print( "".join( [f"{k}={v!r}\n" for k, v in YAML().load(Path("env_variables.yaml"))["env_variables"].items() if not k.__eq__("DATABASE_CONNECTION_ADDRESS")] ) )'); set +a ./cloud_sql_proxy -instances=com-cjoshmartin:us-central1:cms-db=tcp:5432 & python … -
In Python how can I overwrite the class attribute of an inherited class, where that attribute is itself an instance of a model
As in the title, I have a base class ListView, with a Serializer attribute that needs overwriting. For each of my django models I create a child ListView class and a Serializer. So for example for the django model Event we have a corresponding view class EventListView(ListView), and we have a corresponding Serializer class EventSerializer(Serializer). The Serializer child class is specified within the ListViewClass, as in my code below. Is it possible to have the serializer overwritten automatically based on the value supplied to model, and how may I mark model and Serializer as attributes that are to be overwritten adn therefore do not need values specified in the base class? Many thanks class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = 'all' class ListView(APIView): model = # Event is set as the default. Serializer = queryset = model.objects.all() def get(self,request): # !!! Get filter conditions from request queryset = ListView.queryset.filter() # !!! Filter conditions serializer = ListView.Serializer(queryset,many=True) return Response(serializer.data) def post(self,request): data = JSONParser.parse(request) serializer = ListView.Serializer(data = data) if serializer.is_valid(): return Response(serializer.data, status = 201) else: return Response(serializer.errors, status = 400) class EventListView(ListView): model = Event -
Django 3.2: AttributeError: 'NoneType' object has no attribute 'attname'
I am working with Django 3.2, and have come across a problem that seems to have answers here and here also, and I have tried the solutions offered in the accepted answers, but have not been able to resolve the issue I am having (error message in subject title). Here is what my models look like: #### models.py class ActionableModel: def __init__(self, parent_object): self.parent = parent_object # FIX: This might be an expensive operation ... need to investigate if isinstance(parent_object, django.contrib.auth.get_user_model()): self.owner = parent_object self.actionable_object = parent_object else: self.owner = self.parent.get_owner() self.actionable_object = self.parent.get_actionable_object() self.owner_id = self.owner.id self.ct = ContentType.objects.get_for_model(self.actionable_object) self.object_id = self.actionable_object.id # ... class Prey(models.Model): # ... fields pass class Predator(models.Model, ActionableModel): catches = GenericRelation(Prey) catch_count = models.PositiveIntegerField(default=0, db_index=True) last_catch = models.DateTimeField(editable=False, blank=True, null=True, default=None) def __init__(self, *args, **kwargs): ActionableModel.__init__(self, *args, **kwargs) # ... class Meta: abstract = True # Classes used for testing - naming similar to [mommy](https://model-mommy.readthedocs.io/en/latest/basic_usage.html) class Daddy(): def __init__(self, *args, **kwargs): ActionableModel.__init__(self, *args, **kwargs) class Foo(Daddy, Predator): # ... pass In the shell, I type the following: from myapp.models import Foo admin = django.contrib.auth.get_user_model().objects.all().first() foo = Foo.objects.create(parent_object=admin) Here is the stack trace of the error that results in the subject title: Foo.objects.create(parent_object=admin) Traceback (most … -
How to remove extra puncuation marks during saving forms data in django?
when ever i add data to the form i got extra puncuation marks in the value as shown in the image. for example - name = xyz while saving i get name = ('xyz',) This image is for refrence -
How to use a CNN code in python inside a website?
I have website with backend in Python (Django) and JavaScript hosted on heroku. I want to use an external code that is working on Google Colab, this code uses CNN to do image classification. My idea is that user upload an image through the website then the code that is written in python in Google Colab does the classification and returns the result to the website. Does anyone know what would be the best way to do this? -
Flask SQLAlchemy Unique Column Problems
I want to make a blog where a user can make posts. And I want the title of the post to be unique. But when I try to make a post and the post already exists returns an error. But when I write a try it still returns an error. Why does this happen? @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): try: allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) post2 = Post.query.all() db.session.add(post1) db.session.commit() # error, there already is a user using this bank address or other # constraint failed if sear != 2: flash('We couldnt make your post') except: flash('Error') return render_template('posts.html') class Users(UserMixin,db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(200),unique=True,nullable=False) password = db.Column(db.String(200),unique=False,nullable=False) role = db.Column(db.String(200),unique=False,nullable=False) missions = db.Column(db.String(200),unique=False,nullable=True) waiter = db.Column(db.String(200),unique=False,nullable=False) posts = db.relationship('Post',backref='user') class Post(db.Model): … -
Webhook vs Polling Django
I have a doubt about which technology to use, I am developing a project that will have three parts as in the image below, the first and the front in react js, the second would be the back in python django, and the third that will be deliver written in pure python (runs on pc) that will do calculations and physical simulations that can take up to days to run, all environments will be running on aws. For this communication I thought of taking these functions written in pure Python and transforming them into django, and using them as a service, but the question would be whether I use polling or webhooks to do this process, since the physicists gave me the calculations, but there is no a lot of documentation about them, just the minimum to run, I wanted to change the code as little as possible, so I thought about polling, react keeps asking if it's finished, and if it has an error it says it gave an error, I believe the webhook to see if it gave an error and return would need to change the code more, what do you advise? -
Object is not subscriptable python error django
I have this function where i am using models 'Start' and 'End' that contain fields latitude and longitude.. and I am trying to match them with a field called elements that I am using subscript to extract the start_id and end_id and match them with 'Start' and 'End' The function in question that is giving me a subscript error is: def dispatch(request): events = Event.objects.filter(description="Dispatch").values("element") starts = Start.objects.all() ends = End.objects.all() # subscript error fixed d_starts = { s.start_id: s for s in start } # subscript error fixed d_ends = { c.end_id: c for c in end } d_start_end_ids = [ { 'start': d_starts[e['element'][52:58]], 'end': d_ends[e['element'][69:75]] } for e in events ] for d in d_start_end_ids: # Error is here data = {'[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude'])} JsonResponse(data) I am getting an error saying: line 33, in dispatch_data data = '[%s, %s] -> [%s, %s]' % (d['start']['latitude'], d['start']['longitude'], d['end']['latitude'], d['end']['longitude']) TypeError: 'Start' object is not subscriptable] My Start model is: class Start(models.Model): start_id = models.CharField(primary_key=True, max_length=100) name = models.CharField(max_length=150) latitude = models.FloatField(null=True) longitude = models.FloatField(null=True) please help -
Update array of ManyToMany field in Django REST framework
I have a Model Plot which looks like this: from django.db import models class Plot(models.Model): class SUNSHINE(models.TextChoices): NONE = None FULL_SUN = 'Plein soleil', SHADOW = "Dans l'ombre", SUNNY = 'Ensoleillée', MODERATE = 'Modérée' name = models.CharField(max_length=50) garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE) width = models.CharField(max_length=50, blank=True, null=True) height = models.CharField(max_length=50, blank=True, null=True) exposition = models.CharField(max_length=50, choices=SUNSHINE.choices, default=SUNSHINE.NONE, blank=True, null=True) qr_code = models.CharField(max_length=50, blank=True, null=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True) def __str__(self): return self.name With a plant object which is a foreign key of the model of the same name. And I have this partial_update function in my view: class PlotViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Plot.objects.all() def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) serializer = WritePlotSerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) But when, in my front, I want to update the plants in my plot, I can select several of them and when I click on add it works it updated, but it deleted the old plants present or I would like that when I update, it keeps the plants that were already present in the array then it adds the one we just added. How can I do to get this result? Here is my serializer of Plot … -
How to create sitemap with dynamic sub sitemap structure in django?
I'm trying create a dynamic generate sitemap in django and i hit the wall. Action I'm trying to code: in url.py i have url: re_path(r'sitemap-jobs.xml$'...) the above web address triggers function: MonthlyJobsSitemap in sitemap dict whose create sub sitemap divided by months like: http:/host/sitemap-pl-jobs-2022-01.xml The result is address in robots.txt sitemap: /sitemap-pl-jobs.xml. After entering there are files splitted on monthly files: /sitemap-pl-jobs.xml-2022-01. And after entering the monthly sitemap i wanna see addresses to jobs published on web site. I don't have problem with create one sitemap with all jobs but i have to split it into monthly sitemaps. Someone have any idea how to code that in django? -
How to delete multiple records from different classes in django?
It seems that whenever I delete records I get server error (500), I'm knew in web development so I don't know what's causing the problem please help... these are my classes in models.py where I would like to delete records from: class Bscs1_1(models.Model): idNumber = models.CharField(max_length=15) CC100 = models.FloatField() CC101 = models.FloatField() resultCS11 = models.IntegerField() courseCS1 = models.TextField() class Cs(models.Model): cs_count = models.TextField() class Retention_cs1(models.Model): retention_count = models.TextField() And this is how I add records from views.py: def resultCS1_1(request): CC100 = request.POST['CC100'] CC101 = request.POST['CC101'] prediction = model1.predict([[CC100,CC101]]) studentID = request.POST['studentID'] student1 = Bscs1_1() student1.idNumber = studentID student1.resultCS11 = prediction student1.CC100=CC100 student1.CC101=CC101 student1.save() courseCS1 = Cs(cs_count='BSCS1') courseCS1.save() retention = Retention_cs1() if prediction == 0: retention.retention_count = 'NEGATIVE' else: retention.retention_count = 'POSITIVE' retention.save() return render(request, "rCS1_1.html" , {'student1': student1} ) This is how I delete records from all those classes all in one click of a button: def deleteCS12(request, student_id): stud = Bscs1_1.objects.get(pk=student_id) stud.delete() csCount = Cs.objects.get(pk=student_id) csCount.delete() retention = Retention_cs1.objects.get(pk=student_id) retention.delete() return redirect('tableCS12') -
How can I use Q objects on Two Dynamic Search Forms in Django
I am working on a Django project where I want to search profile records for those that are resident in a particular country and state. In this project I would be collecting data of people from different countries and their respective states, so I want a situation where I can have two Search Forms for Country and State. The form should be able to allow me select list of countries in the Profile Model while the state form should be able to allow me type and search for a state in the selected country. The result should be a list of persons in the selected Country and searched state.Please understand that I decided to go with Q objects because I learn that it makes queries efficient. Here are my model code: class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') Here is my search form code: class Applicant_Search_Form(forms.ModelForm): class Meta: model = Profile fields = ['nation', 'state'] Here is my views code: def … -
DRF how to update, create OneToOneField in serializers?
I have two models, with OnetoOne field. How can I update/create them with help of serializers? class Page(models.Model): info = models.TextField(null=True, blank=True) document = models.OneToOneField( Document, primary_key=True, related_name='page', on_delete=models.CASCADE) class Document(models.Model) description = models.TextField(null=True, blank=True) note = models.TextField(null=True, blank=True) My serializer class PageSerializer(ModelSerializer): document = DocumentSerializer() class Meta: model = Page fields = ('document', 'info') def update: def create: -
Question about a code in a Django Girl's tutorial
I'm through a Django Girls' tutorial. There is this code (that I think is mistyped): <a href="<div data-gb-custom-block data-tag="url" data-0='post_draft_list'></div> " class="top-menu"><span class="glyphicon glyphicon-edit"></span></a> Regardless of the errors, I'm trying to figure out what this part does: <div data-gb-custom-block data-tag="url" data-0='post_draft_list'></div> I searched in the internet, but I didn't find an explanation for it. What are 'data-gb-custom-block', data-tag, and 'data-0'? Neither Django's documentation nor Mozilla's mention these codes, that I believe is something belonging to HTML. -
How to groupby one column of django table based on another column
I have a table like below: id | type | code ------------------------------------- 0. 5 2 1 6 6 2 8 16 3 4 11 4 5 4 5 2 2 6 4 1 7 10 6 8 9 2 All I need like output is a list of groupby on codes like here: { '2': [5,2,9], '6': [6, 10], '16': [8], '11':[4], ...} I did this query but it's not doing the right query: type_codes = [{ppd['code']:ppd['type_id']} for ppd in \ MyClass.objects \ .values('code', 'type_id') .order_by() ] Any help will be appericiated -
how to show success message without refreshing the page in django
I have a template called basket whenever I want to update the product quantity it works fine but the success message doesn't show until I refresh the page views.py: def basket_update(request): basket = Basket(request) if request.POST.get('action') == 'post': book_id = int(request.POST.get('bookid')) book_qty = int(request.POST.get('bookqty')) basket.update(book=book_id, qty=book_qty) messages.success(request,"Basket Has Been Updated") basketqty = basket.__len__() baskettotal = basket.get_total_price() response = JsonResponse({'qty': basketqty, 'subtotal': baskettotal}) return response -
Django profile picture does not upload
This question was asked I don't know how much but it doesn't give my answers The app I was gonna make is a little blog webapp from a tutorial (for some training in Django, it's the first time I use it so...) There is my code: # models from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your views here class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Well, that's not all: @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm( request.POST, instance=request.user ) p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile ) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'title': 'Profile', 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) At this time, I changed all my settings and I did some html code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username … -
The 'for' loop only one product's attribute in django
I want to calculate the the difference between total product quantity and shopcart product quantity. So I made calculations in my views and applied to templates. The problem is the for loop which I think should loop through all products only loops to the recently added product and give the result to all the products. What did I do wrong? Here is the code: Template {% for rs in products %} <div> <a href="{% url 'addtoshopcart' rs.id %}" class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</a> </div> <p><strong>Availability:</strong> {% if tot > 0 %} In Stock : {{tot}} Remaining {% else %} Out of Stock {% endif %}</p> {% endfor %} Views def category_products(request,id,slug): current_user = request.user #category = Category.objects.all() setting = Setting.objects.get(pk=1) catdata = Category.objects.get(pk=id) products = Product.objects.filter(category_id=id) context={'products': products, #'category':category, 'setting':setting, 'catdata':catdata } for rs in products: if rs.variant == 'None': checkinproduct = ShopCart.objects.filter(product_id=id, user_id=current_user.id) # Check product in shopcart if checkinproduct: control = 1 # The product is in the cart else: control = 0 # The product is not in the cart""" if control == 1: tot = rs.amount - ShopCart.objects.get(product_id=id, user_id=current_user.id).quantity else: tot = rs.amount context.update({'tot': tot}) else: pass return render(request,'category_products.html',context) -
Django / How to evaluate a django variable inside a bracket expression?
In my html file I need to define a variable for a js file. <script> var gltf_home = "{% static '/3d/ {{ scene.GltfFileToLoad }} ' %}"; </script> which gives as an output : /static/3d/%7B%7B%20scene.GltfFileToLoad%20%7D%7D instead of /static/3d/00-world.glb And this alternative var gltf_home = "{% static '/3d/' {{ scene.GltfFileToLoad }} %}"; gives /static/3d/ What would be the correct way to do it ?