Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter and sort results over multiple tables in Django
I have two models Page and Post where Page can have multiple Posts. Users will be sharing multiple Posts per day with the same URL. As result I need to get feed of the most shared URL per day and it’s posts in the current day. Is there a way to do this in Django ORM? class Page(models.Model): url = models.URLField() class Post(models.Model): page = models.ForeignKey(‘Page', on_delete=models.DO_NOTHING, null=True, blank=True, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I ended up with this which gives me the most shared URL but now I can’t figure it out how to get all the related posts and have them sorted by created_at. Post.objects.filter(created_at__date=date.today()).values('page__id').annotate(num_shares=Count('page__id')).order_by('-num_shares') <PostQuerySet [{'page__id': 2, 'num_shares': 6}, {'page__id': 1, 'num_shares': 5}]> -
Attempting to write full implementation of getting, adding, editing, deleting foreign key objects serialized sent over to front end
I am trying to do a return on objects that are related to another. example. I return a list of cities to my front end. If I click on a city I want to be able to view all the neighborhoods in that city. I want to be able to add, delete, and edit neighborhoods that pertain to that city. Here is my models. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) here are my views and urls that pertain to getting a city or a list of cities url(r'city/(?P<pk>[0-9]+)/$',SearchCityDetail.as_view()), url(r'city$', SearchCityListCreate.as_view()), # create city list url class SearchCityListCreate(ListCreateAPIView): queryset = SearchCity.objects.all() serializer_class =SearchCitySerializer class SearchCityDetail(RetrieveUpdateDestroyAPIView): queryset = SearchCity.objects.all() serializer_class = SearchCitySerializer my neighborhood urls and views so far: ( I am not sure if this is right) url(r'^neighborhood/(?P<citypk>[0-9]+)$', SearchNeighborhoodListCreate.as_view()), url(r'^neighborhood/(?P<citypk>[0-9]+)/(?P<neighborhoodpk>[0-9]+)$',SearchNeighborhoodDetail.as_view()), class SearchNeighborhoodListCreate(ListCreateAPIView): queryset = SearchCity.SearchNeighborhood_set.all() serializer_class = SearchNeighborhoodSerializer class SearchNeighborhoodDetail(RetrieveUpdateDestroyAPIView): queryset = SearchNeighborhood.objects.all() serializer_class = SearchNeighborhoodSerializer now according to the documentation I need to use a serializer that takes a backward relation http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument but I am not sure how. What I am getting at is that I am closing in on a solution from both ends but not sure exactly what I am … -
ParentalKey is not rendered within the StructBlock
I'm trying to create a custom StructBlock which I wanna use inside the StreamField. Here in the StructBlock I have 4 fields, namely: background_style title image category That's my code: from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore import blocks from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsnippets.models import register_snippet from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from modelcluster.fields import ParentalKey from .vars import BackgroundChoices class BaseBlock(blocks.StructBlock): background_style = blocks.ChoiceBlock(choices=BackgroundChoices, icon='color', required=False) @register_snippet class LeadCaptureCategory(models.Model): name = models.CharField(max_length=255) about = models.CharField(max_length=255, blank=True) icon = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('name'), FieldPanel('about'), ImageChooserPanel('icon'), ] def __str__(self): return self.name class Meta: verbose_name_plural = 'Lead Capture Categories' class LeadCaptureForm(BaseBlock): title = blocks.CharBlock(required=False) image = ImageChooserBlock(required=False) category = blocks.BlockField(ParentalKey('LeadCaptureCategory')) class Meta: icon = 'plus-inverse' label = 'lead capture form'.title() admin_text = label template = 'home/blocks/lead_capture_form.html' class HomePage(Page): template = 'home/home_page.html' menu = models.CharField(max_length=128, blank=True) body = StreamField([ ('lead_capture_form', LeadCaptureForm()), ], blank=True) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] 3 of these fields in the admin are rendered correctly, except category. You can see that the category is based on the modelcluster.fields.ParentalKey. Maybe that's the problem? Any idea how to solve this? In [27]: … -
get_absolute_url is not working
I am practicing with below github source code, but stuck in getting working get_absolute_url method.Not able to access svariable.html. It always redirecting to base.html.Any help would be much appreciated. https://github.com/GeoffMahugu/Django-Ecommerce Model.py class Product(models.Model): title = models.CharField(max_length=120) categories = models.ManyToManyField('Category', blank=True) default_category = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE) description = models.TextField(null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=20) default_image = models.ImageField(upload_to=image_upload_to_prod, blank=True, null=True) active = models.BooleanField(default=True) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) slug = models.SlugField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Products:SingleProduct', kwargs={'pk': self.pk}) view.py def SingleProduct(request, pk): objects = get_object_or_404(Product, pk=pk) vari = Variation.objects.filter(product=objects) obj_cat = objects.default_category obj_prod = Product.objects.filter(default_category=obj_cat).exclude(pk=objects.pk).order_by('-pk')[:3] title = '%s' % (objects.title) cart_id = request.session.get('cart_id') object = get_object_or_404(Cart, pk=cart_id) cart_count = object.cartitem_set.count() cart_items = object.cartitem_set.all() context = { 'vari': vari, 'title': title, 'objects': objects, 'obj_prod': obj_prod, 'cart_count': cart_count, 'cart_items': cart_items } template = 'svariable.html' return render(request, template, context) -
How can I input current user_id into django database table?
I'm trying to create editable table in user interface and everything works till I try to insert new model argument like: usr=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) after that getting this kind of error: django.db.utils.IntegrityError: NOT NULL constraint failed: irenginiai_irenginys.usr_id I'm trying to implement this because when I save my data every user can see it. But goal is to separate users information. Maybe there is an easier way to do it. Using django 1.11.10 version Models.py class Device(models.Model): usr = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip = models.CharField(max_length=50) port_number = models.CharField(max_length=50) Views.py def save_device_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True devices = Device.objects.all() data['html_device_list'] = render_to_string('devices/additional/partial_devices_list.html', { 'devices': devices }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def device_sukurti(request): if request.method == 'POST': form = DeviceForm(request.POST) else: form = DeviceForm() return save_device_form(request, form, 'devices/additional/partial_device_sukurti.html') def device_update(request, pk): device = get_object_or_404(Device, pk=pk) if request.method == 'POST': form = DeviceForm(request.POST, instance=device) else: form = DeviceForm(instance=device) return save_device_form(request, form, 'devices/additional/partial_device_update.html') def device_delete(request, pk): device = get_object_or_404(Device, pk=pk) data = dict() if request.method == 'POST': device.delete() data['form_is_valid'] = True devices = Device.objects.all() data['html_device_list'] = render_to_string('devices/additional/partial_devices_list.html', { 'devices': devices }) else: context = {'device': … -
Django Invalid HTTP_HOST header: 'mydomain'. You may need to add u'mydomain' to ALLOWED_HOSTS
This comes up when I try to access my site with the domain name, but it works fine when I use the IP address. I've tried adding 'mydomain', u'mydomain', and my IP address to ALLOWED_HOSTS in settings.py, but always get this error -
Pre-Caching API URL Django
I have a few api urls that return some json and I am also using django's builtin cache system. This works wonderfully except for the first user that uses the site. It will take a long time initially cache everything. So I want to write a Management Command that will make a request to these urls. On my server side I do receive the request but it is not successfully cached. Here is a part of my script where I make the call: import requests response = requests.get('url') content = json.loads(response.content.decode('utf-8')) So my question is, does the request module not enable caching? -
Stream music on template in Django
I'm building Django website to stream music from internet. As we got the url of audio file from which we can stream audio and it's working but I don't know how to make it play on webpage on users action. -
How to include javascript in Django template?
In my Django project 'pizzeria', I have created a static files folder for the app 'pizzas', so the folder structure is: pizzeria/pizzas/static/pizzas/. Inside this folder I have a javascript 'hack.js': //hack.js <script> document.getElementById("home page").innerHTML="Hacked!" </script> Now I want to include this script in my Django template (pizzeria/pizzas/templates/pizzas/base.html), however the following setup does not work (the innerHTML does not change on button click): {% load static %} <p> <a href="{% url 'pizzas:index' %}" id="home page">Home page</a> <a href="{% url 'pizzas:pizzas' %}">Our pizzas</a> <button onclick="{% static 'pizzas/hack.js' %}">Hack!</button> </p> {% block content %} {% endblock content %} What am I doing wrong? -
Django: how can I save objects to the database using FormView and ajax?
I am building an application using google maps api where users can add and save markers on the map. I am using ajax to send the form containing marker attributes to the backend. I am using django's heleper FormView: ajax.js: $(document).on('submit', '.add_marker_form', function(event){ event.preventDefault(); // parse form attributes: // (irrelevent code here) $.ajax({ method: 'POST', // or 'type' url: '/map/saveMarker/', data: data // the four attributes success: function(data){ console.log("marker saved"); }, error: function(data){ console.log("marker not saved"); } }); }) // document forms.py from django.forms import ModelForm from .models import myModel class SaveMarkerForm(ModelForm): class Meta: model = myModel fields = ['title', 'url', 'latitude', 'longitude'] mixin.py from django.http import JsonResponse class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): form.save() response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): data = { 'message': "Successfully submitted data." } return JsonResponse(data) else: return response views.py import requests from django.views.generic.edit import FormView from .forms import SaveMarkerForm from .mixin import AjaxFormMixin class SaveMarkerView(AjaxFormMixin, FormView): form_class = SaveMarkerForm template_name = 'map.html' success_url = '/' But after submitting the form, the objects are not saved in the database. As you can see I added form.save() to form_valid method as suggested … -
django post_save signals on model with two FKs
I have the three models provided by django-organizations: (clearly in pseudo-code) Organization: id #(PK) name OrganizationUser: id #(PK) user_id #(FK to the User model) org_id #(FK to the Organization Model) OrganizationOwner: id #(PK) org_id #(FK to the Organization Model) org_user_id #(FK to the OrganizationUser Model) When a user registers to my app, I want them to pass the name of the Organization they would like to create. For that I combine two forms into a single view (the UserCreationForm and my own OrgForm which is just a ModelForm derived from the Organziation Model (aka just a char field) <form action="" method="post">{% csrf_token %} <table> {{ org_form }} {{ user_form }} </table> <input type="submit" /> </form> With this I have successfully populated both the User and the Organization models. However I would like to grab the post_save signals and automatically populate the OrganizationUser and subsequently the OrganizationOwner models. For now, I'm focusing on the former. The issue arises from the fact that OrganizationUser depends on two FKs (user_id and org_id), so the save method for that model raises an error if any of the two is missing. @receiver(post_save, sender=User) @receiver(post_save, sender=Organization) def create_user_org_profile(sender, instance, created, **kwargs): if created: org = OrganizationUser() … -
how do I create an encrypted read only view of one of the pages of my website?
My users want to create a read only view of one of the pages of the website and send it to their clients. What is the best way to do this? I thought I would encrypt the link (example, http://ap.com/ut/dec/3/st/view_st.html) and display it in another page for them to cut and paste and view. When it is viewed, the encryption should be removed. Would this work? How would I do this? Does anybody have a better idea? -
Django subscription system
I have a some system with react on frontend and Django - as a backend (Django Rest Framework). Now I don't know exactly what the way to choose for subscription billing system. I read about stripe also, read about other subscriptions, but don't understand finally what the right way. Peoples may pay with card or paypal. Also, subscription have a some recurring (one month, one year). Tell me please, what the more best way to do it? Thanks a lot. -
Django Custom Template Tag convert JSON for template usage
I have a string JSON from model. {'street': 'xxxxx', 'unit': 'xxxxx'} May I know how should I do to render in template with @simple_tag? {% json_convert location as data %} so i can access, {{ data.street }} -
its possible order columns like this template in reportlab?
i'm trying to create a report like this image, but doest look like that, cause i dont know to much about reportlab, maybe i need to declare a third frame, to reply the third column : from reportlab.platypus import BaseDocTemplate, Frame,FrameBreak, Paragraph, PageBreak, PageTemplate #TwoColumns title frame_right = Frame(document.leftMargin, document.bottomMargin, document.width/2-6, document.height, id='col1') frame_left = Frame(document.leftMargin+document.width/2+6, document.bottomMargin, document.width/2-6, document.height, id='col2') #maybe declare a new frame #Append paragrah and breack frame 1 story.append(Paragraph("Documento subido {}".format(analysis.suspect_filename), styles["Title"])) story.append(FrameBreak()) #Append paragrah and breack frame 2 story.append(Paragraph("Índice de plagio <font color ='red'> {}</font>".format(suspect_percentage), styles["Title"])) document.addPageTemplates([PageTemplate(id='TitleCol',frames=[frame_right,frame_left]), ]) story.append(FrameBreak()) -
Django -- User' object has no attribute 'backend' When Registering New User
Working on a sign up form, and when all inputs are submitted, the user is correctly populated in database, but the web page is generating the following error: AttributeError at /accounts/sign_up/ 'User' object has no attribute 'backend' i've searched for the last hour but can't figure what this issue might be i don't see any backend declared in settings, but i thought that this was automatically set with built in Django Auth? Anyways here is my stack trace: Traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\accounts\views.py" in sign_up 55. login(request, user) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\__init__.py" in login 112. request.session[BACKEND_SESSION_KEY] = user.backend File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py" in inner 205. return func(self._wrapped, *args) Exception Type: AttributeError at /accounts/sign_up/ Exception Value: 'User' object has no attribute 'backend' which appears to be pointing back to my sign_up view here: def sign_up(request): form = forms.UserCreateForm() if request.method == 'POST': form = forms.UserCreateForm(data=request.POST) if form.is_valid(): form.save() user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email = form.cleaned_data['email'] ) login(request, user) messages.success( request, "You're now a user! You've been signed in, too." ) return HttpResponseRedirect(reverse('home')) # TODO: go to profile return render(request, 'accounts/sign_up.html', {'form': form}) and here is my custom … -
Email Accounts and PythonAnywhere
I have my domain name through Enom and my web app on PythonAnywhere. How do set up email accounts using my domain name? Please provide explicit instructions for using Google, or Enom, or a hosting company. I am not sure how to go about it. Thanks in advance. -
django redirect causes a redirect to next page, but then returns to original?
My redirect function is causing some issues. I call a url from a view using reverse with the parameters required for the view. There is not errors and in the browser of the url it corerctly displays theses parameters. However it seems like it redirects to the new url, but immediately after requesting the new view for the new url the page returns to the original view with the new url still displayed in the browser. Can anyone tell me if I am using the redirect function correctly or maybe i am using the reverse incorrectly? P.S. I chopped out a lot of code bc stackoverflow won't let me post all of it. home/urls.py from django.conf.urls import url from home import views app_name = 'home' urlpatterns = [ url('^$', views.index, name='index'), url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/', views.patient_summary, name='patient_summary'), url('^patient_summary/patientid=(?P<patient_id>\d+)&clinicid=(?P<clinic_id>\d+)/careplanid=(?P<careplan_id>\d+)/', views.care_plan, name='care_plan'), ] home/views.py def patient_summary(request, token, patient_id, clinic_id): user = get_user(token) if request.method == "POST": if ('careplanselected' in request.POST): props = request.POST.get('careplan') props = props.split("@") CPID = props[0] cpname = props[1] my_dict = {'token': token, 'patient_id': patient_id, 'clinic_id': clinic_id, 'careplan_id': CPID} return redirect(reverse('home:care_plan', kwargs=my_dict)) return render(request, 'home/patient_summary.html') def care_plan(request, token, patient_id, clinic_id, careplan_id): user = get_user(token) care_plan = [] cpname = '' return render(request, … -
heroku django.db.utils.ProgrammingError: column foo.foo_id does not exist after migrations
trying to understand the db behavior of an app I've deployed to heroku. no errs on deployment. make sure I'm starting with a clean db: $ heroku pg:reset $ heroku .. manage.py makemigrations -a fooapp the db will makemigrations, but indicates: You are trying to add a non-nullable field 'foo' to bar without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I've been selecting '1' giving it a default value, and then makemigrations runs and completes and I see the new migrations applied. then I migrate, and migrate appears to run successfully (each migraiton for each table is "OK"). but then I see in logs, app throws err The above exception was the direct cause of the following exception: Mar 02 08:21:28 fooapp app/worker.1: Traceback (most recent call last): Mar 02 08:21:28 fooapp app/worker.1: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner Mar 02 08:21:28 fooapp app/worker.1: response = get_response(request) Mar 02 08:21:28 fooapp app/worker.1: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response Mar … -
set a parameter with default value to route url in django
Hy all! I'm new to python / django and I came across a problem that I can not solve. I have a route configured for the site's home (1) and a route configured for categories (2): 1) url(r'^/(?P<c=vinhos>\w+)/$', IndexView().home, name='home') 2) url(r'^categoria/(?P<path>.*)/$', IndexView().by_category, name='by_category') I need to set my home url to open a category by default, something like www.mysite.com/c=defaul_category I tried in some ways, including: url (r '^ / (? P \ w +) / $', IndexView (). Home, name = 'home'). But I know it's incorrect. So... I have no idea how to do this. Could someone help me? Thank you -
How to use Bootstrap 4 and Bootstrap 2 on the same page
I have a Django application which is written in Bootstrap 4. On one page I am using a control which is written in Bootstrap 2, So if I use Bootstrap 2 on that page then controls works but other controls gets broke. If I use Bootstrap 4 then other control works except for the one which is written in Bootstrap 2 as Bootstrap 4 is not backward compatible. Basically, I am trying to use Bootstrap Tags Input written in bootstrap v2.3.2. Is there any way to tackle this issue, any guidance would be highly appreciated. -
Django with non org backends
Can someone give basic example (urls.py, models.py, views.py) on how to use Django with abstract non ORM backend? What to extended and override? Unfortunately all examples on Django still assume ORM use. In my case, I try to make it work against Google BigTable using Python API -
Django generic ListView two models
In django template i need to iterate over two models with two different information but doing nested loops for inside for think that is wrong. In addition this code in template does not work. I created two views that references to the same template. template Inside each module should be it's own childs. {% if all_modules %} {% for module in all_modules %} <li><a class="scrollto" href="">{{ module.name }}</a> <ul class="nav doc-sub-menu v"> {% for child in all_childs %} <li><a class="scrollto" href="#step1">{{ child.name }}</a></li> {% endfor%} </ul> </li> {% endfor %} {% else %} <li><a class="scrollto" href="">None</a></li> {% endif %} In views class BackendModulesListView(generic.ListView): template_name = 'backend_modules.html' model = BackendModules context_object_name = 'all_modules' class ChildsListView(generic.ListView): template_name = 'backend_modules.html' model = Child context_object_name = 'all_childs' queryset = Child.objects.filter(backend_modules_id=1) In models class Child(models.Model): name = models.CharField(max_length=255) backend_modules = models.ForeignKey(BackendModules, null=True, blank=True, related_name='backend') frontend_components = models.ForeignKey(FrontendComponents, null=True, blank=True, related_name='frontend') Please help me to find solution and optimize code. I know i write bad code :( -
The cloud panel doesn't into directory in django
I write cloud panel write python/django. My problem is, urls.py doesn't access next forward directory. I use apache. when it is go to next forward, this page is showing: https://postimg.org/image/b1t9s26b9/ my urls.py inside: from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import TemplateView admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$','explorer.views.home',name='home'), url(r'^servers/$','explorer.views.servers'), url(r'^addserver/$','explorer.views.addserver'), url(r'^removeserver/$','explorer.views.removeserver'), url(r'^manage/(?P<server>[\w]+)/(?P<path>[\w]+)/$','manager.views.filemanager'), url(r'^navback/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.navbackward'), url(r'^naviforward(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<dir>[\w]+)/$','manager.views.navforward'), url(r'^edit/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.editdata'), url(r'^saveandsend/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.senddata'), url(r'^upload/(?P<server>[\w]+)/(?P<path>[\*\w]+)/$','manager.views.uploadfile'), url(r'^delete/(?P<server>[\w]+)/(?P<path>[\*\w]+)/(?P<file>[\.\w]+)$','manager.views.deletefile'), ] my views.py inside: https://postimg.org/image/s2c60qr2d/ views.py inside for ssh connection and sftp connection : https://postimg.org/image/635rdjhxx/ my routing to html file inside: <div class="col-md-4"> {% if path != orginalpath %} <a href="http://127.0.0.1:8000/navback/{{ server }}/{{ modpath }}/"><span class="glyphicon glyphicon-arrow-left" style="color: #ac2925;height: 30px"></span></a> {% endif %} {% for d in dirs %} <ul> <li> <span class="glyphicon glyphicon-folder-close" style="color: #eea236"></span> <a href="http://127.0.0.1:8000/naviforward/{{ server }}/{{ modpath }}{{ d }}/">{{ d }}</a> </li> </ul> {% endfor %} </div> if you're access to project and image you can be look in link: https://postimg.org/gallery/3iakj1t7a/ https://gitlab.com/rection/Cloud-Panel-Django.git How to be solution my problem? -
access user's information using token
I am using Djoser for authentication in django. I have a model class called wallet which looks like following: from django.db import models class Wallet(models.Model): account_address = models.CharField(max_length=100) user = models.OneToOneField('auth.User', related_name='account_no', on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Wallet, self).save(*args, **kwargs) and then i have serializer class for this model which looks like following. from rest_framework import serializers from wallet.models import Wallet class WalletSerializer(serializers.ModelSerializer): class Meta: model = Wallet fields = ('url', 'account_address', 'user') I want to write an api_view for this model class with get method that returns the wallet address for a particular user. Can anybody tell me how to do this?