Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
repo2 is a library for repo1
In the moment, I have two github repositories, i.e. repo1 and repo2. Both are two django projects created by our team. In requirements.pipin ~/work_projects/repo1, I have the line -e git+ssh://git@gitlab.com/repo2.git@de5622dcf0b9a084f9b0a34cdd1d932026904370#egg=repo2 Hence, repo2 becomes a library used by repo1 in ~/.virtualenvs/venv/src (repo1's virtual environment). In the moment, I need to modify both repositories at the same time. So my main focus in the moment is each time I modify repo2, I need to test out the results on repo1. I want to look at the impact of repo2 on repo1 once modified. I don't want to push my changes on github and reinstall repo2 on repo1 each time I want to see those changes. How could I make it works easily, workaround? -
django simple history - how to create history when the object is not created in admin
I'm using django-simple-history==1.9.0 package with django 1.8. When I create an object outside the admin and then look at the history of the object in the admin page, it shows a message This object doesn't have a change history. It probably wasn't added via this admin site. I tried setting the user for that object: user = User.objects.get(username='john') Poll.objects.get(id=536).history.update(history_user=user) but that did not solve the problem. Poll.objects.get(id=536).history.all().count() returns 1 so there is a history generated. Any ideas how to make it show the history or how to create an additional history? I also tried update_change_reason but that did not work at all. -
Django - Authenticate users from external source (IPB Forum)
I'm fairly new to Django - I've been building a small web app for our forum community, which is powered by IPB 4. Initially I didn't have any need for users on the Django site since it was just displaying data, but I've come up with some new ideas and I would love to be able to make it such that if a user has an account on the forums, they could sign into the Django site using the same credentials. I don't need any sign-up functionality on the Django site - if a user isn't registered I can simply redirect them to the forum signup. I've been doing plenty of research on this and there is a lot of information about authenticating users from an external source in Django but I'm having trouble understanding how to go about it with an IPB forum as all of IPB's documentation on SSO relies on PHP. Would Django's authentication back-ends be capable of something like this? Or would setting up an OAuth server on the forum work better? IPB does have a great built in REST API so perhaps that could be utilized as well. Thanks for any guidance you guys might … -
using self.request.user in model queryset in Django
I am using Django 2 I have a model within which I have written a queryset class to add the search function. I want to display only those results which are associated with the authenticated user. For that I'm using user=self.request.user in filter in queryset Notes/model.py class NoteQuerySet(models.query.QuerySet): def authenticated(self): return self.filter(user=self.request.user) def search(self, query): lookups = Q(title__icontains=query) | Q(tags__icontains=query) return self.filter(lookups).authenticated().distinct() class NoteManager(models.Manager): def get_queryset(self): return NoteQuerySet(self.model, using=self._db) def search(self, query): return self.get_queryset().search(query) class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True, default='Untitled') tags = models.CharField(max_length=150, blank=True) objects = NoteManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('notes:update', kwargs={'pk': self.pk}) In Notes/views.py class SearchNoteView(ListView): template_name = 'notes/my_notes.html' context_object_name = 'notes' def get_queryset(self, *args, **kwargs): query = self.request.GET.get('q', None) if query is not None: return Note.objects.search(query) But this return errors as AttributeError: 'NoteQuerySet' object has no attribute 'request' As the error states, it is trying to locate request funtion withing the class. How can I use the request in the queryset class? -
Form does not save time in database with generic class
Good afternoon, I have a form with different types of fields, including one where one hour is required (where I do not use a timepicker but a textinput). For the development of this form I use a .form class next to a generic view createview; where all the data except those that require the entry of an hour are saved. When presenting the data using another generic view, this field appears as None. I have tried, among several things, using the TextInput instead of the TimeInput, but without any difference. This is my model: class Reserva(models.Model): ESTADOS_CHOICES = ( ('AP', 'Aprobado'), ('PE', 'Pendiente'), ('NE', 'Negado'), ) SALONES_CHOICES = ( ('S1', 'Salon 1'), ('S2', 'Salon 2'), ('S3', 'Salon 3'), ('CA', 'Cafeteria'), ) usuario = models.ForeignKey(User) fecha_peticion = models.DateTimeField(auto_now_add=True, blank=True, null=True) asunto = models.CharField(max_length=80) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) salon = models.CharField(max_length=2, choices=SALONES_CHOICES, blank=True, null=True) hora_inicio = models.TimeField() hora_fin = models.TimeField() estado = models.CharField(max_length=2, choices=ESTADOS_CHOICES, blank=True, null=True) observaciones = models.CharField(max_length=100, blank=True, null=True) Este es mi formulario de la clase .form. class F_EnvioPeticion(forms.ModelForm): hora_inicio = forms.TimeField(input_formats=('%H:%M'), widget=forms.TimeInput(format='%H:%M')), class Meta: model = Reserva fields =[ 'asunto', 'fecha_inicio', 'fecha_fin', 'salon', 'hora_inicio', 'estado', ] labels = { 'asunto' :'Este es mi asunto:', 'fecha_inicio' … -
ValueError on uploading text file
ValueError at /path/upload/ Invalid file path or buffer object type: class 'django.core.files.uploadedfile.InMemoryUploadedFile'> I get the error above on uploading a text file (CSV) using Pandas. On my development environment, everything works smoothly but I get the error below on environment set up using uwsgi as app server and nginx as web server. -
Not able to get groups that belong to current user
I'm building a Django app that needs two things. First, it needs the set of groups that the user has access to. With this set of groups, my template is supposed to create a button for each group. Next, it needs the set of "Property" objects that are ManyToMany related to a group in the previously found set of groups (this is to say that I need every property that is assigned to a group that the user has access to). For each of these properties, a button is created. I'm working with an admin user on localhost right now while building this, and I've created a test group with test properties and assigned the admin user to that group. Django however, doesn't seem to be detecting this. The relevant code is below: views.py from __future__ import unicode_literals from django.shortcuts import render from UsageData.models import Property, User, Group, MeterData from django.contrib import auth def reports_proerty_list(request): if request.user.is_authenticated(): current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) return render(request, 'App/App-Template-Page.html') else: # The user is redirected to the sign-in page App-Template-Page.html <div class="row"> {% if current_user_groups %} {% for group in current_user_groups %} <div class="col-sm-2 col-md-2 col-lg-2 text-center"> <button class="tab-selector inactive" id="{{ group.id }}">{{ … -
Update content of static html file in Django
I saved an HTML as a static file in order to save it in cache and render it through a service worker when Offline. I would like to make a small change on my HTML in order to get the appropriate encoding. I am using pythonanywhere as my server. And I have defined in my settings.py the following paths: STATIC_URL = '/static/' STATIC_ROOT = u'/home/cocoa/cocoa/static' When I look at my file in the server in the following directory is: /home/cocoa/cocoa/static/login/Offline/HTML/mEstado.html My file looks like this: If I visit the following URL: https://cocoa.pythonanywhere.com/static/login/Offline/HTML/mEstado.html My file looks like this: I allready tried reloading on shift. Unabling the service-worker and python manage.py collectstatic But nothing seems to work. I do not know where the problem is, nor how to solve it. Any help would be appreciated. -
Missing argument inside a form of django app
I am trying to access a user product list inside the form of my django app. The user information should be the input options of a form from the app. What argument should I pass in my list_prod bellow? I am receiving the following error message: TypeError: list_prod() takes exactly 1 argument (0 given) Please Help! Form class ProductsForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(ProductsForm, self).__init__(*args, **kwargs) def list_prod(self): user_name = (self.request).user.username u = User.objects.get(username=user_name).accesslevel.prod.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) model = Factory Lists = forms.ChoiceField(choices=list_prod()) -
how to use ManyToManyField of model in itself
scenario i have group of users instrest in each others activity when ever a user of this group see a feed (record) or show some activity (like , comment , star) and continue. then whenever next user opens the app randomly sees the feed or show some activity (like , comment , star) so app will lead the second user to first user foot steps until it ignore the at least 3 feeds (records) so the best i come up with is ManyToManyField of model in itself by this method i will be able to classify every record (feed) and add all it's related feed back to the same model even witout adding a new record . example : Sam saw a feed 1 then Sam saw feed 5 then Sam saw feed 10 now it will add feed 5 and 10 as inner_feed to feed 1 and feed 10 to 5 is something like this model possible in django ? class NewsFeed(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, related_name="feeduser") date_created = models.DateTimeField(default=timezone.now) last_update = models.DateTimeField(default=timezone.now) inner_feed = models.ManyToManyField(NewsFeed) if there is anything hard to understand please ask -
Django converts value to tuple after model-field updating
I'm using Django 2.0. I have a model with a field declared as: px = models.DecimalField(max_digits=10, decimal_places=2, default=0) After getting an instance of this object from database, I try to update its property with: obj.px = "-2.6" The value "-2.6" comes from a variable, but I've tested with hard code: -2.6, 2.6, decimal.Decimal("-2.6"), etc. It always converts that value to a tuple I don't know why. What I get in django result is: argument must be a sequence of length 3 Django raises this error when calling the "save" method from the model, and it internally does the conversion: return decimal.Decimal(value) When I print the new value of "px" I get this: (2.6,) The only fix that I did was the following: if isinstance(obj.px, tuple): obj.px = obj.px[0] -
Django IntegerField ignores specified default value when blank=True and empty string posted
Consider the following model field: myfield = models.IntegerField(_('My field'), blank=True, default=0) If the myfield is completely omited from the post the default is properly used by default ModelForm implementation. However if empty string is posted for that field the field value stays None and postgres fails with the IntegrityError on non-null field: IntegrityError: null value in column "myfield" violates not-null constraint Question: How to enforce a default for both cases where either the myfield value is not present or present but empty string? -
Assigning JSON to a Python dictionary with POST and retrieving values with GET
I have a mobile app that is sending JSON to a Python 3.5.2 Django server in the form of POST requests. For testing I want to retrieve specific values from the posted JSON with GET requests to the same url. I've been trying to do this by initializing a global dictionary which is then updated by POST requests. This is my views.py: from django.http import HttpResponse from json import loads import json import string json_data = { "key_1": "placeholder_value_1", "key_2": "placeholder_value_2", "key_3": "placeholder_value_3" } def show_json(request): global json_data if request.method == "POST": body_unicode = request.body.decode('utf-8') json_data = json.loads(body_unicode) return HttpResponse("OK") if request.method == "GET": return HttpResponse(json_data['key_3']) My JSON in the POST request.body has the same keys as the json_data dictionary but different values. When I make GET requests after POST, this code returns placeholder_value_3 instead of the new value I want to assign it. I also tried initializing json_data as an empty dictionary with json_data = {} but GET requests just returned an empty string with that. I think this should be an easy problem for experienced Python programmers to solve but I'm a beginner and no other SO answers I've found have worked so far. What am I doing … -
DRF: Pass response from 3rd party API to serializer
Django Rest Framework serializers expect a QueryDictionary object that's created from a request. I query an API (it responds with a JSON object) in one of my views and use several attributes from the response in a model. The only field in the model that's part of the user's initial request is a foreign key so when I initialize my serializer I'm not sending it any data. Instead I send the data to the serializer when I call save on it. Now that works but it seems like how this should work is I use the API response attributes to initialize my serializer, however I'm having a difficult time getting them in the QueryDictionary object that the serializer likes. What am I missing? The API response format is: Customer object @ 0x7f5012351b38 JSON: {account_balance: 0, id=1235, name=foo bar, etc} -
How to get the date from foreign Key column in Django
I am new to Django.I have two tables StatusTable and SystemTable in where the SystemTable has a foreign column "Status" where is stores the id of the status from StatusTable.The data save is working fine as expected. I need to show the Statusname of the system in a Statuspage but instead I am getting only the id of the status stored in SystemTable. Models.py class StatusTable(models.Model): status = models.CharField(max_length=20,default='') def __str__(self): return self.status class SystemTable(models.Model): sid = models.CharField(max_length=3) status = models.ForeignKey(StatusTable,null=True) Viwes.py def systemstatuspage(request): form = CreateTaskMaster() task_title = TaskMaster.objects.all() my_list = [ model_to_dict(x) for x in task_title] return render(request, 'task/task.html', {'form': form, 'sid':my_list}) enter image description here -
Django scientific notation input validation
I have the following fields on my model: class Range(models.Model): optimal_low = models.DecimalField(max_digits=30, decimal_places=8) optimal_high = models.DecimalField(max_digits=30, decimal_places=8) And here's how I bring them into the form (because the form's primary object is not this model, I just need the fields, and don't want to duplicate the max_digits and decimal_places. class ReadingMappingForm(forms.ModelForm): optimal_low = Range._meta.get_field('optimal_low').formfield() optimal_high = Range._meta.get_field('optimal_high').formfield() It seems django allows entering of decimals in scientific notation out of the box, but there's a glitch above a certain threshold. In the form, if I input 1.5E9 it works fine, and the value gets saved as 1500000000.00000000 (Here's an online scientific notation calculator). However if I input 1.5E10 it says: Ensure that there are no more than 8 decimal places. Which is wrong, because I'm not adding any decimal places. In fact, if I enter 1.5E10 in normal notation, even with the 8 decimal places added, i.e. 15000000000.00000000 it works fine. So I think something is not working correctly under the hood... -
Django web services api deployed on IIS giving 500 server error when 500 concurrent requests are hit
I have django app as webapi running on Azure Application service. Production environment configurations are as- Web server : IIS 8 Application server : FastCGI So, This application will be having around 8k to 10k users. There is currently load testing is going on. Load testing observations are as- For 100 concurrent requests : Working Fine For 250 concurrent requests : All requests are passing but more response time For 500 concurrent requests : Most of the requests are failing. Which is giving 500 internal server error. When I checked application error logs there is None. I checked Azure app service logs, it is stating error in requests Can anyone suggest reason for requests failure. Do I have to do some specific configuration in FastCGI or other configurations ? Also I am open to hear alternative solution which helps to handle large load. Thanks in advance. -
django i18n doesn't work in mac
CommandError: errors happened while running msguniq msguniq: Cannot convert from "ASCII" to "UTF-8". msguniq relies on iconv(). This version was built without iconv(). I have mac high sierra. Already tried with brew install gettext & force options . Same error with anaconda. -
Django: How to handle the incremental id fields in a table
I'm swimming in my first Django project. Lately , a bunch of question came up to my mind. My big concern when I'm creating my app model is regarding how Django will take care of my tables when I will run the syncdb command.Firstly, let's introduce you on my scenario: app: different pages to show up according to the user profile Django 2.0 Python 3.6 DB: SQLite Relation diagram just for two likely tables in my model (one profile is linked with many users, whereas only one user is linked with one profile) Question I'm creating my model in the file project called model.py. I'm including a class per entity, I mean one class called user where I can define the kind of fields and the properties for each of this right. My question is more target on the model for profile. this entity or table that I'm not planning to use in my app. I know that once the model will be created the command syncdb will go thru the model.py file and create the required tables. Anways even if profile will not be part of the app I have to specify it as a class in my model? … -
Obtain the name of the logged user inside a form of a Django App and use the results as input of a form field
I would like to obtain the name of the logged user inside a form of a Django App and use the results as input of a form field. How can I do that? What should I do in my code? I tryied all the solutions. Here is my code Views.py form = ProductForm() Admin.py class AccessLevelInline(admin.StackedInline): model = AccessLevel can_delete = False verbose_name_plural = 'accesslevel' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (AccessLevelInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) Form.py user_name = HOW DO I ACCESS THE USER NAME HERE? u = User.objects.get(username=user_name).accesslevel.prod.split(',') v=(('---------','---------'),) for l in u: v=v+((l.lstrip(),l.lstrip()),) class ProductForm(forms.Form): model = Manufact Prod = forms.ChoiceField(choices=v) -
ModuleNotFoundError: No module named 'bigchaindb_driver'
I'm using Django with Python 3.6.3 and Windows 7. I'm trying to install BigchainDB driver and want to use IPDB. I run this pip install bigchaindb and I guess it executed successfully. I import bigchaindb_driver like that from bigchaindb_driver import BigchainDB. But when i run the server using python manage.py runserver it gives me this error. ModuleNotFoundError: No module named 'bigchaindb_driver' My code look like this: import os from bigchaindb_driver import BigchainDB> tokens = {} tokens['app_id'] = 'my-app-id' tokens['app_key'] = 'my-apy-key' bdb = BigchainDB('https://test.ipdb.io', headers=tokens) My questions are: If i want to use IPDB, i still have to install bigchainDB on my local machine? What exactly i need to start a project on bigchainDB, as i have installed MongoDB and RethinkDB but i don't exactly know weather i need them or not. -
Users for multiple sites in Django
I am trying to get multiple sites to use the same database and code but in a way which forces each user to have their own login to each site. I have seen a few suggestions as to how to make this work but I'm not sure which way to go. I am using the Sites Framework, using the subdomain to identify the current site so I'm not using SITE_ID at all. Use the sites framework - This answer (https://stackoverflow.com/a/1405902/1180442) suggests using the sites framework to do it, but I'm having trouble with the get_user() method, as it doesn't have access to the request and that's where my site info is stored. Use separate databases for users - I'm really not sure about this one but I think it might cause bigger problems down the line. Change to using SITE_ID - I want to try and avoid this if possible as it will mean having to run many different instances of my app, one for each site, which uses it's own settings.py. This will quickly turn into a nightmare, I think. Permissions - I'm wondering if this should be something that I get the permissions framework to use? So one … -
Sorting queryset by prefetched data attribute
I have two models in my models.py Charge(models.Model): ... SPA(models.Model): charge = models.ForeignKey(Charge) processing_date = models.DateTimeField() ... When I'm doing my queries I do Charge.objects.filter(my_filter).prefetch_related(Prefetch('spa_set', Spa.objects.filter(charge_id__in=queryset), to_attribute="spas"))` How would I filter charges by SPA's processing_time. Unsorted Charge1 spa - processing_time 12:30 Charge2 spa - processing_time 14:30 Charge3 spa - processing time 13:30 Sorted Charge1 spa - processing_time 12:30 Charge3 spa - processing_time 13:30 Charge2 spa - processing_time 14:30 -
MySQL table locking issue in Amazon RDS
We are hosting MySQL database in Amazon RDS platform. We see a lot of deadlock issues due to locking. I am trying to understand the deadlock dump report which roughly describes the affected transactions & no of locks etc. Following is such a trace: 2017-12-14 09:00:21 2ba3a5758700 *** (1) TRANSACTION: TRANSACTION 1297355720, ACTIVE 0 sec inserting mysql tables in use 1, locked 1 LOCK WAIT 7 lock struct(s), heap size 1184, 3 row lock(s), undo log entries 1 MySQL thread id 9198894, OS thread handle 0x2ba0b33da700, query id 5198593130 In the above trace, the 4th line says - 'mysql tables in use 1, locked 1'. What does 'locked 1' mean? Does it mean the concerned table is fully locked during the transaction? We are not explicitly locking the table. We use Django @transaction.atomic at certain places, but no explicit Table locking is there in our code. Please help me understand how can I debug the Table locking issue. -
display dictionary file inside for loop in django template
I have the following dictionary: d = {'21': 'test1', '11': 'test2'} {% with '18 17 16 15 14 13 12 11 21 22 23 24 25 26 27 28' as list_upper %} {% for x in list_upper.split %} {% if x in dental_position %} <input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]" value="{{display dict.value here}}"> {% else %}<input type="text" placeholder = "{{ x }}" class="form-control" name="tooth[]"> {% endif%} {% endfor %} I want to display the d[value] inside input text value attribute when values from d[key] is found in list_upper How can I call {% if d.keys in x %} in django template?