Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset annotate on two field
I have a django models (It record the activities for some group_id) class Record(models.Model): group_id = models.PositiveSmallIntegerField(null=True, blank=True, default=None) update_date = models.DateTimeField(auto_now=True) status = models.PositiveSmallIntegerField(default=1) #only 2 status number: 1 or 2 activites = models.CharField(max_length=64, null=True, blank=True, default=None) #Not important for this question ... .. . I want to get a result like this: group the result by update_date count the number of status '1' and '2' separately {'update_date':'2020-01-01', 'status_equal_to_1': 10, 'status_equal_to_2': 20}, {'update_date':'2020-01-03', 'status_equal_to_1': 12, 'status_equal_to_2': 9},...... I have tried to use, result = Record.objects.values('group_id', 'update_date', 'status').annotate(count=Count('update_date')) However, it only count the update_date. How to count the status on this queryset? -
can't connect details.html to index.html in django
index.html {% for item in item_list%} <ul> <li> <a href="/foodmenu/{{item.id}}">{{item.id}} -- {{item.item_name}}</a> </li> </ul> {% endfor %} detail.html <h1>{{item.item_name}}</h1> <h2>{{item.item_desc}}</h2> <h3>{{item.item_price}}</h3> views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from .models import item from django.template import loader # Create your views here. def index(request): item_list = item.objects.all() template_name = loader.get_template('foodmenu/index.html') context = { 'item_list':item_list, } return HttpResponse(template_name.render(context,request)) def detail(request,item_id): item = Item.objects.get(pk=item_id) template_name = loader.get_template('foodmenu/detail.html') context = { 'item':item, } return HttpResponse(template_name.render(context,request)) urls.py from . import views from django.conf.urls import url urlpatterns = [ #foodmenu/ url("foodmenu", views.index,name='index'), #foodmenu/1 url("<int:item_id>/", views.detail,name='detail'), ] this is a django website where the index creates the link and by clicking on the hyperlink it takes me to the details page but problem whith current code is upon clicking hyperlink it does not take me to the details page , is something wrong with the urls.py or views.py ? -
Retrieving a Foreign Key value with django-rest-framework
I have to simple model, one is department, that creating successfully, when I going to create designation with the value of department id its said Could not find department. Here is my designation view class DesignationCreateView(CreateAPIView): serializer_class = DesignationSerializers permission_classes = (IsAuthenticated, ) # queryset = Designation.objects.all() lookup_url_kwarg = 'department_id' def get_queryset(self): return Designation.objects.filter(department_id=self.kwargs.get(self.lookup_url_kwarg)) def create(self, request, *args, **kwargs): try: department = Department.objects.get(id=request.data.get('department_id')) request.data['department'] = department.id except Department.DoesNotExist: raise NotFound(detail='department not found') return super(DesignationCreateView, self).create(request, *args, **kwargs) -
How to create multiple model instance (have one-to-many relationship) with an API call in DRF
I have 2 models Product and Watch like below class Product(models.Model): id = models.CharField(max_length=255, primary_key=True) # other fields And the Watch model have the product_id foreign key connected with Product model class Watch(models.Model): product_id = models.ForeignKey( Product, related_name='watches', on_delete=models.CASCADE, null=True, ) # other fields When I call an API to create a new watch with product_id in the request body. I want to check if the product with that product_id does exist or not. If not, I create a new product instance at the same time. Currently, I'd overiding the create() method in serializer class like so def create(self, validated_data): product_id = validated_data['product_id'] is_product_exist = self.is_product_exist(product_id) if (is_product_exist): watch = Watch.objects.create(**watch_data) else: Product.objects.create(**product_data) watch = Watch.objects.create(**watch_data) return watch But when calling API, I got the error {"product_id":["Invalid pk \"57668290\" - object does not exist."]} So how can I deal with this error? thank you guys -
Is it possbile to acces pythonanywhere database? [By free account] [closed]
I tried so many times to connect pythonanywhere database. I have hostname and password (Database too). OperationalError at /login/ (1044, "Access denied for user 'username'@'%' to database 'mybase'") -
no such table: (Django)
when i run my code (its for a project) i get this error: "no such table: encyclopedia_article". The error appears to come from 9 line of views.py (obj = article.objects.get(id=1). here is the code: views.py from django.shortcuts import render from django.http import HttpResponse from . import util import random from .models import article from .forms import ArticleForm def index(request): obj = article.objects.get(id=1) #THIS IS WHAT APPERS TO CAUSE THE ERROR context = { 'object': obj } entries = util.list_entries() random_page = random.choice(entries) return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "random_page": random_page, }) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) def new_article(request): form = ArticleForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "encyclopedia/new_article_tem.html", context) models.py: class article(models.Model): title = models.CharField(max_length = 120) description = models.TextField(blank=True, null = False) forms.py: from django import forms from .models import article class ArticleForm(forms.ModelForm): class … -
django orm how to update calculate data using only one query
i create one feature about item_buy data here is my ORM class class BuyData(models.Model): buy_count = models.IntegerField(default=0) refund_count = models.IntegerField(default=0) refund_rate = models.FloatField(default=0.0, help_test='refund_count / buy_count') when i create a function about refund i want update my BuyData model like def refund(): buy_data_queryset.update( refund_count = F('refund_count') + 1 ) buy_data_queryset.update( refund_rate = F('refund_count') / F('buy_count') * 100 ) but i think this way is not good because when this function called a lot of time per second, may be this 2 step queries raise some problem... so i found some document, and changed like this def refund(): with transaction.atomic(): buy_data_queryset.update( refund_count = F('refund_count') + 1 ) buy_data_queryset.update( refund_rate = F('refund_count') / F('buy_count') * 100 ) i think this way is good. but i want to know that solve this problem using only one query i know this is not a solution def refund(): # not a solution buy_data_queryset.update( refund_count = F('refund_count') + 1 refund_rate = F('refund_count') / F('buy_count') * 100 ) please give me some advice thank you :)) -
Unable to catch select option value from django form
I have used Select 2 for the product list in the formset. The product ID is being saved in the order details table, while updating I want to capture the product ID (i.e. select option value) but the name of the product is coming up (i.e. select option text). Please help. Thanks in advance. class PurchaseOrderItemsUpdate(UpdateView): model = PurchaseOrder form_class = PurchaseOrderForm template_name = 'purchase-order/index.html' success_url = reverse_lazy('accpack:purchaseorder-list') def get_context_data(self, **kwargs): kwargs['object_list'] = PurchaseOrder.objects.order_by('-id') data = super(PurchaseOrderItemsUpdate, self).get_context_data(**kwargs) PurchaseOrderItemsFormset = inlineformset_factory(PurchaseOrder, PurchaseOrder_detail, form=PurchaseOrderDetailsForm, fields='__all__', fk_name='order', extra=0, can_delete=True) if self.request.POST: data['order_details'] = PurchaseOrderItemsFormset(self.request.POST, instance=self.object) else: data['order_details'] = PurchaseOrderItemsFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() order_details = context['order_details'] if order_details.is_valid(): for item in order_details: print(product = item.cleaned_data['product']) Formset HTML: <input type="hidden" name="order-TOTAL_FORMS" value="5" id="id_order-TOTAL_FORMS"><input type="hidden" name="order-INITIAL_FORMS" value="5" id="id_order-INITIAL_FORMS"><input type="hidden" name="order-MIN_NUM_FORMS" value="0" id="id_order-MIN_NUM_FORMS"><input type ="hidden" name="order-MAX_NUM_FORMS" value="1000" id="id_order-MAX_NUM_FORMS"> <tr><th><label for="id_order-0-product">Product:</label></th><td><select name="order-0-product" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="Select Product" class="setprice product django-select2" style="width:100%" required="true" id="id _order-0-product"> <option value=""></option> <option value="">---------</option> <option value="1">Product1</option> <option value="2">Product2</option> <option value="3">Product3</option> </select></td></tr> <tr><th><label for="id_order-0-product_attr">Product attr:</label></th><td><select name="order-0-product_attr" data-minimum-input-length="0" data-allow-clear="true" data-placeholder="Select Attribute" class="setprice product_attr django-select2" style="width:250px" id="id_order-0-product_attr"> <option value=""></option> <option value="1-S-White">S-White</option> <option value="1-S-Black">S-Black</option> </select></td></tr> <tr><th><label for="id_order-0-order_qnty">Order Qnty:</label></th><td><input type="number" name="order-0-order_qnty" value="1.00" step="0.01" class="setprice order_qnty" min="0" required="true" disabled id="id_order-0-order_qnty"></td></tr> <tr><th><label for="id_order-0-recvd_qnty">Recv. Qnty:</label></th><td><input type="number" name="order-0-recvd_qnty" … -
default fields not working with an Embedded field on save(), in a django project with mongoDB
Let's say I have the below structure of Models for a django project with MongoDB Database, using djongo as DB engine. When I am trying to add a Department record if I don't provide the salary field which is marked as default=0 in the query am getting a ValidationError for not suplied fields class Person(models.Model): name = models.CharFields() surname = models.CharFields() salary = models.FloatField(default=0) class Meta: abstract = True class Department(models.Model): name = models.CharFields(max_length=60, unique=True, null=False) persons = models.EmbeddedField(model_container=Person) If I run the below query: Department( name='Networking', persons = { 'name': 'Mike', 'surname': 'Jordan' } ).save() I get a Validation error for not supplied field (Since is marked as default=0, why django asks for it ?): django.core.exceptions.ValidationError: ['{\'salary\': [\'Value for field "Project.Person.salary" not supplied\'] -
Facing issue while migrating from sqllite to postgresql in Django
I am getting below error when I am migrating from django SQLite to PostgreSQL. django.db.utils.ProgrammingError: cannot cast type smallint to boolean LINE 1: ... "merchant_view" TYPE boolean USING "merchant_view"::boolean I am able to see all the tables in Postgresql even the table which is giving me above error. But in Postgresql its datatype have changed from Boolean to smallint. I am not also not able to change the datatype from smallint to boolean in postresql. Most of the fields has Boolean datatype in postgresql.I dont know what causing this error. How can i solve this error. My Model class ContractLineItems(CommomFields): payment_app_id = models.AutoField(primary_key = True) code = models.CharField(max_length=11,unique=True) module = models.ForeignKey(ContractManager,on_delete=models.CASCADE) description = models.CharField(max_length=255) buy_rate = models.DecimalField(max_digits=10,decimal_places=10) default_rev_share = models.DecimalField(max_digits=10,decimal_places=10) list_price = models.DecimalField(max_digits=10,decimal_places=10) billing_type = models.ForeignKey("BillingType",on_delete=models.CASCADE) merchant_view = models.BooleanField(default=False) bound_descreption = models.CharField(max_length=255) user_id = None trash = None deleted_at = None deleted_by = None Thanks in Advance. -
Django authenticate() don't work after first logout
If I create new user from the page login after submit, if it's all ok, I do automatic login with login(request,user) and rederect user in home page. In this case script works. But if I do logout and subsequently login, authenticate() return None and the authentication fails. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "read": self.read, "archived": self.archived } register views def register(request): if request.method == "POST": email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "mail/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(email, email, password) user.save() except IntegrityError as e: print(e) return render(request, "mail/register.html", { "message": "Email address already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "mail/register.html") login views import json from django.contrib.auth import authenticate, login, logout … -
Django - build form fields from database dynamically
I hope the title of this question is as it should be based on this explanation below. I have a model as below: class Setting(models.Model): TYPE_CHOICES = ( ('CONFIG', 'Config'), ('PREFS', 'Prefs'), ) attribute = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=200) description = models.CharField(max_length=300) type = models.CharField(max_length=30, choices=TYPE_CHOICES) is_active = models.BooleanField(_('Active'), default=True) I use this to save settings. I have don't know all settings in advance and they can change in future. So I decided to save attributes and their values in this model instead of creating columns for each setting(attribute in the model). Now the problem I am facing is how do I present form with all attributes as fields so that a user can fill in appropriate values. Right now, as you can see, form shows columns 'Attribute' and "Value" as labels. I would like it to show value of column 'Attribute' as label and column 'Value' as field input. For example, in Setting model I have this: Attribute ------------ Value 'Accept Cash' ---------- 'No' I would like to appear this on form as <Label>: <Input> 'Accept Cash': 'No' I think I will have to build form fields from the database(Setting model). I am new to this and have … -
cookie isn't stored in browser localstorage cookies
hi I have a question about cookie first i'm using djangorestframework for backend and using react for frontend second, i decided to use jwt token for login authentication so i made jwt token and using django set_cookie() method for response cookie(jwt token is stored) enter image description here like this. and this is my cors settings in my settings.py file enter image description here and in the frontend side(react) enter image description here I wrote my code like this. so, what I expected was .. when I send 'login/' request, server check the id and password and if that is correct response with cookie(with jwt token) and that cookie is stored in local(browser) storage cookie part enter image description here but.. as a result.. enter image description here I got a cookie(with token) from response(that image is network tap) but.. it isn't stored in localstorage cookies as I uploaded above.. so, please tell me what is the solution with my case.. i tested it localhost react is 3000 port and django is 8000 port -
(Django 3.1.6/Python 3.8.7) Using a named method in fields or fieldsets admin.py does not work?
No matter what I try I cannot use a named method as a field name like they do in the docs. Eventually I'll make the method retrieve a field of a ForeignKey but for now I just want to figure out what I'm doing wrong with this simplified example. In this example from docs.djangoproject.com they are using the class method 'view_birth_date' just as I am using 'get_test' (below) and even through I'm using it in fieldsets instead of fields it should work. I've tried it with fields = and fieldsets = and I get the same result (error). It cannot find the field 'get_test' either way. I've also tried putting the def get_test(self) above the fieldsets = but it makes no difference. It should work the same as what is in the documentation but it does not. What am I doing wrong? This should work: @admin.register(Feeddata) class AdminFeeddata(admin.ModelAdmin): """Feeddata admin.""" list_display = ['id', 'eventtime', 'feed'] fieldsets = [ ('Meta', { 'fields': ['feed', 'eventtime', 'get_test'] }), ('JSON Data', { 'fields': ('json_data', ) }), ] # pylint: disable=no-self-use def get_test(self): """Test string.""" return 'test' But I get an error: FieldError at /admin/feeder/feeddata/fff1d764-52cd-499f-9ae9-b1251a806b5b/change/ Unknown field(s) (get_test) specified for Feeddata. Check fields/fieldsets/exclude attributes of … -
Host Django and React on the same server?
I am working on a SAS product. So there could be 1000 users using my application at the same time. Technologies Used: Django for Backend React.js for frontend Django Rest Framework for APIs I have hosted this project on a server with customized Nginx settings as shown here: https://stackoverflow.com/a/60706686/6476015 For now, I am having no issues but I want to know if there is some possibility of something going wrong in the future as usage and data will increase. Should I host the frontend and backend on separate servers? -
DoesNotExist at /cart/ matching query does not exist
I want show item in cart.html page in my cart but when i add tshirt item in cart it's gives Error Product matching query does not exist. and when i add Product item in cart it gives error Tshirt matching query does not exist when I click on Cart cartitem.py file: def cartitem(request): cart=request.session.get('cart') if cart is None: cart=[] for c in cart: tshirt_id=c.get('tshirt') product_id=c.get('product') product=Product.objects.filter(id=product_id) tshirt=Tshirt.objects.get(id=tshirt_id) c['size']= Sizevariant.objects.get(tshirt=tshirt_id, size=c['size']) c['tshirt']=tshirt c['product']=product return render(request,"cart.html",{"cart":cart}) -
Bounding box with longitude less than -180 django postgis
I'm trying to add a bounding box to django model. c.bounding_box = Polygon.from_bbox((-194.06250000000003, 31.952162238024975, -21.796875000000004, 76.3518964311259)) c.save() It works fine, but when I access django admin, I see incorrect box. I think it is because of the longitude less than -180. How can I fix it? -
How critical is pylint's no-self-use?
As an example I have a Django custom management command which periodically (APScheduler + CronTrigger) sends tasks to Dramatiq. Why the following code with separate functions: def get_crontab(options): """Returns crontab whether from options or settings""" crontab = options.get("crontab") if crontab is None: if not hasattr(settings, "REMOVE_TOO_OLD_CRONTAB"): raise ImproperlyConfigured("Whether set settings.REMOVE_TOO_OLD_CRONTAB or use --crontab argument") crontab = settings.REMOVE_TOO_OLD_CRONTAB return crontab def add_cron_job(scheduler: BaseScheduler, actor, crontab): """Adds cron job which triggers Dramatiq actor""" module_path = actor.fn.__module__ actor_name = actor.fn.__name__ trigger = CronTrigger.from_crontab(crontab) job_path = f"{module_path}:{actor_name}.send" job_name = f"{module_path}.{actor_name}" scheduler.add_job(job_path, trigger=trigger, name=job_name) def run_scheduler(scheduler): """Runs scheduler in a blocking way""" def shutdown(signum, frame): scheduler.shutdown() signal.signal(signal.SIGINT, shutdown) signal.signal(signal.SIGTERM, shutdown) scheduler.start() class Command(BaseCommand): help = "Periodically removes too old publications from the RSS feed" def add_arguments(self, parser: argparse.ArgumentParser): parser.add_argument("--crontab", type=str) def handle(self, *args, **options): scheduler = BlockingScheduler() add_cron_job(scheduler, tasks.remove_too_old_publications, get_crontab(options)) run_scheduler(scheduler) is better than a code with methods? class Command(BaseCommand): help = "Periodically removes too old publications from the RSS feed" def add_arguments(self, parser: argparse.ArgumentParser): parser.add_argument("--crontab", type=str) def get_crontab(self, options): """Returns crontab whether from options or settings""" crontab = options.get("crontab") if crontab is None: if not hasattr(settings, "REMOVE_TOO_OLD_CRONTAB"): raise ImproperlyConfigured( "Whether set settings.REMOVE_TOO_OLD_CRONTAB or use --crontab argument" ) crontab = settings.REMOVE_TOO_OLD_CRONTAB return crontab def handle(self, … -
inserting the request's user during put-as-create operations
I am using the following mixin. class PutAsCreateMixin(object): """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not hasattr(self, 'lookup_fields'): lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.save() return Response(serializer.data) and I have the following view. class OwnStarPutDestroyView(CoreView, PutAsCreateMixin, MultipleFieldMixin, PutDeleteAPIView): serializer_class = StarSerializer queryset = Star.objects.all() permission_classes = [IsAuthenticated, AddStars] lookup_fields = ['upload_id', 'user_id'] def get_object(self): # explicitly set the user-id kwarg by referencing # the request's user because we cannot set the same # anywhere else during put-as-create operations self.kwargs['user_id'] = self.request.user.id return super(OwnStarPutDestroyView, self).get_object() path('uploads/<int:upload_id>/stars/me/', views.OwnStarPutDestroyView.as_view(), name='own-stars-put-destroy'), As you can see here, I am setting the user_id to the kwargs before getting the object. This enables the mixin to include the kwarg as a parameter while checking if the object exists However, I don't think that this seems right. Is there a better way to do the same? -
Django can't load static files even though all settings are fine
I don't know why django can't load static files even though I have defined static_url, static_root, staticfiles_dirs and urlpatterns including static_root. I put static files in root_dir/static/ directory. My templates also got right syntax with {% load static%} and {% static '...'%} Please give me some advice on this. Many thanks -
Django + Pymongo creating account confirmation link
I am building a user module from scratch where users can do pretty much all regular user operations from login,signup,..., to account deactivation. The thing is that I am not using mongoengine or django ready-made models that simplify sql connections, instead I am doing everything from scratch using pymongo driver to connect to mongodb database where I need to code all CRUD operations. I am stuck at creating a temporary link for users to (1) confirm account - this link should not be expired, (2) reset password, this link expires in few days. I have two questions regarding this: 1- can i still use django token generator/ authentication library? I am not using Users django library so my users are just ones I create and insert to database, if yes how can i do that?! 2- if no, how can I generate those temp links considering similar level of security that django library adopts, i.e. hashed username/ salted.. etc. any advice if I am doing something wrong or I should re-do everything considering mongoengine as my driver so that I can inherit and use django models?! any recommendation is highly appreciated. Thank you -
unable to upload data from csv into sqlite database using Django,pandas
When I run makemigrations command and then migrate,the fields in the db are not populated with the values from csv. import sqlite3 import pandas as pd conn = sqlite3.connect('/Users/XYZ/OneDrive/Desktop/XYZ/Django/db.sqlite') df = pd.read_csv('/Users/XYZ1q/OneDrive/Desktop/XYZ/Django/grades.csv') df['id']=df.index df=df[['id', 'Student','GradeTest1','GradeTest2','Grade']] df.to_sql('filterByGrade_grademodel', conn, if_exists='replace', index=False) -
Check id user into two fields with get and request
i want create if validation in my views to check before to site they are matched,but if someone is matched together: Models.py class Matched(models.Model): profile_user = models.ForeignKey(Profile, on_delete=models.CASCADE,related_name='profile_user') matched_user = models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='matched_user') and model is with UniqueConstraint but my views def profileDetailView(request, pk): user = Profile.objects.get(pk=pk) if request.user.is_authenticated: pass and my question is to check in if user and request.user are in Matched Model, i mean i can do it like that: x = Matched.object.filter(profile_user=user, matched_user=request.user.profile) y = Matched.object.filter(profile_user=request.user.profile, matched_user=user) and if x or y: pass but its some more optimaze option for do it ? -
how to perform post request on nested serailizers in django rest framework
Hii I am new to django rest framework i am able to perform put delete and get operations but unable to perform post operations models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class User_log(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE,related_name='user_logs') fullname=models.CharField(max_length=255) fb_login=models.BooleanField(default=False) def __str__(self): return self.fullname serializers.py class userSerializers(serializers.ModelSerializer): password1=serializers.CharField(source="user.password1",write_only=True) password2=serializers.CharField(source="user.password2",write_only=True) fullname=serializers.CharField(source='user_logs.fullname') fb=serializers.BooleanField(source='user_logs.fb_login') class Meta: model = User fields=('id','username','email','password1','password2','fullname','fb') related_fields = ['user_logs'] def update(self, instance, validated_data): # Handle related objects for related_obj_name in self.Meta.related_fields: data = validated_data.pop(related_obj_name) related_instance = getattr(instance, related_obj_name) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() return super(userSerializers,self).update(instance, validated_data) urls.py from django.urls import path,include from django.contrib.auth import views as auth_views from . import views from rest_framework import routers router=routers.DefaultRouter() router.register('accounts',views.Userview,basename='user') app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('signup/', views.SignUp.as_view(), name="signup"), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset_email.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_complete.html' ), name='password_reset_complete'), path('',include(router.urls)), ] views.py class Userview(viewsets.ModelViewSet): def get_serializer_class(self): return userSerializers def get_queryset(self): return User.objects.all() def list(self,request): queryset = User.objects.all() serializer=userSerializers(queryset,many=True) if serializer.is_valid: return Response(serializer.data) this is the json format when i perform get request [ { "id": 1, "username": "karm", "email": "karm@gmail.com", "fullname": "ss", "fb": false } ] As mentioned … -
How to provide Share content functionality with discord in Python?
I am building an application using Python & Django in which I want to provide feature to share an event on discord. So what I want is a user can click on share with discord icon and get redirected to sign-in page where once he sign-in can be able to post the Event picture and it's details. I tried to create an application with Discord and followed some tutorial but they eventually end-up with sending messages using Hooks. I want user to share content like we do in Facebook and Twitter. Is that possible to do so with Discord?