Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sort by label_from_instance with ModelMultipleChoiceField in Django 1.8
I have a form with a ModelMultipleChoiceField that has been overridden to specify a label_from_instance. What's the best way to sort the choices by the label? class MultipleAuthorChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): label = author_display(obj) return super(MultipleAuthorChoiceField, self).label_from_instance(label) I understand that I can order_by the queryset that I pass in. While that works to sort the queryset, it's not going to be sorted by the label_from_instance. -
Django extending model.User
I am trying to extend model.User in Django (using SQLite3). Here's my Model for UserProfiles: class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') bio = models.TextField(blank = True, null = True) birth_date = models.DateField(blank = True, null = True) followers = models.ManyToManyField('self', symmetrical=False, null = True, blank = True) But when I run the server, I don't see UserProfiles as a separate tab. There exists a User tab but I don't see any of my custom fields in there. Am I doing something wrong or is this the expected behavior of Django? And how can I test this much code (manually is fine but how?) just to see if the behaviour is as expected. Thank you very much! -
Can't create django app in Conda environment.
I have created a conda environment by typing the following conda create --name testenv python command from here. Now one of my tutorials tells me to install Django which I happily did in the environment(That is the point of using environments right?, keeping dependencies straight) using pip3 install django.Post which I was told to do this django-admin startproject mysite Which didn't work. I am thinking because he was doing it in venv and I am in conda probably that's why(There is no venv folder in my test-app folder as well. Also I have already activated the environment). Every time I type the command django-admin startapp mysite I get this error. Traceback (most recent call last): File "/usr/bin/django-admin", line 18, in <module> from django.core import management ImportError: No module named 'django' How do I fix this? I have already installed Django. What more am I supposed to do? -
Reverse for 'course_detail' with arguments '()' and keyword arguments '{u'cd': ''}' not found. 1 pattern(s) tried: ['courses/(?P<cd>\\d+)/$']
I am fairly new to Django and I followed a tutorial which helped create a blog using Django. That project went fine. But when I wanted to use what I learnt form that tutorial and make my own simple website that's when things went pear shaped. I have been at this problem for a long time now and it is really bugging me, so I hoped a fresh pair of eyes could help me decode the issue. The error I am getting is this: Reverse for 'course_detail' with arguments '()' and keyword arguments '{u'cd': ''}' not found. 1 pattern(s) tried: ['course/(?P<cd>\\d+)/$'] Now I know that in my original project I never had a "u'" before the 'cd' in my arguments and I have no idea where this is coming from, I have looked tirelessly for what is causing this and I can't find it. Here is the rest of the code regarding this issue: course_list.html {% load staticfiles %} <html> <head> <title>Courses</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/website.css' %}"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css"> </head> <body> <div class="links"> <h1><a href="">Home</a> | <a href="">Courses</a> | <a href="">Venues</a> | <a href="">About Us</a> | <a … -
Django: Handling form data after a redirect
I have a Django app with two views (actually more but I'm simplifying). The first view shows a page with details regarding an object and has a form which can be submitted. The second view is called buy the POST request on submitting the form and then redirects back to the first view: views.py: def main_view(request): context = {} # other view code here context['form'] = Form() return render(request, 'mypage.html', context) def form_view(request): form_data = Form(request.POST) if form_data.is_valid(): # process form here else: # add an informative message messages.add_message(request, messages.INFO, "Error message here") return redirect('url_of_main_view') The issue I have here is that I want to pass the form data back to the main view, both to prevent the need to fill in the whole form again, and to allow the validation errors to be displayed. I would normally do this by simply processing the form within one single view, such as: def view(request): context = {} # other view code here context['form'] = Form() if request.method == 'POST': form_data = Form(request.POST) if form_data.is_valid(): # process form data else: # handle messages context['form'] = form_data return render(request, 'mypage.html', context) However, this (in my case at least) would result in a large … -
Django Cities import error
I can't get to import data with manage.py cities --import=all, I don't have idea of why this is happening. Here is the log: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/django/utils/decorators.py", line 184, in inner return func(*args, **kwargs) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/cities/management/commands/cities.py", line 86, in handle func() File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/cities/management/commands/cities.py", line 312, in import_city uptodate = self.download_once('city') File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/cities/management/commands/cities.py", line 159, in download_once self.download_cache[filekey] = self.download(filekey, i) File "/home/julian/.virtualenvs/duenio/local/lib/python2.7/site-packages/cities/management/commands/cities.py", line 119, in download filepath = os.path.join(self.data_dir, filename) File "/home/julian/.virtualenvs/duenio/lib/python2.7/posixpath.py", line 75, in join if b.startswith('/'): AttributeError: 'list' object has no attribute 'startswith' These are the cities settings (I have Postgis installed): DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' ... CITIES_FILES = { 'city': { 'filename': ['CO.zip',], 'urls': ['http://download.geonames.org/export/dump/'+'{filename}'] }, } The weird part is, I installed django-cities in a new fresh project, and it did work. Do you know how to fix this? -
Django manage.py error "bad interpreter: Permission denied" on ubuntu 14.04
I have installed Django on Ubuntu 14.04 then I have activate the virtual environment and create an empty project and when I start the server everything is fine: ./manage.py runserver 0.0.0.0:8000 I have then uploaded my "hello world" project with WinSCP (the project was developed with Visual Studio on Windows client), then I run the same command to start the server: chmod +x manage.py ./manage.py runserver 0.0.0.0:8000 Result: : No such file or directory The first line of manage.py is the same of the empty project, which run without any problem and is: #!/usr/bin/env python I modified the first line of the manage.py to: #!/django/projects/prj01/prj01env/bin python At that point I run again manage.py and the error message is this: bash: ./manage.py: /django/projects/prj01/prj01env/bin: bad interpreter: Permission denied I run every command as root. Do you know how I can make my "hello world" project run properly? Thank you. -
django REST API json encoding
I am working on a django application and i made a rest api (webservice) with djangorestframework. Suppose i have a single table (model). I wrote a serializer for this model and i put a ViewSet class on view.py. Everything works great: If i browse the API URL with my favorite browser, djangorestframework shows me an human readable page where i can see the content of the table, i can also post a new record. That is great. When i see the content of the table, i see json encoded data. But when i put a new record, i see this is just a simple HTML post with no json encoding. I am wondering what is the state of the art in this case: Working with json encoding or not ? What is restfull compliant ? Next step for me to save data from ajax/javascript client Should i do something like that: $.ajax({ url : "/myapi/", type : "POST", contentType: "application/json", data: {field1:'value for field1',field2:'....',...} success : function(data) { ... } }); Or should i do something like that: var formData = new FormData(); formData.append('field1', 'value for field1'); formData.append('field2', '...'); formData.append('userpic', myFileInput.files[0], 'test.jpg'); $.ajax({ url : "/myapi/", type : "POST", data: … -
Django dynamically filled dropdown in form
I'm trying to get a form to have a dropdown whose contents change dynamically according to user. I can get the dropdown to change for all users, but not for individuals. I've got this form: forms.py: class FooForm(ModelForm): class Meta: model = Candidate fields = ( 'name', 'foos', ) labels = { 'name' :_('Name'), 'foos' :_('Chosen Foos'), } widgets = { 'name' : TextInput(attrs={'readonly': 'readonly'}), 'foos' : SelectMultiple(), } models.py: class UserInfo (models.Model): name = models.CharField(max_length = 256, blank = True, default = None) foos = models.ManyToManyField(Foogroup, blank = True) If I use this as is, I get a dropdown filled with all the possible values of Foogroup. If I give FooForm an init(), I can set the dropdown to have a set of values, but that's setting the values for everyone. How can I dynamically set the contents of the dropdown to just what has been set for User Bob, while User Mary gets just those contents that have been set for her? I'm thinking something like this may work: ajax.py: def chooseFoos(request): if request.method != POST: ### 1. do magic to get handle to form's dropdown ### ### 2. fill form's dropdown for request.POST['name'] ### ### 3. highlight … -
Hidden Field value not being saved in Django
I have a hidden field. I'm using a jquery function to fill in the field dynamically. When the form is submitted, the value for that field is not being saved. However it is in the POST data and also is in the cleaned data. I thought it was because of the jquery function, so I put an initial value in the field and removed the function. That value is also not being saved. models.py class Dogs(models.Model): name = models.CharField(max_length=64) class WalkSchedule(models.Model): schedule = models.ForeignKey("test_app.Dogs", related_name="walk_schedule") day = models.CharField(max_length=8) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) forms.py class DogsForm(forms.ModelForm) name = forms.CharField(widget=forms.HiddenInput(), initial='testing') class Meta: model = Dogs fields = "__all__" class WalkScheduleForm(forms.ModelForm): class Meta: model = WalkSchedule exclude = ("schedule",) views.py class SchedCreate(View): def post(self, request, *args, **kwargs): dform = DayPartForm(request.POST, instance=Dogs()) WalkScheduleFormset = inlineformset_factory(Dogs, WalkSchedule, form=WalkScheduleForm, can_delete=False, extra=0, min_num=1) sforms = WalkScheduleFormset(data=request.POST) if sforms.is_valid() and sforms.is_valid(): dform_obj = dform.save() for sform in sforms.forms: sform_obj = sform.save(commit=False) sform_obj.schedule = dform_obj sform_obj.save() -
Save with update_fields did not affect any rows (while changing class)
Let's have a model with decorator: def upgradable(model): @classmethod def upgrade(cls, base, **kwargs): base.__class__ = cls for attr, value in kwargs.items(): setattr(base, attr, value) return base setattr(model, "upgrade", upgrade) return model class Person(models.Model): name = models.CharField(max_length=50) def save(self, *args, **kwargs): self.name = self.name.upper() super(Person, self).save(*args, **kwargs) and inherited model: @upgradable class User(Person): email = models.EmailField(); and I'm trying to upgrade person = Person.objects.get(...) user = User.upgrade(person, email="example@example.com") user.save() But the error appears: Save with update_fields did not affect any rows. in connection to super(Person, self).save(*args, **kwargs) (in method save of model person) It isn't total wrong, because indeed I don't want to change anything in table person, I just want to add something to table user (pointer to person and email). So how to skip this warning? -
How to load site-wide static files in Django only once?
I have multiple web pages which extend a base template, base.html. Within base.html I load multiple JavaScript files (some are retrieved from the static directory, some are retrieved from a CDN): <script src="/path/to/file.js"></script> <script src="cdn-website.com/path/to/file.js"></script> It appears that every time I click a link to a page that extends base.html the JavaScript files have to be requested again, which takes 1-2 seconds, so each page loads very slowly. Are there any workarounds for this? -
django shell and .pystartup compatibility
Recently, I wrote a .pystartup file in my home directory to fix an issue in osx with using readline in the python shell(using the arrow keys created escape characters instead of recalling previous lines). However, now I can no longer run python manage.py shell in Django. The other manage.py functions work fine, like check or runserver or inspectdb. My $PYTHONSTARTUP env variable points to my .pystartup file, which I've included below. I've also noticed that in Django's shell.py file, it attempts to import readline in the python function, which I believe may be the cause of the error, although I'm unsure about how to fix my .pystartup file to make it compatible with Django's shell. I'm also using virtualenv, if that makes any difference. .pystartup file in home directory: import atexit import os import gnureadline as readline import rlcompleter historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): import gnureadline as readline readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del os, atexit, readline, rlcompleter, save_history, historyPath (env) $ python manage.py shell stacktrace: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/ryanmoore/Programming/crib/fim_db/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/ryanmoore/Programming/crib/fim_db/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ryanmoore/Programming/crib/fim_db/env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) … -
Grant permissions to a group over another group and all of its users
I was wondering if there was a way to grant object/model level permissions to a group over a different group and all of its users without having to iterate over the users. example of long way: manager_group = Groups.objects.get(...) employee_group = Groups.objects.get(...) assign_perm('auth.view_group', manager_group, employee_group) for employee in employee_group.user_set.all(): assign_perm('users.view_user', manager_group, employee) also, let's say there are Lessons within the group as well linked by permissions. I would also need to loop over the lessons and grant object permissions for that. So I ask again hopefully with some context explained, is there a way to have the permissions over a group also grant permissions over that group's users and other objects? -
django - Get First element by the recent date of each group
I have following model in django Business ID Business Name Business Revenue Date Here is the sample data: Business ID | Business Name | Business Revenue | Date 1 B1 1000 2012-10-13 2 B2 20000 2013-10-16 1 B1 2000 2013-04-13 2 B2 24000 2014-09-02 I want to fetch all businesses having latest date. I have tried this: model.objects.filter(date__gte = date.today()).order_by('business_id', '-date') This is giving me group of businesses having latest business in each group at the top of it. How do I omit the rest of rows? Kindly assist me. -
Reactjs and data on server
I'm new to Javascript frameworks and looking for framework for my new projects. Until now i created simple apps using MVC framework Django with Bootstrap frontend. Thanks framework i got everything in one package with best-practice well know. For Javascript i used some jQuery libraries without understanding, just configured with doc help. When i tried to write some Javascript on my own and found there are big changes in JS world (like ES6, TypeScript) i found it very usefull. When i found JS frameworks, i felt in love. I have read about frameworks, watched some tutorials. As many other, i found React nice. But what i'm completely missing, is the server part. Especially React tutorials creates components or functions, nice UI, but don't cover what happens with data next. I know that React is ment as "V" in MVC. But what is the best-practice or wide-used extension for server part? Are there tutorials or book to take me further than just creating actions and UI? Thanks for any links, i just need to point best direction. Or is React ment for just specific project parts and better to look elsewhere? -
Create URL with a inherited block variable as argument in Django
I'm trying to create an URL in a Django (1.9) template which parses an inherited block variable as argument. So href="{% url 'overview:detail' '{% block test_id %}{% endblock %}' %}" With the test_id inherited from a child template like: {% extends 'overview/base.html' %} {% block _id %}{{test.id}}{% endblock %} When I try to execute this if gives me the following error: TemplateSyntaxError at /testviewer/ Could not parse the remainder: ''{%' from ''{%' How to prevent this? -
Django JSONField contains list of values
I have values in my JSONField structured like this: [{"id": "723"}, {"id": "614"}] How can I filter queryset if contains id = ['723', '614'] ? -
How can I compute Data from models then serialize it?
Say am serializing this from my model: class PurchaseReportPerClient(AbstractFieldsMixin, serializers.ModelSerializer): purchased_by = UserInlineSerializer(read_only=True) paid = serializers.ReadOnlyField(source='paid') class Meta: model = Purchase fields = ('purchased_by','paid',) In the above case what would I do to return a total_paid for each purchaser given that I have several purchasers and each has done several purchases. So I want to return something like this for each user: { "purchased_by": { "id": "1234", "name": "joe", "email": "abd@cz.com" }, "total_paid":123, } -
Django Template - Looping through Queryset without creating multipletimes Div's
I except this question to be relatively easy, but since I am new to Django I am struggling. I got a QuerySet which is given to a template. Basically I want to create a football (soccer) table. But also in general I want to understand the concept. So for every team in the teams Query set, the data should be filled in the 5 respective columns. At the moment I solved it by adding a for loop into every column. However, I think that it looks ugly and is unefficient. Moreover, I want to edit the id's for the first three loops. So what I am looking for: A possibility to set the for loop around the div's but without creating the div's in every loop. Something like: {%for team in teams %} <div id="position">team.position</div> <div id="name">team.name</div> ... {% endfor %} In addition to adding something like: {% if forloop.counter0 == 0|1|2 %} add id/class to div row {% endif %} Is the smartest way here, adding a variable to the class, meaning class={{xyz}} ? The template looks at the moment like this. <div class="row"> <div class="col-md-2" id="position">{% for tea in teams %}{{tea.league_position}}</br>{% endfor %}</div> <div class="col-md-4" id="name">{% for tea … -
Django App cannot connect to a Mysql container
So I am trying to connect the container of my django app with the container of Mysql by using docker-compose.yml .At first I used to get an error that Access is being denied(Error 1045 if I am not wrong), so I decided to delete the containers and rebuild. After doing this sadly everything stopped working... Now when I start the containers with docker-compose up I get: [Note] mysqld: ready for connections. |[0m Version: '5.7.15' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) I checked the logs of the mysql container and it says: Aborted connection 3 to db: 'XX' user: 'XX' host: 'XX' (Got an error reading communication packets). Any ideas what may be the cause of this? Should I even use docker-compose for this or should I somehow try to implement everything in 1 container? My docker-compose.yml looks like this: db: image: mysql:latest environment: MYSQL_DATABASE: XX MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' MYSQL_USER: XX MYSQL_PASSWORD: XX web: build: . command: python manage.py runserver 0.0.0.0:80 volumes: - .:/app ports: - "80:80" links: - db And of course under settings.py I have set the DATABASE as written in the docker-compose.yml under environment. -
Filter on many-to-one model
I want to be able assign users vehicle registrations, and when the user logs into the website their home page should have a list of vehicle regs they own. However I cannot get the model class to filter on the foreign key. views.py @login_required def home(request): # This is the basic user landing Page veh_list = Vehicle.objects.filter(UserProfile.user) return render(request, 'portal/home.html', {"veh_list": veh_list}) model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User) # The additional attributes we wish to include. compName = models.CharField(max_length = 20) milkco = models.IntegerField() # Override the __unicode__() method to return out something meaningful! def __unicode__(self): return self.user.username class Vehicle(models.Model): vehid = models.CharField(max_length = 10) company = models.ForeignKey(UserProfile, default = 1) class Meta: db_table = "vehicle" def __unicode__(self): return self.vehid home.html <!DOCTYPE html> {% extends 'portal/base.html' %} {% block title %}{{user.first_name }} {{ user.last_name }} Portal{% endblock %} {% block content %} <p>This is the home Page</p> {% if user.is_authenticated %} <h4>Optiload says... hello {{ user.first_name }} {{ user.last_name }}!</h4> {% endif %} {% for veh in veh_list %} {{ veh}} {% endfor %} {% … -
ReferenceRule object can't be deleted because its rule_ptr_id attribute is set to None
class CsvMixin(models.Model): csv_encoding = models.CharField(max_length=64, null=False, blank=False, default="UTF-8") csv_delimiter = models.CharField(max_length=64, null=False, blank=False, default=",") csv_header = models.IntegerField(null=False, blank=False, default=0) csv_skiprows = models.IntegerField(null=False, blank=False, default=0) csv_quotechar = models.CharField(max_length=64, null=False, blank=False, default="\"") csv_strip_whitespace = models.BooleanField(null=False, blank=False, default=True) def _has_header(self): if self.csv_header == -1: return False else: return True def _strip_space(self, df): if self._has_header(): df.rename(columns=lambda x: x.strip(), inplace=True) for c in df.columns: df[c] = pd.core.strings.str_strip(df[c]) def _get_df_from_raw(self, raw): try: if self._has_header(): header = self.csv_header else: header = None df= pd.read_csv(BytesIO(raw), dtype=pd.np.str, skipinitialspace=True, encoding=self.csv_encoding, delimiter=self.csv_delimiter, quotechar=self.csv_quotechar, header=header, skiprows=self.csv_skiprows) if self.csv_strip_whitespace: self._strip_space(df) return df except (UnicodeDecodeError, pd.parser.CParserError) as e: if self.csv_encoding == "UTF-8": self.csv_encoding = chardet.detect(raw)["encoding"] if self.csv_encoding != 'UTF-8': self.save() logger.debug("falling back to %s encoding" % self.csv_encoding) return self._get_df_from_raw(raw) raise CSVEncodingError(e) def get_dataframe(self, file): """opens a CSV file and raises an exception if the encoding is unparseable""" file.open(mode='rb') raw_data = file.read() file.close() df = self._get_df_from_raw(raw_data) df.fillna('', inplace=True) return df def write_dataframe(self, df): """returns a django CSV contentfile from a dataframe""" if self.csv_header == -1: header = False else: header = True file = df.to_csv(index=False, encoding=self.csv_encoding, delimiter=self.csv_delimiter, quotechar=self.csv_quotechar, header=header) return ContentFile(file) class Meta: abstract = True -
External authentication in a Dajngo app
As the title says, I'm developing a Django app which uses another API to authenticate the user. The external API is quite simple and returns a certificate if the user is properly authenticated. My app should not keep any user's information, except it's certificate and id (which I'm keeping as session variables). As a drawback of this implementation, I'm not using Django’s authentication system and all the practical methods it offers, like to check if the user is_authenticated, is_anonymous or to get user's permissions. As the user must be logged to access some pages of my app, I must aswell ask him/her to log in so that he/she could continue. Therefore, using @login_required would be handful. I must also create a Access Control module to check permissions and to allow access to some restricted areas of the app according to groups of users (common users, admins, etc.). Do you guys know how could I customize Django's authetication system to handle all theses issues? Thank you. -
return total based on custom filterset Django Rest API Framework
Is there a way to return only the total of records based on filterset? I need only a payload like below: {'total': 40} I have the following filterset: class BookingsTotalFilter(FilterSet): overdue = BooleanFilter(method='_by_overdue') class Meta: model = Booking fields = ('id', 'name', 'status', 'code') def _by_overdue(self, queryset, name, value): today = timezone.now() if value: return queryset.filter(limit_date__gte=today) return queryset.exclude(limit_date__gte=today) This is my viewset: class BookingViewSet(ListModelMixin): queryset = Booking.objects.annotate(total=Count('id')) lookup_field = 'id' serializer_class = BookingTotalSerializer filter_class = BookingTotalFilter My Serializer: class BookingTotalSerializer(serializers.Serializer): total = serializers.IntegerField() class Meta: model = Booking fields = ('total',)