Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove duplicates in the query set
I have a query set like the one below which depicts the albums and songs associated with those albums. The model name is UserSongs <QuerySet [{'id': 1, 'album': 'Sri', 'song': 'in the end','release': 2017}, {'id': 2, 'album': 'Adi', 'song': 'cafe mocha','release': 2016}, {'id': 3, 'album': 'Shr', 'song': 'smooth criminal','release': 2016}, {'id': 4, 'album': 'Mouse', 'song': 'trooper','release': 2017}, {'id': 5, 'album': 'Mouse', 'song': 'my mobile','release': 2015}, {'id': 6, 'album': 'Sri', 'song': 'my office','release': 2018}, {'id': 7, 'album': 'Sri', 'song': 'null','release': null}, {'id': 8, 'album': 'Mouse', 'song': 'null','release': null}]> In the backend, I'm converting the query set into a list. See code below: albums_songs = UserSongs.objects.filter(album__in = ['Sri','Mouse']).values('albums','songs') list_albums_songs = list(albums_songs) I'm sending this list to the front-end for displaying it in table.Sri,Mouse have multiple entries since they have released multiple songs. In the front end, these songs are displayed in a table with album and songs as entries. Each item in the query set is displayed as one row. If user wants to see only a particular album, there is a search bar where he can search for the desired album. For now, I'm displaying only Sri and Mouse.Like the one below. Album Songs Sri in the end Mouse trooper Mouse … -
Django: how to pass value from a list template to a view, static url
In my template, I have a list of users on which the connected user can click to access the profile of a user on the list. I want to retrieve the user I clicked on in my view. However, I would like to keep a static URL (to avoid having user-related settings displayed in the URL). Do you have any idea how to do that? Here is my template : {% extends "base.html" %} {% block content %} {% if userConnected.adminRole == "SuperUser" %} <h2>Members List</h2> <h3>Members from OU : {{ userConnected.ou }} </h3> {% for element in user_list %} <a href="edit_other_profile"><p>{{ element.first_name }}</p></a> {% endfor %} {% endif %} {% endblock %} What should I add to my template and what should I write in my view "edit_other_profile" to get the right user ? Thanks a lot -
Celery - Permission Problem - Create folder
I use celery (jobs manager) on prod mode for a website (Django) on a centos7 server. My problem is that in a celery task my function did not create folder (see my_function). the function def my_fucntion(): parent_folder = THE_PARENT_PATH if not os.path.exists(centrifuge_recentrifuge_work_dir_path): os.makedirs(centrifuge_recentrifuge_work_dir_path) # The folder THE_PARENT_PATH is created celery_task(parent_folder) the celery task @app.task(name='a task') def celery_task(parent_folder): import getpass; print("permission : ", getpass.getuser()) # permission : apache path_1 = os.path.join(parent_folder, "toto") if not os.path.exists(path_1): os.makedirs(path_1) # The folder path_1 is NOT created ..... some others instructions... # Singularity image run (needed the path_1 folder) I use Supervisord for daemonization of celery. celery.init [program:sitecelery] command=/etc/supervisord.d/celery.sh directory=/mnt/site/ user=apache numprocs=1 stdout_logfile=/var/log/celery/worker.log stderr_logfile=/var/log/celery/worker.log autostart=true autorestart=true priority=999 The folder path_1 is created when user=root but i want that it was not rot but apache user. celery.sh #!/bin/bash cd /mnt/site/ exec ../myenv/bin/python3 -m celery -A site.celery_settings worker -l info --autoscale 20 sudo systemctl status supervisord ● supervisord.service - Process Monitoring and Control Daemon Loaded: loaded (/usr/lib/systemd/system/supervisord.service; disabled; vendor preset: disabled) Active: active (running) since lun. 2018-10-15 09:09:05 CEST; 4min 59s ago Process: 61477 ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf (code=exited, status=0/SUCCESS) Main PID: 61480 (supervisord) CGroup: /system.slice/supervisord.service ├─61480 /usr/bin/python /usr/bin/supervisord -c /etc/supervisord.conf └─61491 ../myenv/bin/python3 -m celery -A Site_CNR.celery_settings worker … -
2 submit buttons on one form
Within a form, I have two submit buttons. Depending on which button the user clicks on, I want the redirect on form.is_valid() to either be page A or page B. Do you know how I might be able to attach a different value to each submit button and pass this value on the POST request so that I can evaluate it in my view? THanks! -
Wild card pattern in Python url
I am new in Django and need url pattern to match everything (particularly uuid). The question and answer may seem very simple, but I need your help here. The below is my code: # parent urls.py urlpatterns = [ path('admin/', admin.site.urls), path('alerting/', include('alerting.urls')), ] # alerting/urls.py urlpatterns = [ path('', views.index, name='index'), path('test', views.test, name='test'), path('.*', views.test, name='uuid'), ] I've tried in many ways but could find how make it work. -
.DATABASES is improperly configured. Please supply the ENGINE value
(mydjango) C:\StockMarketResearch\Else\StockAnalysisApp>python manage.py dbshell Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\mydjango\lib\site-packages\django\core\management__init__.py", line 338, in execute_from_command_line utility.execute() File "C:\mydjango\lib\site-packages\django\core\management__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\mydjango\lib\site-packages\django\core\management\base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "C:\mydjango\lib\site-packages\django\core\management\base.py", line 441, in execute output = self.handle(*args, **options) File "C:\mydjango\lib\site-packages\django\core\management\commands\dbshell.py", line 19, in handle connection.client.runshell() File "C:\mydjango\lib\site-packages\django\db\backends\dummy\base.py", line 21, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details -
How to make multi filter on django orm?
I have a table with fields: No. | name | utc_date | utc_time | ------------------------------------ 1 | John | 181014 | 140104.12 | 2 | Mark | 181014 | 152312.01 | 3 | Kim | 181015 | 092345.23 | 4 | Jane | 181015 | 234543.32 | How can I create Django ORM query like that: ? (utc_date >= 181014, utc_time >=150000.00) AND (utc_date <= 181015, utc_time <= 150000.00 ) *I tried to make as shown below, but it doesn't work: MyTable.objects.filter(utc_date__gte=181014, utc_date__lte=181015, utc_time__gte=150000.00, utc_time__lte=150000.00) -
How to display specified groups list while creating users in django application instead of displaying all groups list
enter image description here The user logged in as an access to only Wild group.But when creating user it showing all the groups list -
Image not being displayed in template using django-ads
I am new to django ads. I have created a project called mysite and inside that project I have created an app called advertisements. See the below. The template which renders the add is as follows: {% extends "advertisement/base.html" %} {% load static %} {% load ads_tags %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'advertisement/css/index.css' %}" /> {% endblock %} {% block scripts %} <script type="text/javascript" src="{% static 'advertisement/js/index.js' %}"></script> {% endblock %} {% block title %}Java Coffee House{% endblock %} {% block content %} <div class="row justify-content-center"> {% render_ads_zone 'content' %} </div> {% endblock %} In my template, the link is working fine. However, the image is not loaded. The console says Not Found: /advertisement/iphone.jpeg. The admin page where I add the image dumps the image under the project folder. Any ideas on to solve this error? -
django mutually exclusive boolean fields^
First time post here :) I'm learning python and the django framework through a simple photo album app. I'm working through the admin site only for now, and django is v.2.1. There's a photo-album table and an images table. A photo album can have many images and an image can be associated with many photo albums, so I modelized a many-to-many relation through an intermediary table. My photo album change page has an inline for the images in it. All this is straightforward and works well. Apart from the two parent tables's PKs, the intermediary table has an extra boolean field, "isCover", so that a user can select an image in the photo album to act as a cover. However, in the inline there is no way to enforce only one image is checked as cover. Plus, I'd like the functionality that the first image be automatically selected as cover if the user selects none. How can that be accomplished? Thanks in advance for any insights! Joe -
Django acquire data from different layer
I have one django project with the structure like: In the main page, there are many topics. In each topic, there are many entries related to it. The topics and entries information could be the inputs by visitors. Now I need to acquire the data from the entries by groups. For example, for topic "1", entries include "ss", "sss", "ssss"; topic "2", entries include "aaa", "aaaa". I need the acquired data to be: [[(u'ss',)], [(u'sss',), (u'ssss',)], [(u'aaa',), (u'aaaa',)]]. May I know how could edit the coding in the function of view.py. I proposed like: def button_view(request): import sys topics = Topic.objects.filter(owner=request.user).order_by("date_added") a_content_list = [] for a in topics entries = Entry.objects.get(topic = a) a_content_list.append(entries) Could the a_content_list be what I want? Thx! -
Django Logging - How to remove SQL query in logging file
I try to make Django Logging to log error from server. Now my code: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(PROJECT_LOCAL_URL, 'mylog.log'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } When I check mylog.log, it have too many sql queries string - SELECT FROM, which I want not to see. How can I config this? How can I remove all sql queries in logging file? -
Selectize + Bootstrap 4
I wanted to add to my webpage a simple tagging option, using Selectize for Django. I first created a ModelForm as follows: class Tag_forms(ModelForm): class Meta: model = case fields = ['tags'] widgets = { 'tags': tag_widget.TagSelectize(attrs={ 'placeholder': '', }), } def __init__(self, *args, **kwargs): super(Tag_forms, self).__init__(*args, **kwargs) self.fields['tags'].widget.attrs.update({}) After pasting the above ModelForm into HTML doc via Django tagging + attachment of JS and CSS for Selectize, I get a working tag window - so far so good. However, the problems start when I try to implement some Bootstrap form formatting into the mix. The HTML structure this Django implementation builds looks like so: Which produces view like this one: However, when I try and add form-control class to the "selectize-control" to format everything in it nicely and align it with Bootstrap goodness, I get the following: Its functionality is intact, but "selectize-control" and "selectize-input" divs get misaligned. I can apply form-control to the inner one, but then I lose the ability to see effects of adding "is-valid / is-invalid" classes to any of these divs - green/red frame is just not visible. Not only that, I cannot really add id or any real attribute to the 2nd inpu … -
graphql code organization for scalable projects
Think that we have a big project with lots of apps which results in lots of queries and mutations. For such projects, how do you people handle the graphql code architecture. Let's take an example. I have an app called accounts. It will have queries and mutation related to user and profile. The folder structure i am using is every app will have graphql folder which then will have schema.py and mutations.py. The code is arranged something like this for now schema.py class User(DjangoObjectType): class Meta: model = CustomUser filter_fields = { 'email': ['exact', ], } exclude_fields = ('password', 'is_superuser', ) interfaces = (relay.Node, ) class ProfileNode(DjangoObjectType): class Meta: model = Profile interfaces = (relay.Node, ) class UserQuery(object): user = relay.Node.Field(User) users = DjangoFilterConnectionField(User) # resolve_users is not needed now class ProfileQuery(object): profile = relay.Node.Field(ProfileNode) profiles = DjangoFilterConnectionField(ProfileNode) class UserProfile(ObjectType): profile = Field(ProfileNode) def resolve_profile(self, info, **kwargs): if id is not None and info.context.user.is_authenticated: profile = Profile.objects.get(user=info.context.user) return profile return None class Viewer(ObjectType): user = Field(User) def resolve_user(self, info, **kwargs): if info.context.user.is_authenticated: return info.context.user return None mutations.py class Register(graphene.Mutation): """ Mutation to register a user """ class Arguments: first_name = graphene.String(required=True) last_name = graphene.String(required=True) email = graphene.String(required=True) password = graphene.String(required=True) … -
DRF Viewset custom "create" method does not call serializer custom "create" method
referring to the code below. What I'm trying to achieve is to create a new instance of "Survey" when an "Answer" is created. The POST request sent is: {"choice":123} First problem: "survey": [ "This field is required." ]. Removing "survey" from the serializer fields gets around this but I'm not sure this is correct. Note that both "Survey" & "Choice" have one-to-many relationship with "Answer" via foreign key. Second problem: The custom create method in the serializer is not called because the test print "HELLO" I put in is not executed and nothing is created. Been stuck on this for a while, any ideas guys? Much appreciate it. class AddAnswerView(viewsets.ViewSet): # serializer_class = AnswerSerializer def create(self, request, *args, **kwargs): data = request.data.get( "items") if 'items' in request.data else request.data many = isinstance(data, list) serializer = AnswerSerializer(data=data, many=many) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = models.C fields = ('id',) class SurveySerializer(serializers.ModelSerializer): class Meta: model = models.Survey fields = ('id',) class AnswerSerializer(serializers.ModelSerializer): survey = SurveySerializer choice = ChoiceSerializer class Meta: model = models.Answer fields = ('choice', 'survey') def create(self, validated_data): print('HELLO') user = self.context['request'].user new_survey = models.Survey.objects.create(user=user) answer = models.Answer.objects.create(survey=new_survey, **validated_data) return answer -
Ajax response appending in a table
I am doing a django project where in in ajax, i am calling my function and getting response in array then i am appending those response in my html table. <script> $(document).ready(function(){ $.ajax({ method : 'POST', url : '/home', data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(data){ var res = $.parseJSON(data); var trHTML = ''; if (res.code == '200'){ for(i in res.data){ console.log(res.data) console.log(res.data[i].id); trHTML += '<tr><td><div><img src=' + res.data[i].poster_url + '>' + '</td><td><div>' + res.data[i].name + '</div><div></div></td><td>' + res.data[i].content_types_id + '</td><td>' + Africa + '</td><td><ul>' + '</ul><td>'; } } else { alert('Cart is empty'); } $('#table-list').append(trHTML); }, error: function(data){ console.log(data); }, }) }) </script> html codes <table id="seller-content-list" class="col-md-12 table-bordered table-striped table-condensed cf"> <thead class="cf"> <tr> <th width="10%">&nbsp;</th> <th width="30%" class="numeric">File Name</th> <th width="15%" class="numeric">Content Type</th> <th width="16%" class="numeric">Geo Rights</th> <th width="16%" class="numeric">License</th> <th width="13%" class="numeric">Action</th> </tr> </thead> <tbody> <tr> <td data-title=""><div class="product"><img src="{% static 'images/p1.jpg' %}"></div></td> <td data-title="File Name"> <div class="fl">The Lost World: Jurassic Park</div> <div><button type="button" class="btn btn-white"><i class="fas fa-upload"></i> Upload Video</button></div> </td> <td data-title="Content Type">Video</td> <td data-title="Geo Rights">Asia Pacific, Africa</td> <td data-title="License">Active Licenses:16</td> <td align="left" valign="middle" data-title="Action"> <ul class="action_icon"> <li><i class="fas fa-pencil-alt"></i></li> <li><i class="fas fa-trash-alt"></i></li> <li><i class="fas fa-ban"></i></li> </ul> </td> </tr> But problem is when … -
Working/Sharing my Django project on the cloud
Hey I have been using a OneDrive to work on my django projects so far but came upon some issues (for example using i18n translation module e.g. making a django-admin makemessages was showing an error). Now i use a USB drive to store my django projects and work on different computers but it's also inconvenient and today also had some problems with unsaved files etc. ? Do you know what is the best cloud on which i can store my projects and work on my Pycharm django projects online ?? (i would prefer a free plan solution). I've been looking on google and stackoverflow for answers but couldn't find the right answer ... -
Python - Int not iterable -- how to convert a number into a list of that length?
I am making an application in Django and Python. I am a student of Web Development. I have a start date and an end date for a trip model in my database. I am able to get the number of days in a trip by subtracting the two. My question is, based on the number of days in the trip (x) , I would like to create (x) number of html elements (divs). When I try to do this, I get an error message saying that and Int is not iterable. How do I convert x number of days in a trip to a list with x items in it? Thank you Code: class Trip (models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name='trips') start_date = models.DateField() end_date = models.DateField() trail = models.CharField(max_length=300) permit = models.URLField(blank=True, null=True) completed = models.BooleanField(default=False) location = models.CharField(blank=True, max_length=400) lat = models.DecimalField(blank=True, null=True, max_digits=9, decimal_places=6) lng = models.DecimalField(blank=True, null=True, max_digits=9, decimal_places=6) created_at = models.DateField(auto_now_add =True) def __str__ (self): return self.trail def total_days(self): return (self.end_date - self.start_date).days -
Django - How to include a map in a modal form and save coordinates to database when user selects point on map?
I am working on a project and a student of Web Development. I am making an application in Django. When a user creates a new trip with a form I've made, I want to add a map to that form so that users only have to click a point on a map in order to get coordinates to save to the database for that trip. I want to save coordinates for every new trip so that I can render a map on each user's profile page that shows them markers of every trip they've taken that is in the database. Please help! Thank you -
Django - Permissions to proxy model
I create a proxy model from auth.Group model, that I want to apply permissions to it. proxies.py class InstitutionOwnerGroup(Group): # Gestores pk = 1 is_superuser = False is_staff = False perm = 'can_manage_institutions' class Meta: proxy = True permissions = ( ('can_manage_institutions', 'Gerencia Instituições'), ) data migration # Generated by Django 2.1.1 on 2018-10-14 23:30 from django.db import migrations from horsy.apps.accounts.proxies import InstitutionOwnerGroup def create_owner_group(app, _schema): InstitutionOwnerGroup.objects.create( name="Gestores" ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_add_admin_user'), ] operations = [ migrations.RunPython(create_owner_group) ] Gestores model in admin panel: The given permission can_manage_institutions isn't been applied to model in data migration. Can someone help me ? -
Django form encoding
I am sending data over to my view using a form. When I send the char ó it is printed in the view as the char �. Any idea how to have it encoded correctly? views.py: # -*- coding: utf-8 -*- def myView(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): title = form.cleaned_data.get('title') print(title) # prints � instead of ó forms.py: # -*- coding: utf-8 -*- class MyForm(forms.ModelForm): title = forms.CharField(required=False) myform.html: <form action="/results/" method="post" content='text/html; charset=UTF-8'>>{% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.title.errors }} <label for="id_name">Title</label> {{ form.title }} </div> <button type="submit"> <i class="fa fa-thumb-tack"></i> Search </button> </form> -
Django-Oscar URLs for Django 2.0?
Django-Oscar has apparently been updated to Django 2.0. I am new to Django, I am not sure how I would update the URLs that are mentioned in the Oscar Tutorial: from django.conf.urls import include, url from django.contrib import admin from oscar.app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), # The Django admin is not officially supported; expect breakage. # Nonetheless, it's often useful for debugging. url(r'^admin/', include(admin.site.urls)), url(r'', include(application.urls)), ] This is the url that is currently available: urlpatterns = [ path('admin/', admin.site.urls), ] So, do this mean that I would change the django-oscar URls to?: path(r'^i18n/', include('django.conf.urls.i18n')), -
How to access queryset's fields inside an annotate() inside a Prefetch?
class PlayerProfile(models.Model): nickname = models.CharField(max_length=255) class Team(models.Model): players = models.ManyToManyField(PlayerProfile, blank=True, related_name='teams') captain = models.ForeignKey(PlayerProfile, null=True, on_delete=models.SET_NULL) . class TeamView(viewsets.ModelViewSet): ... def get_queryset(self): queryset = Team.objects.all() queryset = queryset.prefetch_related( Prefetch( 'players', queryset=PlayerProfile.objects.annotate(is_captain=F('?')) )) return queryset On the line queryset=PlayerProfile.objects.annotate(is_captain=F('?')) I basically want to annotate to each player a field is_captain being true or false based on the captain field from the Team object. Is this is possible? -
How express SQL query using Django ORM?
I have an example application of the shop. Full application code is available at https://github.com/dry-python/tutorials/tree/master/django In this example, User can buy a subscription for different categories of the content. The user can subscribe for one day, one month or one year. Each period has its own price. Price can change in time, so Price model stores not the actual prices but the whole Price history. The Price with the most recent from_date value is the actual one. This is the Price model. class Price(models.Model): category = models.ForeignKey(Category, related_name="prices", on_delete=models.CASCADE) from_date = models.DateField() cost = models.DecimalField(max_digits=10, decimal_places=2) period = models.IntegerField() I want to select the cheapest (from actual) price for each category. I can express this with following SQL query. SELECT "category_id", MIN("cost") FROM "example_price" WHERE "id" IN ( SELECT "id" FROM "example_price" WHERE "category_id" IN (1, 2, 3, 4) GROUP BY "category_id", "period" HAVING "from_date" = MAX("from_date") ) GROUP BY "category_id" How I can express it with Django ORM? Regards, Artem. -
How to get value between two span id in python using soap
Now the code below can get only one value from one span id . I want to get all values between two span id for example from RAOCSTD2018-10-27 to RAOCSTD2018-10-30 from bs4 import BeautifulSoup html = """<tr id="RAOCSTD-dates" class="availability selected"> <td title="3" class="dt20181027 d6"> <span id="RAOCSTD2018-10-27">$739</span></td><td title="3" class="dt20181028 d0"> <span id="RAOCSTD2018-10-28">$686 </span></td><td title="3" class="dt20181029 d1"> <span id="RAOCSTD2018-10-29">$686 </span></td><td title="3" class="dt20181030 d2"> <span id="RAOCSTD2018-10-30"> $686 </span></td> </tr>""" soup = BeautifulSoup(html, 'html.parser') allvaluesbetweentwospanid = {} for li_tag in soup.find_all('tr', {'class':'availability selected'}): # for span_tag in li_tag.find_all('li', {'class':'list-group-item'}): # field = span_tag.find('span', {'class':'strong'}).text value = li_tag.find('span', {'id':room_instance + chek_in}).text need[field] = value