Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django doesn't update the ImageField path
I am trying to upload a profile picture when model instance is being created. I want my profile picture to be stored in a folder, that is named according to the instance id, hence once the picture is uploaded I need to create a new dir and move the picture there. I followed this, which suggests overriding the default save() method in the model, and this, that proposes to use post_save signal to save the new file twice. My current code looks as follows: class Emp(models.Model): photo = models.ImageField("Photo", blank=True, null=True, default='default_avatar.png') def save(self, *args, **kwargs): # Call standard save super(Emp, self).save(*args, **kwargs) if self.photo.path: initial_path = self.photo.path new_path = os.path.join(settings.MEDIA_ROOT, 'profile_picture_of_emp_{0}/{1}'.format(self.pk, os.path.basename(initial_path))) # Create dir if necessary and move file if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) os.rename(initial_path, new_path) # Save changes super(Emp, self).save(*args, **kwargs) So this actually moves the file and creates new_path correctly, however, the self.photo.path stills refers to the old location and I can't figure out a way to update this new path. The same happens with post_save signal as it doesn't update the path of moved file. Any suggestions? Thanks! -
Django run custom management command on docker + Kubernetes env
I have deployed my Django application on AWS using Kubernetes. I am using docker containers to deploy my application. I have created the custom management command lets say python manage.py customcommand I want execute it on kubernetes level. To get pods i am using kubctl get pods I am trying to find solution but not succeeded Thank you. -
InlineFormset Updating issues, after changing the value in the input
I have 2 models Product and Image: class Image(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) parent = models.ForeignKey('self', blank=True, null=True, verbose_name='original image', on_delete=models.CASCADE) image = models.ImageField(upload_to=file_upload_to) image_type = models.CharField(max_length=50) parent is a Foreign Key to the original image I use the Image Model in a formset: ImageFormSet = inlineformset_factory(parent_model=Product, model=Image, form=ImageModelForm, min_num=1, max_num=4, can_delete=True) Steps: Set the Product Form with the inlineformset for Image Show and submit the creation form save the original image(s) after the original image is saved, create multiple image by cropping the original image, using a task Edit/Update Form, show as image one of the cropped image (instead of original) by modifying(filter by image_type) the Formset queryset An here appear the issue: The {{form.id}} value in case of update, is the pk(id) of the cropped image, instead of the original image: <input name="product-image-0-id" value="15" type="hidden"> and when the image is updated, is replacing the cropped image in database instead of the original image, and the 'cropped' tasks after and insertion in database is wrong. I tried to replace the value(using a custom widget) instead of the cropped image with the pk(id) of the original(parent_id). but if I do, this, on updating/replacing an older image, the new replacing … -
Redis does not work with celery backend
I use the example task: @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In [4]: debug_task() Request: <Context: {'args': (), 'kwargs': {}}> Settings: CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672/' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ALWAYS_EAGER = False I am using docker images: docker run --rm -d --name reddy -p 6379:6379 redis docker run --rm -d --name haas -p 5672:5672 -p 15672:15672 --hostname haashost --link reddy:redis rabbitmq:management I can see rabbitmq in the management plugin processing, and this I get from redis: In [2]: res = debug_task.delay() redis monitor: 1516271123.743674 [0 172.17.0.1:33908] "SUBSCRIBE" "celery-task-meta-33e54cc6-4fdc-4747-8f57-a06cd73fb663" but getting timeout with: In [3]: res.get(timeout=1) even though monitor gives: 1516271129.684841 [0 172.17.0.1:33912] "GET" "celery-task-meta-33e54cc6-4fdc-4747-8f57-a06cd73fb663" -
Where I can take access_token and token_secret for twitter
Maybe my question is very stupid. But I couldn't find the answer neither in the official documentation of rest-auth nor there in questions. I want to use authentication through Twitter. I created the app in Twitter, put all the data into the model Social application According to the documentation I made view: from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter from rest_auth.views import LoginView from rest_auth.social_serializers import TwitterLoginSerializer from rest_framework.permissions import AllowAny class TwitterLogin(LoginView): serializer_class = TwitterLoginSerializer adapter_class = TwitterOAuthAdapter permission_classes = (AllowAny,) Added url: from django.urls import path from .views import TwitterLogin urlpatterns = [ path('rest-auth/twitter/', TwitterLogin.as_view(), name='twitter_login') ] Then went to the link: /rest-auth/twitter/ And got the request: { "access_token": "", "token_secret": "" } I.e. these data must be transfer from front-end to the API endpoint. The question is: how front-end will take acces_token and token_secret? I don't understend this moment of authentication. If somewhere there is a detailed description of this issue, or on this resource is already someone gave the answer to this question - I will be grateful for the link. -
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fedc69d9c50>: Failed to establish a new connection
urllib3.exceptions.NewConnectionError: : Failed to establish a new connection error happens. When I access get_data method,the error happens. I wrote in get_data method like def get_data(request, **user_id): user = UserInfoUtil.user(id, user_id['user_id']) print(111) uid = user.to_string()[0] print(222) users = UserInfoUtil.get_info(id,uid) print(users) I wrote in UserInfoUtil like class UserInfoUtil(object): def user(d, id, uid, Data=False): if Data: for user in id.userEs().query({'query': {'data': {'user': uid}}}): return UserInfoUtil.createUser(id user) else: for user in id.user().query({'id': Id(uid)}): return UserInfoUtil.createUserInfo(id, user) return None I do not think I dealed with much data in program.So I really cannot understand why this error happens.print(111)&print(222) is shown in terminal, but print(users) is not shown.I think Timeout causes this error ,so I rewrote timeout is 1000,but same error happens.Why does this error happen?How can I fix this? -
DJANGO timezone setting and auto_now result are difference
I have setup my django and i have a model with an auto_now=True, because my SQL server timezone has been set to 'Asia/Shanghai', so i would like to set django to this timezone too. i have set it up TIME_ZONE='Asia/Shanghai' and Use_TZ=True. I checked that datetime.datetime.now() can give me the right timezone time. but the django.utils.timezone.now() time is still UTC time as shown in below shell output. I think this explain why my auton_now object timezone is always in UTC. I am planning to set in models.py the default to use my datetime.datetime.now() object, but i have a warning about this. How can i set up settings.py such that the django.utils.timezone object can be set correctly too? >>> timezone.get_current_timezone() <DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD> >>> timezone.now() datetime.datetime(2018, 1, 18, 10, 11, 0, 936572, tzinfo=<UTC>) >>> >>> datetime.datetime.now() datetime.datetime(2018, 1, 18, 18, 20, 23, 722825) -
Django Admin URL reverse to admin users
I would like to know How I can redirect admin users logged in my Django application (Django 2.0) to the user admin webpage ? In my menu, I have : <li><a target="_blank" href="{% url "admin:index" %}">Administration</a></li> But How I could redirect to /admin/auth/user ? I tried : <a target="_blank" href="{% url "admin:auth:user" %}">Utilisateurs</a> or <a target="_blank" href="{% url opts|admin_urlname:'user' %}">Utilisateurs</a> But I don't overcome to redirect to user admin page thanks to Django documentation (Django Doc) -
Django from_email defaulting to recipient
Im using Django, anymail API & mailgun to send emails from my site. I have a form where users can subscribe, At present when the email is send to the subscriber's email address, the FROM address default to a combination of their and my email domain. As an exmample: User enters test@test.com an receives email from test=test.com@mail.mydomain.com and not the one I specified of info@mydomain.com I am pretty sure the problem is within my views.py, but im not sure how to resolve. views.py def send_email(subject, html_content, text_content=None, from_email=None, recipients=[], attachments=[], bcc=[], cc=[]): # send email to user with attachment if not from_email: from_email = settings.DEFAULT_FROM_EMAIL if not text_content: text_content = '' email = EmailMultiAlternatives( subject, text_content, from_email, recipients, bcc=bcc, cc=cc ) email.attach_alternative(html_content, "text/html") for attachment in attachments: # Example: email.attach('design.png', img_data, 'image/png') email.attach(*attachment) email.send() def send_mass_mail(data_list): for data in data_list: template = data.pop('template') context = data.pop('context') html_content = get_rendered_html(template, context) data.update({'html_content': html_content}) send_email(**data) # Contact Form - home.html def HomePage(request, template='home.html'): form = ContactForm(request.POST or None) if form.is_valid(): from_email = form.cleaned_data['from_email'] # Create message1 to send to poster message1 = { 'subject': 'Test', 'from_email': from_email, 'recipients': [from_email], 'template': "marketing/welcome.html", 'context': { "from_email": from_email, } } # Create message1 to send … -
Django Raspberry Pi LCD RealTime data
I've Django 2.0 on my Raspberry Pi 3. I connected 2x16LCD to this device. I'm looking for ways to display sensor data and time on screen in real time. Here's my views.py: from django.shortcuts import render from engine.functions import lcdF def index(request): if 'temp' in request.POST: lcdF.printTemp(0,2) elif 'time' in request.POST: lcdF.printTime() return render(request, 'system/index.html') In the index.html file I've two buttons who sends POST request And here is lcdF.py: import time from datetime import datetime from engine.lib import lcd, temp config = lcd.LCD() def printWelcome(): config.lcd_clear() config.lcd_display_string("System", 1) config.lcd_display_string("aktywny", 2) def printLong(self, string, row): config.lcd_clear() my_long_string = string my_long_string = my_long_string + " " config.lcd_display_string(my_long_string[:19], row) for i in range(0, len(my_long_string)): lcd_text = my_long_string[i:(i + 20)] config.lcd_display_string(lcd_text, row) time.sleep(0.3) # self.display.lcd_clear() def printTime(): config.lcd_clear() config.lcd_display_string("ZEGAR:", 1) while True: data = datetime.now().strftime('%d.%m.%y %H:%M') config.lcd_display_string(data, 2) time.sleep(1) def printTemp(number, frequency): config.lcd_clear() config.lcd_display_string("TEMP:", 1) while True: x = round(temp.read_temp(), number) temperature = "{temp:." + str(number) + "f}" string = str(temperature.format(temp=x)) config.lcd_display_string(string + " C", 2) time.sleep(frequency) It's work inccorect, these two functions interfere with each other Is it a good idea to get data value through the while True loop? -
User Ability to Search Django Database
I am looking to create a very simple form with several drop down fields allowing users to query a database of restaurants I have created (I would like to use the fields 'food', 'city' and 'average rating'). Whilst I have found an approach to do this using separate html pages (Django form to query database (models)) I would like to implement this on one page (restaurants.html). I am using Python 3.1.0, Django 2.0.1 and Bootstrap 4.0. Appreciate all your help. My models.pyis as follows: from django.db import models import numpy as np # Create your models here. class Restaurant(models.Model): name = models.CharField(max_length=100, null=False) desc = models.CharField(max_length=100) web = models.CharField(max_length=100) phone = models.CharField(max_length=40) address = models.CharField(max_length=100) post_code = models.CharField(max_length=20) picture = models.ImageField(upload_to='images/restaurants', null=True) map = models.ImageField(upload_to='images/restaurants', null=True) FOOD = ((1,'English'), (2,'French'), (3,'American'), (4,'Indian'), (5, 'Undefined')) food = models.IntegerField(choices=FOOD, default=5) CITY = ((1,'London'), (2,'Paris')) city = models.IntegerField(choices=CITY, default=1) STARS = ((1,'One'), (2,'Two'), (3,'Three'), (4,'Four'),) CB_rating = models.IntegerField(choices=STARS, default=4) def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return self.name views.py: from django.shortcuts import get_object_or_404, render from .models import Review, Restaurant from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .forms import ReviewForm import datetime def review_list(request): latest_review_list = Review.objects.order_by('-pub_date')[:9] … -
Disable button after one week
I made a page where you can place a comment. You can also delete your comment with a delete button. What I want is that after you placed a comment you have one week to delete it. So after a week I want to hide the delete button. When trying to do this I'm getting this error: '<' not supported between instances of 'datetime.timedelta' and 'int' view: class TechnologyDetailView(DetailView): model = Technology def get_queryset(self): group_permissions = Permission.objects.filter(group__user=self.request.user) query = Technology.objects.filter(pk=self.kwargs['pk'], is_active=True, permission__in=group_permissions) for tech in query: comments = Comment.objects.filter(technology=tech) now = datetime.now() for comment in comments: comment.timestamp = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') print(comment.timestamp) age = now - comment.timestamp if age < 604800: comment.is_removable = True else: comment.is_removable = False return query template: <h3>Comments</h3> {% for comment in technology.comment_set.all %} <div class="row" style="border-bottom-style:solid; border-bottom-width:1px; border-color:gray;"> <h6 style="font-weight:bold">Written by {{ comment.user.name }} on {{ comment.timestamp }}</h6> <span>{{ comment.content|breaks }}</span> <p>{{ comment.timestamp | timesince }}</p> {% if comment.user == request.user %} <a class="modal-trigger right" href="#modal_{{ comment.pk }}">Delete Comment</a> {% endif %} <div id="modal_{{ comment.pk }}" class="modal"> <div class="modal-content"> <iframe frameborder="0" id="encoder_iframe" height=300px width="100%" src="{% url 'delete- comment' comment.pk %}"></iframe> </div> </div> </div> {% empty %} <p>There are no comments</p> … -
Django HTTP request to api
So i been trying to get this to work but at the same time i do not understand some of these code means. I'm sorry for making the question so long but i want to understand how these works. I am trying to make a HTTP request to another API to do POST and GET method using django. Based on the website code example, which is this url: https://www.twilio.com/blog/2014/11/build-your-own-pokedex-with-django-mms-and-pokeapi.html As i wanted to use HTTP Request on my API to call other API, therefore i wanted to get a better understanding of how these works and how to use it. The code is at the bottom of the website. But i will just provide the code here so it is easier for you. website code from django_twilio.views import twilio_view from twilio.twiml import Response import requests import json BASE_URL = 'http://pokeapi.co' def query_pokeapi(resource_uri): url = '{0}{1}'.format(BASE_URL, resource_uri) response = requests.get(url) if response.status_code == 200: return json.loads(response.text) return None @twilio_view def incoming_message(request): twiml = Response() body = request.POST.get('Body', '') body = body.lower() pokemon_url = '/api/v1/pokemon/{0}/'.format(body) pokemon = query_pokeapi(pokemon_url) if pokemon: sprite_uri = pokemon['sprites'][0]['resource_uri'] description_uri = pokemon['descriptions'][0]['resource_uri'] sprite = query_pokeapi(sprite_uri) description = query_pokeapi(description_uri) message = '{0}, {1}'.format(pokemon['name'], description['description']) image = '{0}{1}'.format(BASE_URL, sprite['image']) frm … -
Template in Django doesn't show same content for 2 paths
For this template, everything will show fine, but only for the first course. If I add lectures for another course, template won't show them. def courses(request, slug): con = get_object_or_404(Course, slug=slug) context = { 'course': con, 'lectures': con.lectures.all(), 'categories': con.categories.all(), } return render(request, 'courses/courses.html', context) <ul> {% for a in categories %} <li><strong>{{ a.course_category }}</strong></li> {% for c in lectures %} {% if a == c.course_category %} <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% endif %} {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} {% endfor %} </ul> -
Django templates, views merge lines in table
I have a view that aggregates columns using annotate and I am aggregating 5 columns, one of which is Sum and the others are Count. The data is received from SQL. So it looks like this: data = super().get_queryset() val = data.values('col1', 'col2', 'col3', 'col4', 'col5) final_data = val.annotate(col1=Sum('col1), col2 = Count(Case(When(type='A' then=1), output_filed(IntegerField())), col3 = Count(Case(When(type='B' then=1), output_filed(IntegerField())), col4 = Count(Case(When(type='C' then=1), output_filed(IntegerField())), col5 = Count(Case(When(type='D' then=1), output_filed(IntegerField()))) This is working to show the results, however I need to show it all in one line. This is how it displays now: List Col1 Col2 Col3 Col4 Col5 A 7895 12 0 0 0 A 0 0 12 0 0 A 2198 0 0 4 0 But I need it to show like this: List Col1 Col2 Col3 Col4 Col5 A 10093 12 12 4 0 What approach is best to achieve this, and how? -
Segmentation fault (core dumped) in django alongside server also sidconnected
i'm trying to plot line chart using Matplotlib and mpld3 with Django . its working properly but if i hit refresh button in browser to reload the page suddenly server getting stopped with error message [Segmentation fault (core dumped)] . bellow i mentioned my code . thanks in advance !! in views.py : from django.shortcuts import render from django.http import HttpResponse import matplotlib.pyplot as plt , mpld3 def index(request): fig = plt.figure() plt.plot([1,2,3,4,5],[5,4,3,2,1],'r--') g = mpld3.fig_to_html(fig) return render(request,'index.html',{'a' : g}) -
Django: ModelFormMixin not rendering form
I've got the following problem. I have a webapp where a genericListView of 'Speakers' allows the user to click on profiles - which then causes to load a detailview which displays the Speakers profile. So far so good, however, from there I want to enable the user to contact / hire the expert. This is done through a form at the bottom of the DetailView, which generates a new 'Quotation' object. So I want to display a submission/create form for the 'Quotation' object inside a genericDetailView for the 'Speaker' object. I thought I could solve this with the 'ModelFormMixin', but even though the DetailView inherets from this mixin and the 'formclass' has been set, no form appears in the template. This is the detailview class SpeakerDetail(ModelFormMixin, DetailView): template_name = 'v2templates/speakers/speaker_detail.html' model = Speaker menu_id = "speaker" form_class = QuotationForm def get(self, request, *args, **kwargs): qs = (self.model.objects.filter(status=STATE_ACTIVE) .distinct().prefetch_related(oabs, 'sociallink_set')) pk = self.kwargs.get('pk') slug = self.kwargs.get('slug', None) self.object, slug_matched = get_slug_object_or_404(qs, pk, slug) if not slug_matched and self.object and self.object.slug: return redirect(self.object) if not self.object: raise Http404 context = self.get_context_data(object=self.object) return self.render_to_response(context) And this is the ModelForm I am linking to: class QuotationForm(ModelForm): class Meta: model = Quotation fields = [ … -
Connect Django backend with Chatfuel bot
I have this problem where I have to connect a Django project with a Chatfuel bot. In my application I have certain activities that are assigned to the users registered in the panel, when these activities are updated, are about to end or you just want to know what it objective is, I have to send a message to the user through Facebook letting him know this information. The first problem I have is that I do not know how to connect the profile of my user in Django with his Facebook profile, that is, how the bot will know which activities are the ones that correspond to him based on his profile in Django. Later the second problem I have is that since they are linked, how can I send the messages through Facebook. Any ideas? -
Using Python 3 in virtualenv not working properly
python 3.5.2 run cmd ( virtualenv -p python3 venv) Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /var/www/html/python3_virtualenv/bin/python3 Also creating executable in /var/www/html/python3_virtualenv/bin/python Installing setuptools, pip, wheel... stay of execution -
How to display ckeditor in template django?
I have installed ckeditor for django and it is displayed in the admin as it should, but how do I make it display in my template. template {% extends 'blog/base.html' %} {% load crispy_forms_tags %}{%block content%} {% if user.is_superuser %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form class="form-horizontal" id="label-edit" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> {% else %} <h1 class="display-4 text-center">404 Not Found</h1> {% endif %} {% endblock %} I am using crispy forms. I want the ckeditor to appear on the template. Thanks in advance. -
django.db.utils.DatabaseError: Cannot add foreign key constraint in MultiDB
I am trying to migrate my app name notifications in to different db (name is notificationcenter) but getting error in Foreign key constraint, I know the limitations of Django in multiple database but both models (i.e notification_template, gateway_status) will migrate in same database, Please go through given details. I've also added this router in to settings.py dbrouter.py: class NotificationRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'notifications': return 'notificationcenter' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'notifications': return 'notificationcenter' return None # def allow_relation(self, obj1, obj2, **hints): # """ # Allow relations if a model in the auth app is involved. # """ # if obj1._meta.app_label == 'auth' or \ # obj2._meta.app_label == 'auth': # return True # return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'notifications': return db == 'notificationcenter' else: return False # elif db == 'default': # # Ensure that all other apps don't … -
Browsable API becomes unreadable when too many child relations
How can I limit the number of child relations listed in the HyperlinkedModelSerializer's HyperlinkedRelatedField? When there's hundreads or thousands of child relations, the whole page becomes very quickly unreadable and slow. The page-size itself is not the problem, but how many child relations are visible. class FooSerializer(serializers.HyperlinkedModelSerializer): bars = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='bar-detail') class Meta: model = Foo fields = '__all__' class Bar(models.Model): name = models.CharField(max_length=200) foo = models.ForeignKey(Foo, related_name="bars", on_delete=models.PROTECT) In the browsable API: /api/v1/foos/ { "count": 6, "next": null, "previous": null, "results": [ { "url": "http://localhost:8000/api/v1/foos/1/", "name": "Something" "bars": [ "http://localhost:8000/api/v1/bars/3/", "http://localhost:8000/api/v1/bars/4/", "http://localhost:8000/api/v1/bars/5/", "http://localhost:8000/api/v1/bars/6/", "http://localhost:8000/api/v1/bars/7/", "http://localhost:8000/api/v1/bars/8/", "http://localhost:8000/api/v1/bars/9/", "http://localhost:8000/api/v1/bars/10/", "http://localhost:8000/api/v1/bars/11/", "http://localhost:8000/api/v1/bars/12/", "http://localhost:8000/api/v1/bars/13/", ..... As you can see this list becomes very long very quickly. Would be good to cut it to max five or so. For the Form input-fields there HTML_SELECT_CUTOFF but I believe there's nothing similar to read_only=True fields? -
django make a list of objects from queryset
i have a field in models with name answer ,This field has 4 values either a,b,c and d . I am writing a view to create a list of this answer.. I have user the code platform = get_object_or_404(Platform, user=request.user, test_key=article) b = json.loads(platform.list) ans = list(Upload.objects.filter(id__in=b).values_list('answer',flat=True)) and this gives me ans as [(u'a',), (u'b',), (u'c',), (u'b',), (u'c',), (u'b',), (u'c',)] but i want the list as [a,b,c,b,c] I am stuck with this -
How to implicitly pass user from a request to corresponding serializer?
I have a following code: class Article(models.Model): ... owner = models.ForeignKey(User, on_delete=models.CASCADE) class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'owner') extra_kwargs = { 'owner': {'write_only': True}, } class ArticleList(generics.ListCreateAPIView): serializer_class = ArticleSerializer def get_queryset(self): user = self.request.user return Article.objects.filter(owner=user.id) def post(self, request, *args, **kwargs): request.data['owner'] = self.request.user.id return self.create(request, *args, **kwargs) I have to explicitly pass user from request in post method of ArticleList ApiView to satisfy ForeignKey non-empty requirement. This is fine. But I have another models with a ForeignKey to User and as a result it leads to many copy-paste lines, especially in POST and PUT methods. Does anybody knows more elegant DRY solution? -
How to get to Django server logs if server is started in Docker
Folks, I created a Django project and I started it in Docker. Therefore I don't see server logs and I need to know how POST and GET methods look like. How I can get acces to this logs? BR, Damian