Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding post creater user instead of request.user
I am building a BlogGroup App and I am stuck on an Error. I am trying to add users in database from the Post Detail Page in template. BUT when i try to add post creater User then it is adding request.user. I have no idea what is wrong in the code. models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') class BannedMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) views.py def ban_user(request,pk): groupss = Group.objects.get(id=pk) posts = get_object_or_404(GroupPost,pk=pk) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.group = groupss new_post.save() new_post.banned_members.add(posts.user) return redirect('mains:home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban_user.html', context) def PostDetailView(request,pk): data = get_object_or_404(GroupPost,pk=pk) context = {'data':data} return render(request, 'Postdetail.html', context) Postdetail.html {% block content %} {{ data.user }} <b>User :</b> <a href="{% url 'ban_user' data.user.id %}">Ban {{ data.user }}</a> {% endblock content %} I am trying to save the post owner to add in banned_members but it is adding request.user everytime. Any help would be much Appreciated. Thank You in Advance -
django nginx gunicorn application showing apache2 default page - only on ip request not domain name
Very odd behavior from my Ubuntu 18.04 LTS server I have followed this tutorial here (twice) and it is all working properly except a couple odd things firstly, when I use my browser to visit the IP of my VPS, the django default application page shows up throughout the tutorial however accessing it through the domain name results in a time out error secondly, now that I have completed the tutorial and configured nginx to proxy pass to gunicorn, the apache2 ubuntu default page is now displaying instead of the django default page on a visit to the ip address and still no response from the domain name, even though there is no installation of apache2 on this server... $ whereis apache2 apache2: here is my gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target here is my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=trends Group=www-data WorkingDirectory=/trends_dir ExecStart=/trends_dir/trendsvenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ trends.wsgi:application [Install] WantedBy=multi-user.target here is my /etc/nginx/sites-available config file for the site, which has been properly symlinked to /etc/nginx/sites-enabled server { listen 80; server_name www.trendsontheblock.com trendsontheblock.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /trends_dir; … -
Addinng a string utilizing a quote in django raw query
I want to include a string as a query and the string would contain spaces so I would need to make use of quotes. But this is giving me error that it is expecting another parameter. ModelName.objects.raw("select * from tablename where city='%s' and state=%s",params=['San francisco', 'Los Angeles']) This the error that is produced error: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied. -
Django multiple annotate with Sum get wrong answer
I'm trying to use .annotate() with multiple Sum() But i got wrong calculations. I've read that I should use Subquery but I didn't get it done with it maybe I use it in wrong way (because it is first time) or it doesn't solve my issue. class DonationQuerySet(QuerySet): def completed(self): return self.with_donations_stats().filter( amount__lte=F('total_donation'), deleted_at=None) def not_completed(self): return self.with_donations_stats().filter( amount__gt=F('total_donation'), deleted_at=None) def with_donations_stats(self): return self.annotate( wallet_donation=Coalesce(Sum('wallet_transaction__amount'), 0), normal_donation=Coalesce(Sum('transactions__amount'), 0), total_donation=F('wallet_donation') + F('normal_donation')) class DonationManager(Manager): def get_queryset(self): return DonationQuerySet(self.model, using=self._db) def completed(self): return self.get_queryset().completed() def not_completed(self): return self.get_queryset().not_completed() def with_donations_stats(self): return self.get_queryset().with_donations_stats() How could I solve it? -
how to create relation between existing data in case of OneToMany relation in Django?
Let assume there are two table custom_users and sub_products and there is one-to-many relation between them i.e, a user can have multiple products . Bellow is the code:- Sub_Products:- class Sub_Products(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() pic = models.ImageField(upload_to="sub_products") products = models.ForeignKey(Products, on_delete=models.CASCADE) custom_user = models.ForeignKey(CustomUsers, null=True, on_delete=models.SET_NULL) CustomUsers:- class CustomUsers(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) email = models.EmailField() password1 = models.CharField(max_length=10, blank=False) # is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] Now table created by these two models are containing data except custom_user field in sub_products table. Data in CustomUsers Table:- >>> allusers = CustomUsers.objects.all() >>> print(allusers) <QuerySet [<CustomUsers: admin@gmail.com,True,TrueTrue,Truepbkdf2_sha256$260000$eRZ8K8QIVKL9hpyMlyr0n0$5L+P3/2o1vSx4kN6mne5YCANDry0LmAOx6kHEHtBIDM=>, <CustomUsers: at harva@gmail.com,False,FalseTrue,Falsepbkdf2_sha256$260000$jyc9eK0V3Dr0roJFZG1GJU$27COkzOdmiOd4NuGpZu/zp9O5d4qOeVE5zAMSwt9jPs=>]> And Data in Sub_Products table:- >>> allproducts = Sub_Products.objects.all() >>> print(allproducts) <QuerySet [<Sub_Products: Tshirt>, <Sub_Products: HRX tshirt>, <Sub_Products: Tshirt>, <Sub_Products: Nike Tshirt>, <Sub_Products: Shirts>, <Sub_Products: RoadStar Ts hirt>, <Sub_Products: Nike Tshirt>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Slipers>, <Sub_Products: Sandel>, <Sub_Products: Slipers>]> Now my real question how should we create relation between existing user and products such that a user can have multiple products. I really appreciate your help. Thanks in advance. Hope to … -
I deployed a site for trial using GitHub zeet and Django website and my css files and images is showing not found
I did deploy a Django site using GitHub hosted with zeet and its not showing the css and images and javascript i need help. I did try many ways it does work if I make it with just html css and javascript but not working with Django. -
how can i update a filed in django after the time ends?
my projects is bidding site, i wanted to close the bid after some specific date. but i don't know how to implement it. please any one suggest me anything models.py class products(models.Model): produtname=models.CharField(max_length=255) productdesc=models.CharField(max_length=255) amount=models.FloatField() image=models.ImageField(upload_to='pics') featured=models.BooleanField(default=False) enddate=models.DateTimeField() soldout=models.BooleanField(default=False) after the end date the field soldout should be automatically set to true -
Django Admin list_filter and ordering on annotated fields
I'm trying to filter in Django Admin on an annotated field, but getting a FieldDoesNotExist error. class Event(models.Model): name = models.CharField(max_length=50, blank=True) class EventSession(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() @admin.register(Event) class EventAdmin(admin.ModelAdmin): ordering = ["event_start_date"] list_filter = ["event_start_date", "event_end_date"] def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( event_start_date=Min("eventsession_set__start_date"), # start of first day event_end_date=Max("eventsession_set__start_date"), # start of last day ) return qs The resulting error in Django Admin is: FieldDoesNotExist at /admin/events/event/ Event has no field named 'event_start_date' I need to filter on event_start_date rather than eventsession_set__start_date because filtering on the latter causes multiples rows per event (one for each session) to show up in the list view. The error comes from the get_field method of django/db/models/options.py: try: # Retrieve field instance by name from cached or just-computed # field map. return self.fields_map[field_name] except KeyError: raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) I'm on Django 3.2. Any ideas? -
When I define a custom manager .. Error:Manager isn't accessible via Post instances
I defined a custom manager inheriting models. Manager put in in my model 'Post'. The error says that you cant call manager through a instance but i have not called it through a instance it works fine when i remove the custom manager. models.py: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='Published') class Post(models.Model): STATUS_CHOICES = [ ('draft','Draft'), ('published','Published'), ] id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200) created = models.DateTimeField(auto_now_add=True) published = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published') author = models.ForeignKey(CustomUser,on_delete=models.CASCADE) body = models.TextField() objects = models.Manager() published = PublishedManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("detail", kwargs={"slug":self.slug,"id": self.id}) views.py: class PostListView(ListView): model = Post template_name = 'blog/index.html' context_object_name='posts' Error image -
I want to restrict a particular user from creating a saved class object if the current user id is different from the id in the live class object
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=2.5) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_registered = models.BooleanField(default=False) is_attended = models.BooleanField(default=False) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) my views.py from django.shortcuts import render from rest_framework import mixins from rest_framework import generics from django.contrib.auth.mixins import LoginRequiredMixin from rest_framework import status from django.contrib.auth.models import User from rest_framework.response import Response from django.contrib.auth import authenticate from . import serializers from . import models # Create your … -
null value in column "group_id" of relation "group_bannedmembers" violates not-null constraint
I am building a BlogGroupApp and I am trying to add a feature of Block Users in Any Kind of Blog Group by Admin. When i try to save the form of banned user then it is keep showing null value in column "group_id" of relation "group_bannedmembers" violates not-null constraint DETAIL: Failing row contains (1, 1, null). models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class BannedMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) views.py def ban_user(request,pk): posts = get_object_or_404(User, pk=pk) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.save() new_post.banned_members.add(posts) return redirect(':home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban.html', context) When i try to ban user then it is keep showing this error. AND when i delete group from BannedMembers then it is wokring Fine, BUT I have to add group in model. I have no idea what am i doing wrong. Any help would be Appreciated. Thank you in Advance. -
How to check if input is already entered before in Django?
I am new to Django. I want to generate Qrcode for given input,and I have done it.But I want to set Error if qr code for given in put is already generate before.Here is my code.Forms.py from django import forms from generateqr.models import * import qrcode class Qrgenerate(forms.Form): input =forms.CharField() def clean_input(self): valinput=self.cleaned_data['input'] if len(valinput)<5: raise forms.ValidationError('Enter more than 5 ') else: img=qrcode.make(valinput) img.save("test.png") return valinput views.py from django.shortcuts import render from .forms import Qrgenerate import qrcode from django.http import HttpResponse # Create your views here. def showformdata(request): if request.method =='POST': fm = Qrgenerate(request.POST or None) return render(request,"home.html",{'form':fm }) [enter image description here]This is form where I want to set error if input is already entered by user before.I have tried with this code,But not work and gives ERROR Attribute 'object' is not found. def clean_input(self): valinput = self.cleaned_data['username'] try: input = Qrcode.objects.get(input==input) except user.DoesNotExist: return input raise forms.ValidationError(i'input "%s" is already in use.' % input) [1]: https://i.stack.imgur.com/mDigT.png Thanks in advance.Please help me out. -
Select all foreign keys from the foreign key table in django
Let's imagine I have 2 models: Class Tree(models.Model): title = models.CharField(max_length=255) Class Apple(models.Model): tree = models.ForeignKey(Tree, related_name="apples") How do I select all the Trees that have Apples. I mean I want to select all the Trees that exist in Apple Model from an instance of Tree. I think I want to execute this query: SELECT DISTINCT tree.id, tree.title FROM apple JOIN tree ON apple.tree = tree.id -
Any good resources for using DRF api with Vanilla Django?
I have a project for which I have made all the relevant REST APIs using DRF. I however have to implement them on the frontend which has to be made using Django templates and hitting the APIs using requests module. Is there a good resource where I can reference into this, as I can't find anything on it online. -
Post Creater is not adding in Banned Users
I am building a BlogApp and I am building a Feature of Ban Users, In which Blog Admin can ban other members in the Group. BUT when i submit the form then it is not saving and keep showing that null value in column "group_id" of relation "group_banmembers" violates not-null constraint DETAIL: Failing row contains (13, null, 1, can_create_post). models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class BanMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) can_create_blogpost = models.BooleanField(blank=True,default=True) views.py def ban_user(request,grouppost_id): posts = GroupPost.objects.get(id=grouppost_id) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.save() new_post.banned_members.add(posts.user) return redirect('home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban.html', context) group_posts.html {% for pos in posts %} <br> <br> {{ pos.title }} <br> <b>User :</b> <a href="{% url 'ban_user' pos.user.id %}">Ban {{ pos.user }}</a> <br> {% endfor %} I am trying to ban a user which posted a post in a specific Group. BUT when i click on save button for ban then it is not saving in database. I have no idea what am i … -
Django forms.ModelForm POST change object before update
Via a standard HTML POST form I successfully update an exciting record with the bellow but the situation is that I need to change one data field. On the Django website the say just make e new form instance and change the field but for what ever the reason is the field data does not change in the save() action. class ProvisioningDetails(View): def post(self, request, provisioning_ptr_id, terminal_id, site_id): form = ProvisioningForm(request.POST) if form.is_valid(): a = Provisioning.objects.get(provisioning_ptr_id=provisioning_ptr_id) f = ProvisioningForm(request.POST, instance=a) f.str1 = "some new data" f.save() return redirect( "provisionings_show_view", site_id, terminal_id, provisioning_ptr_id ) class ProvisioningForm(forms.ModelForm): class Meta: model = Provisioning fields = [ "id", "fixedip", "str1", "str2", "str3", "ip", ] def clean(self,): cleaned_data = super(ProvisioningForm, self).clean() I also tried this which does the change the data in the form but not in the database: class ProvisioningDetails(View): def post(self, request, provisioning_ptr_id, terminal_id, site_id): form = ProvisioningForm(request.POST) if form.is_valid(): a = Provisioning.objects.get(provisioning_ptr_id=provisioning_ptr_id) new = ProvisioningForm(request.POST) new.str1 = "some new data" f = ProvisioningForm(new, instance=a) f.save() return redirect( "provisionings_show_view", site_id, terminal_id, provisioning_ptr_id ) Anyone know how I can get the str1 = "some new data" save in the database -
Django: The view didn't return an HttpResponse object. It returned None instead
I keep getting this error when I try to use my 'edit' url. The view to_do_list_app.views.edit didn't return an HttpResponse object. It returned None instead. my url.py urlpatterns = [ path('', views.todo, name='todo'), path('delete/<job_id>', views.delete, name='delete'), path('cross_off/<job_id>', views.cross_off, name='cross_off'), path('uncross/<job_id>', views.uncross, name='uncross'), path('edit/<job_id>', views.edit, name='edit'), ] from django.db import models.py class Jobs(models.Model): # Relationships to_do_owner = models.ForeignKey("auth.User", on_delete=models.SET_NULL, blank=True, null=True) # Fields item = models.CharField(max_length=200) completed = models.BooleanField(default=False) def __str__(self): return self.item +' | ' + str(self.completed) Here is my veiws.py from django.shortcuts import render, redirect from .models import Jobs from .forms import ListForm from django.contrib import messages from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required def edit(request, job_id): if request.method == 'POST': item = Jobs.objects.get(pk=job_id) form = ListForm(request.POST or None, instance=item) if form.is_valid() and request.POST['item'] != '': form.save() messages.success(request, request.POST['item']+ ' er blevet redigeret i din opgave list') return HttpResponseRedirect('todo') else: item =Jobs.objects.get(pk=job_id) context = {'item': item} return render(request, 'edit.html', context) And here I have my template edith.html <form class="d-flex" method="POST" action="{% url 'edit' item.id %}"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="{{ item.item }}" value="{{ item.item }}" aria-label="Search" name="item"> <input type="hidden" value="{{ user.username }}" name="job_owner"> <input type="hidden" value="{{ item.completed }}" name="completed"> <button class="btn btn-outline-secondary" type="submit">Rediger opgave</button> </form> … -
Passing form data to a celery task
I have a simple form (with no model) in my views in which I capture the inputs the user type in order to send an email. I capture those inputs with: if result['success']: name = form.cleaned_data['name'] email = form.cleaned_data['email'] ... send_email_task() Te question is, how can I pass that data to a Celery send_email_task in order to send it. Something like: @shared_task def send_email_task(): send_mail(name + ': ' + subject, 'From: ' + email ... -
Django - How to parallelize my Import process?
I'm running a Import process which is working fine if I start it sequentially but as soon as multiple threads starting to import/scan my files for metadata I'm running into the following error: Core.models.MusicAlbums.MultipleObjectsReturned: get() returned more than one MusicAlbums -- it returned 2! So my question is how can such a flow be parallelized?: ... else: if not MusicArtists.objects.filter(title=artist_value).exists(): try: new_music_artist_object, is_created = MusicArtists.objects.get_or_create(title=artist_value) new_music_artist_object.refresh_from_db() except MultipleObjectsReturned: new_music_artist_object = MusicArtists.objects.get(title=artist_value) pass else: new_music_artist_object = MusicArtists.objects.get(title=artist_value) if not MusicAlbums.objects.filter(artist=new_music_artist_object, title=album_value).exists(): try: new_music_album_object, is_created = MusicAlbums.objects.get_or_create( title=album_value, artist=new_music_artist_object, cover=cover_value, total_discs=total_discs_value, total_tracks=total_tracks_value, copyright=copyright_value, release_date=release_date_value, genre=genre_value) new_music_album_object.refresh_from_db() except MultipleObjectsReturned: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) pass else: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) try: new_music_track_object, is_created = MusicTracks.objects.get_or_create( file=new_file_object, album=new_music_album_object, artist=new_music_artist_object, bitrate=bitrate_value, genre=genre_value, duration=duration_value, size=size_value, nb_streams=nb_streams_value, media_type=0, title=title_value, release_date=release_date_value, disc=disc_value, track=track_value ) new_music_track_object.refresh_from_db() pull_streams(object_id=new_music_track_object) except MultipleObjectsReturned: pass Basically each file gets placed onto a message queue for processing, than X worker(s) pic up one of those generated tasks and processes them. So far so good but as soon as I have 2 workers that are processing a MusicTrack out of the same MusicAlbum my process breaks or at least I get multiple entries at the database for the same thing, I get two entries for the MusicAlbum … -
I tried to aggregate the sum of a property from a model in Django
On the model page, I created a property called nzd_price, which is not really a field, but a property. On a templatetags page, I tried to aggregate the sum all the rows of a column from nzd_price for a new row with the name Total: models.py: class BrazilBill(models.Model): item = models.CharField('item', max_length = 50) price = models.DecimalField('price', max_digits = 10, decimal_places = 2) @property def nzd_price(self): return round(float(self.price) * 0.29, 2) templatetags/total_price.py: from django import template from django.db.models import Sum from financial_planning.models import BrazilBill register = template.Library() @register.filter def brazil_bill_total_brl(value): return BrazilBill.objects.aggregate(Sum('price')).get('price__sum') @register.filter def brazil_bill_total_nzd(value): return BrazilBill.objects.aggregate(Sum('nzd_price')).get('nzd_price__sum') The error: FieldError at /financial-planning/ Cannot resolve keyword 'nzd_price' into field. Choices are: id, item, price Based on Calculate the sum of model properties in Django, I also tried: @register.filter def brazil_bill_total_nzd(value): return BrazilBill.objects.aggregate(Sum('brazilbill__nzd_price')) -
How to integrate OAuth2 with back- and frontend
I'm learning OAuth2 to integrate a 3rd party provider like Facebook or Github. But I'm struggling with finding resources that describe how to integrate it when you're building an app with both a back- and frontend. In this example, let's pretend a have frontend (myfrontend.com) running something like Vue.js. And a backend (mybackend.com) running something like Django. And a 3rd party provider like GitHub. My idea is to use this flow: Front end redirect's to providers Authorize url. example: https://github.com/login/oauth/authorize?client_id=<client_id>&redirect_uri=https://mybackend.com/callback?return-to=https://myfrontend.com/home. If the user authorizes, backend receives code in /callback. Backend sends authentication request (serverside) with code to get access_token to 3rd party provider. Backend creates a user if it doesn't exist yet and saves access_token associated with that user. Backend creates a new local token for the user (for authenticating to mybackend.com) (JWT or OAuth2). Backend redirects to https://myfrontend.com/home (specified in first url) with token in body. Frontend receives token and saves in in local storage. When the frontend requires a resource from GitHub a behalf of the user, a request is sent to my backend which in turn uses the save access_token and requests the resource from GitHub. My question is this: Is this flow safe or should I … -
Trying to establish a realtion Between model tables in Django.but iam getting error while insering values |foreign-key item must be an instance
class User(AbstractUser): pass class auction_list(models.Model): item_id=models.IntegerField(primary_key=True) item_name=models.CharField(max_length=64) owner=models.CharField(max_length=64) image=models.CharField(max_length=128) def __str__(self): return f"{self.item_id}:{self.owner}{self.item_name}" class bid(models.Model): item_id=models.ForeignKey(auction_list,on_delete=models.CASCADE,related_name="currentbid") bid=models.IntegerField(max_length=16) user=models.CharField(max_length=64) def __str__(self) : return f"{self.item_id}{self.bid}{self.user}" and when i try to inser the valules i get this error inseritions i tried to do: In [16]: a3=auction_list(item_id=3,item_name="keyboard",owner="alex" ) In [17]: a3.save() In [18]: a3 Out[18]: <auction_list: 3:alexkeyboard> In [20]: b1=bid(item_id=3,bid=100,user="alex") and the error i get is In [20]: b1=bid(item_id=3,bid=100,user="alex") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-20-6befcb719aa3> in <module> ----> 1 b1=bid(item_id=3,bid=100,user="alex") ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in __init__(self, *args, **kwargs) 483 # checked) by the RelatedObjectDescriptor. 484 if rel_obj is not _DEFERRED: --> 485 _setattr(self, field.name, rel_obj) 486 else: 487 if val is not _DEFERRED: ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py in __set__(self, instance, value) 213 # An object must be an instance of the related class. 214 if value is not None and not isinstance(value, self.field.remote_field.model._meta.concrete_model): --> 215 raise ValueError( 216 'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % ( 217 value, ValueError: Cannot assign "3": "bid.item_id" must be a "auction_list" instance. can some one help me understand wht is the problem here and how can i resolve these -
Celery-beat doesnt work with daily schedule
I trying to run tasks with celery-beat. When I launch it by minute or hour schedule, tasks will start correctly, but if I trying to run daily task, it display in django admin panel, but not run in time. It must to work in the following way: regular django code starts a 'start_primaries' task in Party class: def setup_task(self): schedule, created = IntervalSchedule.objects.get_or_create(every=7, period=IntervalSchedule.DAYS) self.task = PeriodicTask.objects.create( name=self.title + ', id ' + str(self.pk), task='start_primaries', interval=schedule, args=json.dumps([self.id]), start_time=timezone.now() ) self.save() Is it possible that there are some settings that limit the duration of the task's life? At the moment I have the following among the Django settings: CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 950400 CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'django-db' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_RESULT_EXPIRES = None CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 950400} -
is there any other way to post data?
while submitting my data i am having error saying please check you detail even though all the data i have input is correct def register(request): registered = False user_form = UserForm() user_profile_form = UserProfileForm() if request.method == 'POST': user_form = UserForm(data = request.POST) user_profile_form = UserProfileForm(data = request.POST) if user_form.is_valid() and user_profile_form.is_valid(): user_form.save() user_profile_form.save(commit = false) user_profile_form.user = user #creating that OneToOneField relation if 'profile_pic' in request.FILES: user_profile_form.profile_pic = request.FILES['profile_pic'] user_profile_form.save() registered = True return index(request) else: print('Error occured while Posting Data please check you detail!') else: user_form = UserForm() user_profile_form = UserProfileForm() return render(request,'levelfive_second_app/register.html',context = {'user_form':user_form , 'user_profile_form':user_profile_form}) -
Errno 13 Permission denied: media file in Django
I am trying to write a file to the django media folder, but on execution I get a permission denied error. The configuration works fine on the OSX development platform, but not on the Ubuntu test server. I have the following config: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' print('SETTINGS CWD = ', os.getcwd()) models.py methods: def template_to_file(self): print('MODELS CWD = ', os.getcwd()) with open(path + '/newsletter-volume-1.html', 'w') as static_file: static_file.write('Hello') def save(self, *args, **kwargs): self.template_to_file() super(Newsletter, self).save(*args, **kwargs) On the OSX development platform the file writes to the media folder and the Current Working Directory prints are as follows: SETTINGS CWD = /Users/tb/Documents/dev/backoffice MODELS CWD = /Users/tb/Documents/dev/backoffice However, on the Ubuntu platform I get: [Errno 13] Permission denied: '/home/admin/backoffice/media/newsletter-volume-1.html' SETTINGS CWD = /home/admin/backoffice MODELS CWD = / The following permissions are set as follows (admin is the owner of Django): drwxrwxr-x 9 admin admin 4096 Jun 19 09:05 . drwxr-xr-x 7 admin admin 4096 Jun 19 06:02 .. drwxrwxr-x 2 admin admin 4096 Jun 19 06:07 media Does anyone have a solution to this and an explanation as to why the Current working directory changes to '/' on the Ubuntu server?