Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nested serializer showing null data
from rest_framework import serializers from .models import PlayerTable, ChildTable class ChildTableSerializer(serializers.ModelSerializer): # x= ChildTable.objects.all().values class Meta: model = ChildTable fields = ('season','goals','fk') # fields =('fk',) class PlayerTableSerializer(serializers.ModelSerializer): player_details = ChildTableSerializer(many=True, read_only=True) class Meta: model = PlayerTable fields = ('player_details',) -
what should be the django path parameteres for gunicorn command?
i'm building the image with this Dockerfile FROM python RUN mkdir /app WORKDIR /app RUN pip install gunicorn django COPY ./requirements.pip /requirements.pip RUN pip install -r /requirements.pip COPY ./app/* ./ EXPOSE 8000 CMD ["gunicorn", "--chdir", ".", "--bind", ":8000", "app_platform.wsgi:application"] when i run the container, it exits complaining about unable to change application directory. I'm sure it's about gunicorn command, so are my arguments valid to the CMD section? My app resides at the /app dir as indicated by Dockerfile -
I want to change the time calculation format (django models, virtual field)
model field code is this created = models.DateTimeField(auto_now=True) @property def now_diff(self): return timezone.now() - self.created I have a question about django time circulation using virtual field current output of time circulation is 5:26:34.349728 But I want to 5:26:34 Is there a way? thanks for let me know ~! -
Django Prevent page from refreshing
So guys I have 2 problems. I am pretty new in Django and Python. I build a page with a form and I can input data in those fields, I receive the data do some operation with it and pass back other variables which are shown in a div under the form field after a button was clicked. It is actually working but the page refreshes so I can see the result for only one second. Second Problem is that I have to click twice on the button so it shows me the right result. Example: First button click Result shows x, then I use other input and click button, result shows x after I click the button again it shows the right result, how do I fix this problem aswell. And do you have suggestions how to make this system better? I am already really thankful for your help. My view file: from django.shortcuts import render,redirect from django.http import HttpResponse from pages.forms import NameForm import requests # Create your views here. def home_view(request,*args,**kwargs): api_key = "RGAPI-9b573263-7b5a-433e-9e82-a973f5db4749" name = "" tier = "" rank = "" lp = 0 if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): summoner = … -
Django admin changelist - link to related model change page
Is there a built-in way to tell Django to show links to related models in changelist? If we have models School and Student, I want display School in Student changelist as a link to School object change page. I can do that old way: class StudentAdmin(..): list_display = [...,'school',...] def school(..): return mark_safe(..link..) Is there a built in way? Something like: class StudentAdmin(..): ... related_change_links = ['school'] -
Update variable in view with specific data
I have view: def film(request, zanr, godina): filmovi = {'1': {'name': 'Osvetnici: Zavrsnica', 'zanr': ' Action', 'godina': '2019'} , '2' : {'name': 'It Chapter Two', 'zanr': ' Horror', 'godina': '2018'}, '3' : {'name': 'Kapetanica Marvel', 'zanr': ' Action', 'godina': '2019'}, '4' : {'name': 'Aladdin', 'zanr': ' Comedy', 'godina': '2019'} } data = filmovi.get(id, {}) return render(request, 'film.html', data) So I wonder how to make for loop to fill variable "data" with all movies with "zanr" = "Action" and "godina" = "2019"? What is the best way to call that view from "urls.py"? re_path('film/zanr/(?P[0-9]+)/', views.film, name='film') I guess "godina" should be good with "(?P[0-9]+)" as that is year (integer) but how can I take parameter "zanr"? It should be string without numbers. Thank You all. -
Suggest some Facebook social share package with examples to share image and description dynamically [on hold]
Api's from Django rest framework, I am unable to share image and description to Facebook from angular 5 websites, please help -
Output of Xlswriter in django DateField isn't correct
I used the xlsxwriter package to get the excel output form my django project(Exactly form my models). These are my fields: date1 = models.DateField(default=datetime.date.today) date2 = models.DateField(null=True,blank=True) The output of all fields is completely and correctly embedded in Excel, the only problem is that the fields of DateField do not output correctly. The output of these fields: 43603 What should I do to fix the problem? -
LookupError: No installed app with label 'admin' when running runserver in a environment created using anaconda
I am new to django and am trying to do the tutorial on django for the on-line portal. I have done the below on two different machines but am getting the below error: I have created a environment using anaconda I have activated the environment using conda activate envName I have created the django project I am following the django tutorial Get the following error when running python manage.py runserver (testenv) C:\Users\bradley\Documents\Web Sites\training>python manage.py runserver Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception0.with_traceback(_exception[2]) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\bradley\AppData\Local\Continuum\anaconda3\envs\testenv\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File … -
How to have any html content in a Bootstrap popover?
I'm trying to create some popover and I'd like to have a form in the popover. I look every where in the Internet and nothing worked correctly. If someone can give me some help, or already have a solution, I'll be glad. -
Is Django-InPlaceEdit compatible with Django after v1.8
InPlaceEdit documentation states that it is compatible with Django >= v1.2 (https://django-inplaceedit.readthedocs.io/en/latest/install.html) however it appears that it is not compatible after v1.8. The InPlaceEdit urls.py file utilises the old 'patterns()' function which is no longer supported since v1.8 (https://docs.djangoproject.com/en/1.9/ref/urls/). Is the issue I've identified the problem or have I made a mistake somewhere else? If this is the cause of the problem - is there a work-around for this? I am using the following versions: (Python 3.7.0, Django 2.1.7, JQuery 3.3.1) I have attempted to implement InPlaceEdit with the following code additions (as per the InPlaceEdit instructions): In base.html -> added: {% load inplace_edit %} Where static files are loaded -> added: {% inplace_static %} In settings.py INSTALLED_APPS -> add entry: INSTALLED_APPS = ( #.....................# 'inplaceeditform', ) In settings.py -> added: TEMPLATE_CONTEXT_PROCESSORS = ( #...# 'django.core.context_processors.request', #...# ) In urls.py -> added entry to urlpatterns: urlpatterns = [ # path(r'^inplaceeditform/', include('inplaceeditform.urls')), # ] Note: This is slightly different to the instructions as the syntax for this version has changed InPlaceEdit instructions & app uses the old syntax where the patterns() function is used. The following code is used in the InPlaceEdit url.py file. try: from django.conf.urls import patterns, url except … -
Filter by m2m field
I have two models: User and Company class Company(models.Model): name = models.CharField(verbose_name=_('Name'), max_length=255) archived = models.BooleanField(verbose_name=_('Company status'), default=False) class UserToCompanies(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) date_joined = models.DateTimeField(default=timezone.now) class User(LoggerModelMixin, AbstractBaseUser, PermissionsMixin): companies = models.ManyToManyField(Company, through='UserToCompanies') I need to get users qs only with users with at least one active company. If user has only archived companies I'm not expecting it's instance in qs. Is it possible in django without million DB requests? -
How to reindex resampled pandas DataFrame with missing dates keeping current values
I have a dataframe whose index is a subset days of a month. I want to add all the days, from 1st to last, filling not existing values to 0 and keeping existing ones. I've tried with reindex, but all tries ends with missing data. This is my sample DataFrame: checkin_date checkout_date duration 0 2019-05-20 08:48:09.630928+00:00 2019-05-20 09:51:55.130997+00:00 01:03:45.500069 1 2019-05-20 08:39:12.660055+00:00 2019-05-20 09:51:55.130997+00:00 01:12:42.470942 2 2019-05-19 16:38:15.195097+00:00 2019-05-20 08:20:49.860755+00:00 15:42:34.665658 3 2019-05-19 16:20:29.513691+00:00 2019-05-20 07:41:46.928414+00:00 15:21:17.414723 4 2019-05-07 12:06:02.255836+00:00 2019-05-07 17:30:22.550536+00:00 05:24:20.294700 5 2019-05-07 11:00:19.765565+00:00 2019-05-07 11:10:33.792748+00:00 00:10:14.027183 I do this to resample: df.set_index('checkin_date').resample('D').sum() which gives me the DataFrame from first existing date in the month to last existing date: duration checkin_date 2019-05-07 00:00:00+00:00 0 days 05:34:34.321883 2019-05-08 00:00:00+00:00 0 days 00:00:00 2019-05-09 00:00:00+00:00 0 days 00:00:00 2019-05-10 00:00:00+00:00 0 days 00:00:00 2019-05-11 00:00:00+00:00 0 days 00:00:00 2019-05-12 00:00:00+00:00 0 days 00:00:00 2019-05-13 00:00:00+00:00 0 days 00:00:00 2019-05-14 00:00:00+00:00 0 days 00:00:00 2019-05-15 00:00:00+00:00 0 days 00:00:00 2019-05-16 00:00:00+00:00 0 days 00:00:00 2019-05-17 00:00:00+00:00 0 days 00:00:00 2019-05-18 00:00:00+00:00 0 days 00:00:00 2019-05-19 00:00:00+00:00 1 days 07:03:52.080381 2019-05-20 00:00:00+00:00 0 days 02:16:27.971011 Which is perfect. But I need to complete the DataFrame with the missing dates of the month: … -
Use filename as name of file when downloading from s3 using boto3
I'm uploading a file using boto3 like this: client = boto3.client('s3', aws_access_key_id = id, aws_secret_access_key = key client.upload_file('tmp/test.pdf', 'bucketname', 'test.pdf') Then I generate a download link using generate_presigned_url url = client.generate_presigned_url( ClientMethod = 'get_object', Params = { 'Bucket': 'bucketname', 'key': <randomhash> } ) When I download the file on the link it's named after the key which is a random unique hash - with no extension - I want to give it a specific filename with extension.How can I do that? -
Annotate response of query based on week number
I have a query like this using the Django ORM: query_set.annotate( metrics ).annotate( ....blah blah.... ).annotate(title=Concat('date__year', Value('*'), 'date__month')) I expect the title field to be like 2019-05 or similarly week number (__week) of the year such as 2019-30 that means the 30th week of 2019. -
if Python 2.x source code and applies a transform it into valid Python 3.x code?
I have changed between the versions, showing how to change from Python 2-style to Python 3.1-style. I'm getting a SyntaxError on a file that was generated by the system itself Django/config/_init_.py -
What is the proper way to make a field on Django admin form readonly
Is there a way to make a field read-only based on a another field value (it's a Boolean field). So when the admin checks the Boolean field the input field becomes read-only. -
Django QuerySet: filter by 'value LIKE column'
I have an SQL query to determine the longest matching prefix matching a given input string. The use case is to find the rate to call a given destination, which is determine by multiple rows in database. The most specific matching prefix is the one to use. So in raw SQL it looks like this: SELECT * FROM rateplan_rates WHERE '3212345789' LIKE CONCAT(prefix, '%') ORDER BY CHAR_LENGTH(prefix) DESC LIMIT 1 In the above example, the destination is 3212345789. In the real application this is backed by caching mechanisms and more stuff, but it comes down to that. I want to accomplish the same in our Django project for an API call, and I'm aware that I can use raw SQL there too, but I was wondering if there was a way to do in Django "queryset-language". I'm stuck with this: RateplanRate.objects \ .annotate(prefix_length=Length('prefix'), prefix_match=Concat('prefix', '%')) \ .filter('search_value LIKE prefix_match') \ .order_by('-prefix_length')[0:1] The missing part is the search_value LIKE prefix_match of course. Is this possible or should I just fall back to raw SQL? -
How to define ArrayField to django forms
How to define ArrayField in django form I have some function params for which I want to add validation so I created a form and one of the function parameter is list. How can I define that in forms from django.contrib.postgres.fields import ArrayField class SampleParams(forms.Form): num = forms.IntegerField() li = ArrayField(forms.CharField(max_length=100, required=False)) but I think ArrayField is related when I want to store data in database but my case is just to validate the params but not store data -
Set variable in PostgreSQL trigger which can be seen in Python/psycopg2
I am hunting a non reproducible in a production environment. I can detect the buggy change in a postgres trigger. Since it is production code I must not raise an exception. I can only use logging. If I could see the stacktrace of the python interpreter, I could see which codes the change which I am hunting. But how to get this interpreter stacktrace, if the condition is detect in the db trigger? I could set a variable in the db trigger which gets checked after each sql statement. If the value is true, then I log the current stacktrace. Then I can see which code executes the buggy change. But how to set the variable? The value should only be visible to the current psycopg2 connection. Other way to solve this: I guess LISTEN+NOTIFY could is not a good solution, since it is async. The interpreter would already execute other code in the moment the notify event would get received. -
How to create custom permission for specific fields in model?
I have created some model and i want to create user group which can only edit one field on model. For example if i have Car model (model, brand, registration) and i have one basic user, that user should onlyo change registration field. Is it possible to do that? -
Django queryset with recursive many-to-many and result displayed
I would like to get your help in order to find a solution to my issue by handling many-to-many field and display the result. Expected result: I have a list of content version in my application (e.g : 8th Edition, 9th Edition, 10th Edition...) and for each one, I have a list of collections with subversion (toto 9.8, toto 9.9, toto 9.10, toto 10.0, ...). I'm trying to display a dynamical navbar which contains tabs according to content version. Each tab contains list of subversions. Tab 9th Edition contains 9.8, 9.9, 9.10, ... Tab 10th Edition contains 10.0, ... --------- My model: I have a model file which has: class NavbarMenuSettings(models.Model): """ A class to manage navbar menu of the application """ collection = models.ManyToManyField('publication.Collection', related_name='collection_list', symmetrical=False) application = models.ForeignKey('publication.WebApplication', verbose_name=_('application'), related_name='application', on_delete=models.CASCADE) title = models.CharField(max_length=30, verbose_name=_('title'), default=('Xth Edition (Current)')) order = models.PositiveSmallIntegerField(default=1, verbose_name=_('menu order'), blank=True, null=False) display = models.BooleanField(verbose_name=_('Display menu'), default=True) class Meta: verbose_name = _('menu setting') verbose_name_plural = _('menu settings') I have a menu.py file which let to handle my navbar: def list_of_edition(): """ Return list of editions """ instance = NavbarMenuSettings.objects.filter(display=True).order_by('order') return instance edition_children = () for instance in list_of_edition(): edition_children += MenuItem(instance.collection.all(), reverse('home'), weight=150, separator=False), for … -
How change only field that user entered not all field?
I create custom UserChangeForm and I set all field to required=False and then when user changes one field in that form all information in database change and if user leaves one field, its update that field to empty. i need only change field that user entered in form and other field don't change in database. I tried : class UserInfoChangeForm(UserChangeForm): last_name = forms.CharField(label="",max_length=100,required=False) username = forms.CharField(label="", required=False) channel_name = forms.CharField(label="",max_length=100,required=False) class Meta: model = CustomUser fields = ('username', 'channel_name','last_name') def __init__(self, *args, **kwargs): ' super(UserChangeForm, self).__init__(*args, **kwargs) self.fields.pop('password', 'email') -
How to handle django backend request for logged in user in a RESTfull manner?
I am developing a web platform that provides licence handling (e.g. creation, invoicing, downloading) for a specific software. Backend is django 2.1.7 and frontend angular. I have the following use case and I want to make sure it respects REST architecture and that it is future proof (avoid pitfalls). So I have 2 apis: ip/userprofiles ip/licences These 2 apis are protected and can be accessed only after log in. In my current implementation the GET requests for these 2 api's return only data specific to the logged in user by extracting the user id and name from the request.user (so for the authenticated user) information. User with user1 name logged in (NOT admin). GET ip/userprofiles will return user1 profile. GET ip/licences will return user1 licences. Another use case would be that the admin should have access to all licences and all users and for this I do a check to see if the request.user is admin. User with user10 name logged in (user10 IS admin): GET ip/userprofiles will return ALL users profiles. GET ip/licences will return ALL licences (for all user). For admin users the apis allows also filtering by users using a query string parameter. Is this approach ok … -
Django, LinkedIn oAuth2.0 raises save() prohibited to prevent data loss due to unsaved related object 'user'
I am using LinkedIn oAuth2.0 and it successfully fetched details from LinkedIn but it raises an error:save() prohibited to prevent data loss due to unsaved related object 'user'. What's missing here?