Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create query using Django Models with grouping , average and "IN"
Does anyone know how to build such raw query: SELECT week_number, part, type, AVG(col1), AVG(col2), AVG(col3), ( AVG(col1) + AVG(col2) + AVG(col3) ) as Total FROM table1 WHERE location = 'TgR' AND week_number BETWEEN 38 AND 42 AND part IN ('Q', 'F') GROUP BY week_number, part, type in Django model ? completely have no idea how to do this Thanks in advance, -
"PyCharm can't check if the following file been updated" when doing makemigrations/migrate
When I use PyCharm's manage.py terminal to do a makemigrations or migrate I have the following warning message: PyCharm can't check if the following file been updated: [filepath] for a hundred of files located inside my webpack and babel-preset-es2015 folders, within my static/node_modules folder The command is executed properly, but I would like to get rid of these hundreds of red warnings in the terminal. Especially since I think the migrations takes longer to be executed since I have those. Can I somehow tell PyCharm to stop checking my node_modules or even static folders? -
Django on Apache redirects incorrect
I am currently hosting my Django site on an Apache server. The Django site works fine when hosting it locally, but when I host it from the server any time you attempt to navigate to a different part of the site there's an error. As it stands you can get to the home page by navigating to example.com/djproj this pulls up the login screen as it should. When you enter your credentials and hit the submit button it takes you to example.com which is not supported, however if you manually navigate back to example.com/djproj it takes you to the home screen and you're logged in, clicking any of the buttons gives you a similar error. Notably, if you attempt to go to a supported url (one in the urls file) by directly typing it in, ie example.com/djproj/precheck/ you get a 404 stating the request URL is example.com//precheck/. I will try to provide the scripts I think applicable, but if I'm missing something I'll be happy to provide. The file structure looks like /var/www/html/djproj/cif where cif holds all the typical django files such as manage.py and the associated application folders. wsgi.py import os, sys from django.core.wsgi import get_wsgi_application path = 'var/www/djproj/grip/cif' … -
Django -Bootstrap navbar not being styled
Just started out with Bootstrap and Django. I cannot seem to get the navbar to be styled properly. The jinja part that gets loaded at the block:loads home.html get styled very nicely. The navbar however is a bunch of blue unstyled links, no background and all. I am a bit fuzzy on how web development works, but I am guessing it has to do with the bootstrap.js part, as the navbar requires some javascript? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="NAME=""> <meta name="NAME" content=""> {% load staticfiles %} <title>TITLE</title> <!-- Bootstrap core CSS and JS --> <link href="{% static 'home/css/bootstrap.min.css' %}" type = "text/css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div class="container-fluid"> <nav class="navbar navbar-inverse"> <!-- Logo --> <div class="navbar-header"> <a href="#" class="navbar-brand">LOGO</a> </div> <!-- Menu items --> <div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li class="active"><a href="#">Home</a></li> <li class="active"><a href="#">Home</a></li> <li class="active"><a href="#">Home</a></li> </ul> </div> </nav> </div> <!-- loads home.html --> {% block content %} {% endblock %} <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="mailto:mail" target="_blank">Contact</a> | <a href="https://website/" target="_blank">website</a> | <a href="#" target="_blank">Twitter</a> | <a href="https://slack.com/" target="blank">Slack</a></p> </div> </footer> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document … -
pip Installation Error for installing channels
help me please when i run this code sudo pip install channels i get this error running build_ext building 'twisted.test.raiser' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/src creating build/temp.linux-x86_64-3.5/src/twisted creating build/temp.linux-x86_64-3.5/src/twisted/test x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fdebug-prefix-map=/build/python3.5-MLq5fN/python3.5-3.5.3=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c src/twisted/test/raiser.c -o build/temp.linux-x86_64-3.5/src/twisted/test/raiser.o src/twisted/test/raiser.c:4:20: fatal error: Python.h: No such file or directory #include "Python.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- what can i do please. -
404 when requesting url of saved image in media directory using django rest framework
I am developing a django rest api using the django rest framework. The rest api manages clothing items to be shown in an android application and has a model named Clothing which has an ImageField for showing the clothing item. From the django admin, I can add an image and save the Clothing model instance by clicked the save button below, which I do click and then get a success message: I then check my media/clothing/ file which is configured to save the static files and see that the image has indeed been saved in this location: Now, back to the admin, when I navigate back to the newly created Clothing model instance it has a path showing where the image is currently being stored: When I click on it I get a 404 page not found (the X's in the url replace the actual numbers): I'll show my setup for managing static files just in case it is needed: urls.py urlpatterns = [ url(r'^add-clothing/$', views.AddClothingView.as_view(), name="add_clothing_image"), url(r'^list-clothing/$', views.ListClothingView.as_view(), name="list_clothing"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'assets'),) The image is in the correct … -
Django admin not loading
I have a problem with Django admin. I can log in and so on but I have way to create company profiles to django and diplay them on website. When I want to edit some profile my browser wont the admin page. It shows net::ERR_INCOMPLETE_CHUNKED_ENCODING. Only browser that opens the page is Microsoft Edge, strange hah! I am not a developer, so I will try my best to make it as clear as possible. -
Django Rest Framework Multi-tier Nested Serialization
I have four models I am trying to serialize into one response. I have managed to get the top three models to work as desired and I can get the bottom two to work as desired but I cannot for the life of me get the last relationship to work as desired within one serialized response. Appreciate any thoughts as at this point, I don't know if I should be focused on my serializers or the view. models.py: class Survey(models.Model): survey_name = models.CharField('survey name', max_length=100) survey_type = models.CharField('survey type', max_length=1) survey_category = models.CharField('survey category', max_length=1) questions = models.ManyToManyField(Question, through='SurveyDetail') date_created = models.DateTimeField('date created', auto_now_add=True) date_updated = models.DateTimeField('date updated', auto_now=True) class SurveyDetail(models.Model): survey = models.ForeignKey(Survey, verbose_name='survey identifier') question = models.ForeignKey(Question, verbose_name='question identifier') question_number = models.IntegerField('question number', default=0) question_type = models.CharField('question type', max_length=1, default='M') question_quiz_mode = models.BooleanField('quiz mode', default=False) question_attributes = JSONField('question attributes', null=True, blank=True) date_created = models.DateTimeField('date created', auto_now_add=True) date_updated = models.DateTimeField('date updated', auto_now=True) class Question(models.Model): question_text = models.CharField('question', max_length=200) date_created = models.DateTimeField('date created', auto_now_add=True) date_updated = models.DateTimeField('date updated', auto_now=True) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='parent question identifier') answer_number = models.IntegerField('answer number', default=0) answer_text = models.CharField('answer text', max_length=200) correct_answer = models.BooleanField('quiz answer', default=False) date_created = models.DateTimeField('date created', auto_now_add=True) date_updated = … -
Django form field accept arabic and english
this is my forms.py regex = re.compile(ur' range ?? ', re.UNICODE) class EditProfileForm(UserChangeForm): username = forms.RegexField(max_length=50, regex=regex,) class Meta(): model = User fields = ('username','email','first_name','last_name','password') if there is a way to allow arabic character in the field -
Django/Python - Instagram API - Can't extract data from access_token dictionary
I'm trying to use Instagram API to get an access_token. I've succeeded but I can't retrieve the data from the response object I get with module Requests. views.py code https://imgur.com/XkfX855 give me this : https://imgur.com/scP71G8 does someone knows how to retrieve data from this weird dictionary ? {"access_token": "bananasxxxxxxxxxxx", "user": {"id": "131banana27", "username": "bananamaster", "profile_picture": "banana", "full_name": "banana", "bio": "", "website": "", "is_business": false}} -
Django Migration Is Failing
I have a django/postgresql application. Whenever I run my latest migration, I receive the following error: ValueError: Found wrong number (0) of constraints for package(speciality, title) I believe I need to customize the migration, but what change I should make. This is the migration: operations = [ migrations.AddField( model_name='package', name='speciality', field=models.ManyToManyField(related_name='specialities', to='speciality.Speciality', blank=True), ), migrations.AlterField( model_name='package', name='title', field=models.CharField(unique=True, max_length=50), ), migrations.AlterUniqueTogether( name='package', unique_together=set([]), ), migrations.RemoveField( model_name='package', name='speciality', ), ] This is my current table configuaration for this model: sleepyfish=# \d package Table "public.package" Column | Type | Modifiers ---------------+--------------------------+------------------------------------------------------ id | integer | not null default nextval('package_id_seq'::regclass) created_at | timestamp with time zone | not null updated_at | timestamp with time zone | not null title | character varying(50) | not null description | text | status | boolean | not null price | numeric(8,2) | not null speciality_id | integer | Indexes: "package_pkey" PRIMARY KEY, btree (id) "package_speciality_id_3aeb5c97679442e4_uniq" UNIQUE CONSTRAINT, btree (speciality_id, title) "package_66db61fe" btree (speciality_id) Foreign-key constraints: "package_speciality_id_4255b58fe1ae00c0_fk_speciality_id" FOREIGN KEY (speciality_id) REFERENCES speciality(id) DEFERRABLE INITIALLY DEFERRED Referenced by: TABLE "claimedpackage" CONSTRAINT "claimedpackage_package_id_9e1da358fbb9a46_fk_package_id" FOREIGN KEY (package_id) REFERENCES package(id) DEFERRABLE INITIALLY DEFERRED TABLE "package_service" CONSTRAINT "package_service_package_id_3b0ea08bfcd8da76_fk_package_id" FOREIGN KEY (package_id) REFERENCES package(id) DEFERRABLE INITIALLY DEFERRED -
Edit multiple models just with a form django
Hi i needed some extra fields in my project for users so i made a model named Profile models.py class Profile(models.Model): user = models.OneToOneField(User,blank=False) profilepicture = models.ImageFileField(upload_to='/images/') and now im gonna make a form to edit both at the same time how to do it? -
Can I use 'RetrieveUpdateAPIView' without 'look_up' field?
RetrieveUpdateAPIView's url works with a specific field. (ex. /profile/update/<pk>) I'm getting user account from token in HTTP header, so it's difficult to include user's pk into the url. This view is my RetrieveUpdateAPIView. class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView): serializer_class = ProfileRetrieveAndUpdateSerializer # lookup_field = 'pk' def get_queryset(self): qs = Profile.objects.all() logged_in_user_profile = qs.filter(user=self.request.user) return logged_in_user_profile Should I just use views.APIView for this feature? -
Run python as web server
I am trying to setup the following opensource application: https://github.com/taroved/pol As per the readme file, i tried to run python script. python downloader.py python manage.py runserver it loads fine till the terminal is open, if i close the terminal, the process gets killed. I know, it is expected since it is child process of terminal. I tried nohub downloader.py but, the output is not sent to -
Case sensitive unique constraints on django and mysql
I have a model with a unique constraint (or rather unique_together): class ReadingMapping(models.Model): mapset = models.ForeignKey('mapping.ReadingMapset') data = models.CharField(max_length=500, verbose_name="attributes") class Meta: unique_together = ('mapset', 'data') However because I'm using MYSQL as backend, the comparison is case insensitive because of the collation/charset which is either a default of MYSQL or of Django (is this correct?) and I need it to be case sensitive. From reading around I gathered this cannot be directly in the Django model, and so I need to alter the table on the database (See this SO question) My first question is what is the correct SQL statement to alter the table, or rather the column. I'm not sure if I need to change the charset or just the collation, or which charset/collation I should be setting it to despite reading various sources. My second question is how do I make this change part of migrations (we'll have dozens of databases) can I just create an arbitrary migration file with an SQL statement in it? -
wsgi.py no module named MySite
I'm trying to start my Django application on Apache on Windows server. I have problem with the wsgi.py file. I got the following error in server log: mod_wsgi (pid=1332): Target WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=1332): Exception occurred processing WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py'. Traceback (most recent call last):\r File "C:/Apache24/htdocs/OctopusWeb/wsgi.py", line 11, in <module>\r import OctopusWeb\r ImportError: No module named 'OctopusWeb'\r mod_wsgi (pid=1332): Target WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=1332): Exception occurred processing WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py'. Traceback (most recent call last):\r File "C:/Apache24/htdocs/OctopusWeb/wsgi.py", line 11, in <module>\r import OctopusWeb\r ImportError: No module named 'OctopusWeb'\r mod_wsgi (pid=1332): Target WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=1332): Exception occurred processing WSGI script 'C:/Apache24/htdocs/OctopusWeb/wsgi.py'. Traceback (most recent call last):\r File "C:/Apache24/htdocs/OctopusWeb/wsgi.py", line 11, in <module>\r import OctopusWeb\r ImportError: No module named 'OctopusWeb'\r The OctopusWeb is the name of folder in which the settings.py and wsgi.py files are. My wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OctopusWeb.settings") application = get_wsgi_application() All files I use are in C:\Apache24\htdocs directory. Do you have any idea what I did wrong? -
How can user report something on Django site
How can I create a way so that a user can report something on website, as we see on our social networks? How can I get the url in Admin panel pointing me to the webpage that user have reported? Please help me with this concern. Thanks in advance! -
django-autocomplete-light and django-filter Forward Filter Selection
I've implemented django-autocomplete-light and django-filter together for two fields (foreign keys referencing related fields in two other models: field__field = ModelChoiceFilter(queryset=Model.objects.all(), widget=autocomplete.ModelSelect2(url='url')) field2__field2 = ModelChoiceFilter(queryset=SecondModel.objects.all(), widget=autocomplete.ModelSelect2(url='url2')) When I try to use DAL's forward ability... field__field = ModelChoiceFilter(queryset=Model.objects.all(), widget=autocomplete.ModelSelect2(url='url')) field2__field2 = ModelChoiceFilter(queryset=SecondModel.objects.all(), widget=autocomplete.ModelSelect2(url='url2', forward=['field__field'])) ...nothing happens. The autocomplete boxes do not cascade. I think it might have to do with the fact that django-filter requires the queryset to be called explicitly. How do I implement forward effectively? -
Can't access multiple files submitted from a form
In a model here is the filefield that will host multiple files: screenshot_thumb = models.FileField( null = True, blank = True ) In forms.py here is where I define the field to accept multiple files: class VideoForm( forms.ModelForm ): screenshot_thumb = forms.FileField( widget = forms.FileInput( attrs = { 'multiple': True } ), required = False ) class Meta: model = Video fields = [ 'status', 'file_name', 'file_name_with_path', 'file_bucket', 'screenshot_thumb' ] In the view, I try to grab the files with this: files = request.FILES.getlist( 'screenshot_thumb' ) which is apparently what should be used: https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#uploading-multiple-files full view: def video_edit( request ): """ User clicks to edit his advanced profile""" user = request.user or None video_id = request.GET.get( "id" ) instance = get_object_or_404( Video, id = video_id ) # Instantiate form with existing instance form = VideoForm( request.POST or None, instance = instance ) context = { 'form' : form, 'video_id': video_id } # Save form if form.is_valid(): form_instance = form.save( commit = False ) ############ HERE ############################# files = request.FILES.getlist( 'screenshot_thumb' ) form_instance.save() # Flash info messages.info( request, 'Your video has been updated' ) my_print( "Video form updated" ) return redirect( f'/videos/edit?id={video_id}' ) else: # Initial form display, and redisplay of … -
Django empty args in get_queryset for ListView
I want to get a Project name for Sample. It should be in self.args because my urls.py looks like that (there is a lot of urls so I will post only important ones): projects/urls.py app_name = 'projects' urlpatterns = [ url(r"^$", ProjectListView.as_view(), name="projects_list"), url(r"^(\w+)/robjects/", include("robjects.urls")), url(r"^(\w+)/tags/$", TagsListView.as_view(), name="tag_list"), ... ] robjects/urls.py app_name="robjects" urlpatterns = [ ... url(r'^(?P<pk>[0-9]+)/samples/', include("samples.urls")), ] samples/urls.py app_name="samples" urlpatterns = [ url(r'^list/$', SampleListView.as_view(), name='sample_list_view'), url(r'^create/$', SampleCreateView.as_view(), name='sample_create_view'), url(r'^(?P<sample_id>[0-9]+)/update/$', SampleUpdateView.as_view(), name='sample_update'), url(r'^(?P<sample_id>[0-9]+)/delete/$', SampleDeleteView.as_view(), name='sample_delete'), ] I want to get project_name, that is the '(\w+)' part of projects/urls.py. To do that I wrote that code in samples/views.py. I tried to do project_name = self.args[0] but my args are empty. class SampleListView(ListView): model = Sample template_name = "samples/samples_list.html" def get(self, request, *args, **kwargs): """A base view for displaying a list of objects.""" # check if project exists try: pk = kwargs['pk'] robject = Robject.objects.get(id=pk) # add project to view attributes self.robject = robject except Robject.DoesNotExist: raise Http404 print(self.args) return super(SampleListView, self).get(request, *args, **kwargs) def get_queryset(self, *args, **kwargs): """ Overwrite orginal qs and add filtering by robject """ # original queryset qs = super().get_queryset(*args, **kwargs) print('args, ',self.args) print('kwargs', self.kwargs) pk = self.kwargs['pk'] robject = Robject.objects.get(id=pk) return qs.filter(robject=self.robject) This is the output … -
TypeError: string indices must be integers ,I used items() for iteration
I got an error TypeError: string indices must be integers.Traceback says Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/XXX/testapp/app/views.py", line 164, in <module> user1 = User.objects.filter(user_id=row_data['user_id']).exists() TypeError: string indices must be integers I wrote #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() files = glob.glob('./user/*.xlsx') for x in files: if "$" not in x: book3 = xlrd.open_workbook(x) sheet3 = book3.sheet_by_index(0) cells = [ ] data_dict = OrderedDict() for key, rowy, colx in cells: try: data_dict[key] = sheet3.cell_value(rowy, colx) except IndexError: data_dict[key] = None for row_number, row_data in data_dict.items(): user1 = User.objects.filter(user_id=row_data['user_id']).exists() if user1: user1.__dict__.update(**data_dict) user1.save() I really cannot understand why this error happens, because I know data_dict is dictionary type, so I used items() for iteration.Also I cannot understand which indices must be integers.How can I fix this?What should I write it? -
Django, showing more than one model in view
So I'd like to show two models from two different app in one of the apps views. Specifically, I am trying to show the user's posts feed on their profile page. However I haven't been able to figure it out and nothing I've found works. Here is my code, please take a look. Feed app models: from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class UserPost(models.Model): author = models.ForeignKey(User,related_name='userpost',null=True) post_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=150,blank=False) post_body = models.TextField(max_length=1000,blank=False) def publish(self): self.save() def get_absolute_url(self): return reverse('index') def __str__(self): return self.title Not sure if you'd need to see this but here is the users app models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from users.choices import * # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) join_date = models.DateTimeField(default=timezone.now) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) location = models.CharField(max_length=150) title = models.CharField(max_length=250) user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1) website = models.URLField(max_length=100,blank=True) about = models.TextField(max_length=500,default='about') twitter = models.CharField(max_length=50,blank=True) dribbble = models.CharField(max_length=50,blank=True) github = models.CharField(max_length=50,blank=True) def __str__(self): return self.user.username Users app View where I want the two models to display: from django.shortcuts import render,get_object_or_404 from users.forms import UserForm,UserProfileForm from … -
Where to override post method on function based views
Here: https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/#uploading-multiple-files it explains that to process multiple uploaded files you can override the post method as such: from django.views.generic.edit import FormView from .forms import FileFieldForm class FileFieldView(FormView): form_class = FileFieldForm template_name = 'upload.html' # Replace with your template. success_url = '...' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: ... # Do something with each file. return self.form_valid(form) else: return self.form_invalid(form) On a function based view, is there a way to override the post method such as in this example? Or how could I access multiple files from a form screenshot_thumb field defined as class VideoForm( forms.ModelForm ): screenshot_thumb = forms.FileField( widget = forms.FileInput( attrs = { 'multiple': True } ), required = False ) -
Jinja2 macro import "with context" and global variables: {% from file.html import macro_name with context %}
In Jinja2 template engine for python, my macro "with context" could not access the global variables from the context. Import statements: {% import 'en-US/my_macro.html' as all_macros %} {% from 'en-US/my_macro.html' import the_macro with context %} Macro usage: {{ all_macros.the_macro() }} The macro is being called, but the globals have no value. Here's the relevant docs for "with context" -
Django forms. Save data but do not validate until submission
I am new to Django and have been doing lots of reading so perhaps this is a noob question. We have applications that involve many forms that users fill out along the way. One user might fill out the budget page and another user might fill out the project description page. Along the way any data they input will be SAVED but NOT validated. On the review page only data is shown and no input boxes / forms. At the bottom is a submit button. When the user submits the application I then want validation to be performed on all the parts / pages / forms of the application. If there are validation errors then the application can not be submitted. My model fields are mostly marked as blank=True or null=True depending on the field type. Some fields are required but most I leave blank or null to allow the users to input data along the way. Any advice on best practices or do not repeat yourself is greatly appreciated.