Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Three related models in inlineformset_factory django
help please. I have three models: class FirstModel(models.Model): title = models.CharField(max_length=200, verbose_name=_('Title')) slug = models.SlugField(max_length=100, verbose_name=_('Slug')) summary = models.TextField(verbose_name=_('Summary')) class SecondModel(models.Model): listing = models.ForeignKey(FirstModel) attribute = models.ForeignKey(ThirdModel) value = models.CharField(_('Value'), max_length=255) class ThirdModel(models.Model): name = models.CharField(_('ThirdModel'), max_length=100) validation = models.CharField(_('Value type'), choices=CHOICESTUPLE) And i want render two forms with FirstModel and ThirdModel in one template using inlineformset_factory() with UpdateView. How to correctly create two formsets with this relationship between models. Is it possible? -
my django server running at 127.0.0.1:8000/blog how to change become 127.0.0.1:8000
url.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] -
Django queryset filter behaves differently in a shell vs runserver
Running the script below using python manage.py runserver 0:8000: exclude_category_id = 6 to_exclude = Post.objects.filter(categories=exclude_category_id).order_by('-published_at')[:4] print to_exclude results in [<Post: 100>, <Post: 98>, <Post: 97>, <Post: 86>] but if I run the same script using python manage.py shell: exclude_category_id = 6 to_exclude = Post.objects.filter(categories=exclude_category_id).order_by('-published_at')[:4] it returns [<Post: 122>, <Post: 121>, <Post: 120>, <Post: 119>] which is the expected behavior. This happens across different servers that I've tested it in. -
trouble using distinct() and filter() in django with an Oracle backend
I'm trying to get a list of all the distinct values field B can take given a value for field A. I'm using django 1.10 and Oracle 12g. I tried MyModel.objects.filter(fieldA='foo').values_list('fieldB').distinct() but this gives me a list with many duplicates, as if distinct() simply isn't working. I can get rid of the duplicates by converting the list to a set in python, but I'd like to rely on the database. thanks for any help you can give -
django build_absolute_uri IP instead of domain name (and not HTTPS)
On my Django application, everywhere the build_absolute_uri method is called, the returned url is the server IP instead of the domain name. Another thing is that the uri is not secured. It returns HTTP instead of HTTPS. What are the parameters to enable the HTTPS protocol and to tell django to replace the IP by the domain name? -
How to make correct revert to specific version in django-reversion?
I have 2 question cause little bit comfused with django-reversion app. I have page where users can see list all of reversions. Every version has button to revert. 1 Question: How to show only some fields of changes. Right now it shows me all fields. I use version.field_dict.items. 2 Question: How to make correct revert to specific version? Here below you can see code but it raise Error in views.py when I try to click to revert link. What I did wrong? template.html {% for version in versions %} {% for field_name, field_value in version.field_dict.items %} {{ field_name }} {{ field_value }} {% endfor %} <a href="{% url 'project:group_task_revert' project_code=project.code group_task_code=group_task.code group_task_reversion_id=version.revision.id%}">REVERT</a> {% endfor %} urls.py: url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_code>[0-9a-f-]+)/(?P<group_reversion_id>\d+)/$', group_revert, name='group_revert'), views.py: def group_revert(request, project_code, group_code, group_reversion_id): project = get_object_or_404(Project, pk=project_code, status='open') group = get_object_or_404(Group, pk=group_code) versions = Version.objects.get_for_object(group) versions[group_reversion_id].revision.revert() return redirect('project:project_detail', project_code=project.code) ERROR: Internal Server Error: /ru/account/dashboard/projects/42442299-97dd-4d92-9ef1-880f9cdd1612/4d3d3422-2618-4d66-96f5-8f0a0b5d9bf3/21/ Traceback (most recent call last): File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 198, in group_revert versions[group_reversion_id].revision.revert() File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py", line 271, in __getitem__ raise TypeError TypeError -
Add description to each dropdown options dynamically in Django-widget-tweaks form
I have this form select dropdown, rendered using Django-tweak's render_field. In my template, I have this form like so: <form method="POST" action="" class="org-member-edit" id='organization_permissions' data-parsley-validate> {% csrf_token %} <div class="form-group member-role{% if org_role_form.org_role.errors %} has-error{% endif %}"> <label class="control-label" for="{{ org_role_form.org_role.id_for_label }}">{% trans "Role" %}</label> {% render_field org_role_form.org_role class+="form-control" data-parsley-required="true" %} <div class="error-block">{{ org_role_form.org_role.errors }}</div> </div> </form> in the 5th line above, i.e the render_field org_role_form.org_role in the template tag, the org_role takes up values from the following form: class EditOrganizationMemberForm(SuperUserCheck, forms.Form): org_role = forms.ChoiceField(choices=ADMIN_CHOICES) which takes choice fields from another file choices.py like so: ADMIN_CHOICES = ( ('A', _('Administrator')), ('M', _('Member')) ) and so the dropdown looks like: I want it to look something like this: When I inspect the element (dev tools in browser), I can see that this select option gets rendered up like this: so, I tried attempting for the solution using jQuery like so: $('#id_org_role option').each( function(){ if ($(this).val() == 'M') { $(this).text().append("<br/> description here"); } else if ($(this).val() == 'A'){ $(this).text().append("<br/> description here"); } }); But it didnt help. however, If I do: $('#id_org_role option').each( function(){ if ($(this).val() == 'M') { alert($(this).val()); } }); it works,and generates an alert with value 'M' which means … -
USB device in the browser
I have a django application and I would like my user to connect and access a USB device. Are there any javascript or jquery plugins that I can leverage to accomplish this requirement? -
Get date from self object
I am attempting to pull the date field from the current item. I can't seem to get the syntax right. How would I go about getting the date data from the form I just submitted? Whenever I try the code below I get the following error: 'NoneType' object has no attribute 'get' views.py class EntryCreate(CreateView): form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): e_item = self.object.get() e_date = e_item.get('date') e_month = e_date.strftime('%B') e_year = e_date.year qs = MonthYear.objects.filter(month=e_month, year=e_year) models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) Thanks in advance for your help. -
How to show datetime in Django in specific timezone?
I have a Django (v1.10.6) project that has some models with datetime fields, for example: created_at = models.DateTimeField(auto_now_add=True) that are stored in PostgreSQL database without timezone information: created_at timestamp without time zone NOT NULL postgresql.conf: timezone = 'UTC' I want all the dates of my application to be shown in America/Bogota time zone (it shouldn't depend on user's actual time zone), so my settings.py file has the following configuration: TIME_ZONE = 'America/Bogota' USE_I18N = False USE_L10N = True USE_TZ = True SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s' SHORT_DATE_FORMAT = 'd-m-Y' TIME_FORMAT = 'H:i:s' but when I write {{ object.created_at|date:'SHORT_DATETIME_FORMAT' }} in templates, it still shows the date in UTC format. -
Django app: best place for a routine on enable app
I have a project in django 1.10 that has some apps. This project will be used by several organizations, and depends on each of them which apps will be enabled. Where is the best place in an app to include a function that has to be run only when the app is enabled? It needs to create some (main app) objects in the db, as a proper configuration for the app. Reading the docs seems that AppConfig.ready() is the best place. Is it? -
Can't find js file in Django
I'm having trouble linking a js file in my Django project. I have the following in my html: <script type="text/javascript" src="{% static 'tande/sketch.js' %}"></script> And I have {% load staticfiles %} in my header. But when I load the page this raises a 404 GET error at this line ^^ I have put the sktech.js file into myapp>static>myapp>sketch.js And ran python manage.py collectstatic Which has placed the file into my staticroot directory.. so surely this should work fine? The only things I can see in my settings.py related to this are: INSTALLED_APPS = ( .... 'django.contrib.staticfiles', ... ) STATIC_URL = '/static/' STATIC_ROOT = './staticroot' Am I missing something in my settings? I am a bit clueless about the settings stuff... -
how to get content in same div without getting in many boxes?
I have following code <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"> var product = "{{ obj.type_product }}"; var product1 = "{{ name }}"; var vastu = "{{ obj1.vastu_key.id }}"; var type_id = "{{ obj.id }}"; if (vastu == type_id) { var title = "{{ obj1.title }}"; var brand = "{{ obj1.brand }}"; var img = "{{ obj1.image }}"; var price = "{{ obj1.price }}"; $("#statbox").prepend("<div id='box2'>" + title + brand + price +"</div>"); } </script> {% endfor %} {% endfor %} </div> I am using two for loops here and the box2 which is styled in css, by running this code i got box2 multiple times as content contains in child for loop and that title,brand,img,price is displyed in each new box2. But i want new box2 should be generate only according to content contains in parent for loop not according to content contains in child for loop and the all contents i.e. title,brand,img,price which are associated with each content of parent for loop should disply in same box2. Multiple box2 only create according to parent for loop and contents of child for loop in the same box2 created … -
Unable to save django edit profile
I'm trying to make an edit profile page with function based view which updates the profile model. I managed to get this code running a while ago but now the save button wont work. I know this might only be a minor error, so please spare me models.py from django.db import models from accounts.models import User from django.contrib.auth.decorators import login_required from django.db.models.signals import post_save class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(default="default_avatar.png") bio = models.CharField(max_length=200, default="", blank=True) skills = models.ManyToManyField("Skill") #kelas = models.ManyToManyField("kelas.Kelas", blank=True) def __str__(self): return self.user.username def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_profile, sender=User) # automatically run create_profile if save() method is called by user class Skill(models.Model): name = models.CharField(max_length=50, primary_key=True) def skillOwner(self): return list(self.usernames.all()) def __str__(self): return self.name views.py from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required class DetailView(generic.DetailView): model = Profile template_name = "profiles/user_profile.html" def EditProfileView(request, pk): args = {'profile':Profile.objects.get(pk=pk), 'skill' : Skill.objects.all()} if request.method == 'POST': form = EditProfileForm(request.POST, instance=Profile.objects.get(pk=request.user)) if form.is_valid(): profile = form.save(commit=False) profile.skills.add(Skill.objects.get(name = form.data['skill'])) profile.save() form.save() return HttpResponseRedirect(reverse('profiles:profiles', kwargs={'pk' : request.user.pk})) else: form = EditProfileForm() args['form'] = form return render(request, 'profiles/edit_profile.html', args) class DeleteProfileSkill(generic.DeleteView): def delete(self, request, *args, **kwargs): username = self.kwargs['pk'] … -
Remove date of publication in Zinnia
How do you remove the publication date that is besides the author's name in Zinnia Django app? Do you edit that on the admin site or hard code it in template? -
Django - avoid current users from deleting themselfs
Admin (current user) who are logged in can delete himself and I want to avoid that, since it throws the error AnonymousUser. There are no issues related to this that I can see since most of them are asking for is in Django Admin Site which is not what I want. Still a newbie so appreciate all the help, folks! models.py class Administrator(AbstractUser): union_position = models.CharField(max_length=100) association = models.ForeignKey(Association) class Meta: db_table = 'Administrator' views.py class admin_delete(DeleteView): model = Administrator success_url = reverse_lazy('admin_overview') template_name = 'admin/admin_delete.html' admin_overview.html <div class="admin-overview"> <ul class="list-group"> {% for administrator in object_list %} <table class="table table-bordered"> <thead> <tr> <th>first_name</th> <th>last_name</th> <th>email</th> <th>association</th> <th>union_position</th> <th>username</th> </tr> </thead> <tbody> <tr> <td>{{ administrator.first_name }}</td> <td>{{ administrator.last_name }}</td> <td>{{ administrator.email }}</td> <td>{{ administrator.association }}</td> <td>{{ administrator.union_position }}</td> <td>{{ administrator.username }}</td> <td> <a class="btn btn-primary btn-m" href="{% url "admin_edit" pk=administrator.id %}"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> {% trans 'Update' %} </a> </td> <td> <a class="btn btn-danger btn-m" href="{% url "admin_delete" pk=administrator.id %}"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> {% trans 'Delete' %} </a> </td> </tr> </tbody> </table> {% empty %} <center><p>{% trans 'Nothing to display.' %}</p></center> {% endfor %} </ul> </div> admin_delete.html <div class="admin-delete"> <form action="" method="POST"> {% csrf_token %} <center><p>Are you sure you … -
Django dynamic table in templates
I'm building an app to manage rooms. These are my models: class Room(models.Model): name = models.CharField(max_length=64) desc = models.CharField(max_length=512) seats = models.IntegerField() def __str__(self): return str(self.id) class Reservation(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) time = models.IntegerField() hours = models.IntegerField() user = models.ForeignKey(User) room = models.ForeignKey(Room) reason = models.CharField(max_length=64) def __str__(self): return self.reason My form: class LoginForm(forms.Form): username = forms.CharField(label='User Name', max_length=16) password = forms.CharField(widget=forms.PasswordInput()) class AddReservation(forms.Form): date = forms.DateField(label='date', widget=forms.SelectDateWidget, initial=datetime.date.today()) time = forms.IntegerField(label='time', min_value=8, max_value=20) hours = forms.IntegerField(label='hours', min_value=1, max_value=12) room = forms.ModelChoiceField(queryset = Room.objects.all().order_by('name'), label='room' ) reason = forms.CharField(label='reason', max_length=64) class RegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=30) email = forms.EmailField(label='Email') password1 = forms.CharField(label='Password', widget=forms.PasswordInput()) password2 = forms.CharField(label='Password (Again)', widget=forms.PasswordInput()) first_name = forms.CharField(label='First Name', max_length=20) last_name = forms.CharField(label='Last Name', max_length=20) class DatePicker(forms.Form): date = forms.DateField(label='date', widget=forms.SelectDateWidget, initial=datetime.date.today()) My messed up view: def index(request): rooms = Room.objects.all().order_by('name') resv = Reservation.objects.filter(date=datetime.date.today()) a = [0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] count = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] print("a", resv) print(rooms) if request.method == 'GET': form = DatePicker(request.GET) if form.is_valid(): dt = form.cleaned_data['date'] resv = Reservation.objects.filter(date=dt) print(dt) print("b", resv) form = DatePicker() return render(request, 'index.html', {'form': form, 'rooms': … -
Django or Ruby-On-Rails max users on one server deployment and implcations of GIL
I'm aware of the hugely trafficked sites built in Django or Ruby On Rails. I'm considering one of these frameworks for an application that will be deployed on ONE box and used internally by a company. I'm a noob and I'm wondering how may concurrent users I can support with a response time of under 2 seconds. Example box spec: Core i5, 8Gb Ram 2.3Ghz. Apache webserver. Postgres DB. App overview: Simple CRUD operations. Small models of 10-20 fields probably <1K data per record. Relational database schema, around 20 tables. Example usage scenario: 100 users making a CRUD request every 5 seconds (=20 requests per second). At the same time 2 users uploading a video and one background search process running to identify potentially related data entries. 1) Would a video upload process run outside the GIL once an initial request set it off uploading? 2) For the above system built in Django with the full stack deployed on the box described above, with the usage figures above, should I expect response times <2s? If so what would you estimate my maximum hits per second could be for response time <2s? 3) For the the same scenario with Ruby On … -
HyperlinkedIdentityField error when using a different identifier in URLs in Django Rest Framework
I have a model: class Project(models.Model): pass A serializer: class ProjectSerializer(serializers.ModelSerializer): selfLink = serializers.HyperlinkedIdentityField(view_name='project-details') class Meta: model = Project fields = '__all__' Two views: class ProjectList(ListAPIView): model = Project queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectDetails(RetrieveAPIView): queryset = Project.objects.all() model = Project serializer_class = ProjectSerializer def get(self, request, project_id): # I used here 'project_id' insead of 'pk', because I need to build some long API URLs with different pk's # E.g. http://example.com/api/project/<project_id>/tasks/<task_id>/subtasks/<subtask_id> # Instead of: # E.g. http://example.com/api/project/<pk>/tasks/<pk>/subtasks/<pk> queryset = Project.objects.get(id=project_id) return Response(ProjectSerializer(queryset, context={'request': request}).data) And URLs: urlpatterns = [ url(r'^projects/', include([ url(r'^$', api.projects.ProjectList.as_view()), url(r'^(?P<project_id>[-\w]+)/', include([ url(r'^$', api.projects.ProjectDetails.as_view(), name='project-details'), url(r'^tasks/', include(project_investigations_patterns)), ])), ])), ] However, visiting: http://example.com/api/projects/ output the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'project-details' with arguments '()' and keyword arguments '{'pk': UUID('a6fe49c2-7b0a-4012-8066-6ec1d0cfdfc1')}' not found. 1 pattern(s) tried: ['api/projects/(?P[-\w]+)/$'] Could not resolve URL for hyperlinked relationship using view name "project-details". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. So the problem is really in the HyperlinkedIdentityField. If I comment out the following line: selfLink = serializers.HyperlinkedIdentityField(view_name='project-details') then the API respond well (but I dont have the link I need). If I use instead of in the … -
Use of foreignKey between app models in Django 1.10
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news. The first the app called teams has one model called Team, and has 2 fields: "name" and "creation_date". The second app called members has one model called Member, and I want to put one field called "team_in" that would be one of the teams that are in registered in the other app with the field "name". I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand? -
invalid literal for int() with base 10: 'list'
I'm filtering models and trying to return user_id, like this Project.objects.filter(client_sub_org__lead_contact__account_handler=user_id), when I debug this I've got that my user_id is returning list as a result and for that matter I'm getting invalid literal for int() with base 10: list, so I'm I filtering this properly, how to return user_id in this case? class Project(models.Model): client_sub_org = models.ForeignKey(ClientSubOrganization) class ClientSubOrganization(models.Model): lead_contact = models.OneToOneField(LeadContact, blank=True, null=True) class LeadContact(models.Model): account_handler = models.ForeignKey(User) -
How do I change a list within a list back to one list [duplicate]
This question already has an answer here: Flatten (an irregular) list of lists in Python 31 answers I have a list that contains another two lists inside it. how do I change it back to one list? I am using django. current output: [1L, 1L, [3L, 11L], [11L]] expected output: [1L, 1L, 3L, 11L, 11L] -
Django : Extract data from table to initially populate a form
I'm looking to initially populate my Django form with data based from another app. I followed this SO example in order to write my function : Initial populating on Django Forms However, I don't overcome to get what I want. This is what my function is supposed to do : I have a model which is named : Person with lots of informations (firstname, ...) and a very useful unique number in order to distinguished each person. Then, I have another model which is named BirthCertificate with a form in order to create a Birth Act. In my form view, user gives this unique number and Django is able to search the good person (not hard) et initially populate my form (which have some common fields between Person.model and BirthCertificate.model). I have 2 steps : First : User writes person's unique number Second : User writes parents' unique number I submit this informations and the first step should initially populate common fields. Second step works pretty well. This is my function, but somethings still isn't working : def BirthCertificate_Form_unique_number(request) : #User fill some fields query_social_number = request.GET.get('social_number') query_social_number_father = request.GET.get('social_number_father') query_social_number_mother = request.GET.get('social_number_mother') if query_social_number : query_social_number_list = Person.objects.filter(social_number=query_social_number) if … -
How does django detect file changes
I'm trying to watch for changes in .py files, in a directory. I went through existing solution. I'm curious on how django library solves this problem. The development server is restarted on file changes. -
creating multiple Django model fields
I need to create 100 same fields in Django model. Maybe there is the simple way of doing this or I need to add it like this: Field1 = models.CharField(max_length=40) Field2 = models.CharField(max_length=40) Field3 = models.CharField(max_length=40) ... ?