Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unescaping characters with Python (Django)
I am trying to show a list of Objects from my Postgres DB like this: # -*- coding: utf-8 -*- @python_2_unicode_compatible @csrf_exempt def eventlist(request): esemenyek = Event.objects.all().values() esemenyek_list = list(esemenyek) return JsonResponse(esemenyek_list, safe=False) This would work great but I use characters like óüöűáéúő and instead of these I get their escaped version like \u0171\u00e1\u00e9\u00fa\u0151\u00f3\u00fc\n\r. I spent a couple of hours trying to figure it out without any luck. -
Get multiple values
fields = ['first_name', 'last_name', 'birth_date'] user__first_name, user__last_name, birth_date = self.fields.get(fields) As self.fields is a list, it is not possible to do such thing. How could it possible to modify it so that it works? -
Running some task every 5 mins Django
I wrote small django website that read the data from data base and show that data in a table. (Database will be filled by making the request to an external API. ) Now my problem is that I need to make the request every 5 minutes to API and get the last 5 mins data and store them in the data base and at the same time update my table to show last 5 mins data. I have read about job scheduler but I did not get how I can perform it. First of all is an scheduler such as celery is a good solution for this problem? and would be helpful for me if you can guide me how would be the approach to solve this? -
Django web analytics
I want have web analytics module in my website, where I can see -who has logged in at what time by user name -From which location -Duration I have added google analytics, but I want to have my own dashboard in my website itself. Is there any package is that allow achieve my result or is there way I can use any web analytics tool inside my Django project -
ImportError No module named request
C:\Users\james\Desktop\FaceRecognitionAPI-master\FaceRecognitionAPI-master>python manage.py runserver Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 10, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 19, in check_resolver for pattern in resolver.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 33, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\james\Desktop\FaceRecognitionAPI-master\FaceRecognitionAPI-master\facerec\urls.py", line 6, in from api import views File "C:\Users\james\Desktop\FaceRecognitionAPI-master\FaceRecognitionAPI-master\api\views.py", line 9, in import urllib.request ImportError: No module named request -
Django `DateTimeRangeField` used with `date_hierarchy`
I have a DateTimeRangeField that I'd like to use with django's date_hierarchy but date_hierarchy needs a DateField or DateTimeField. I've written a function to convert the range into a datetime using range.lower, but this doesn't seem to work. eg. @admin.register(models.MyModel) class MyModelAdmin(AdvancedModelAdmin): date_hierarchy = 'date_range_to_datetime' def date_range_to_datetime(instance): """ Return a datetime from django date range. """ return instance.range.lower Is there a way to use a DateTimeRangeField with date_hierarchy? -
I cannot login from Dockered Django web application. What is wrong?
I successfully put my web application in a Docker container. Looking through... I can register users. When I tried to register the same user my web application says that the user is already registered. I cannot logged in as any users. I can go to admin login panel. I cannot logged in as an admin. Other than that everything went fine. I am using SQLite. And this is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./nginx:/etc/nginx/conf.d - ./static:/app/static depends_on: - web rabbit: hostname: rabbit_airport image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5673:5672" web: build: ./ container_name: django_airport volumes: - ./:/app - ./static:/app/static expose: - "8080" links: - rabbit depends_on: - rabbit I don't think I need separate container for SQLite don't I? -
How to test if one element from list is in other list in django filter
I trying to make this for query work using the Django filter. Any help? tmp = TemporaryLesson.objects.filter(Q(expiration_date__gte=now()) | Q(expiration_date__isnull=True)) temporary_lessons = [] for t in tmp: # How to make this manual query works in the filter above? for c in t.related_courses: if c in student.my_courses: temporary_lessons.append(t) break -
Multiple Logics in filter
I'm implementing ModelManger for privacy. Basically, I want to exclude some queryset for this case if post(Cloth)'s field only_me is true and owner of post(Cloth) is not logged in user. class ClothManager(models.Manager): def all(self, *args, **kwargs): return super(ClothManager, self).filter(???) Use Case return qs if only_me=false return qs if only_me=true and user=self.request.user (Can we call self.request.user in Model?) DO NOT return qs if only_me=true and user is not self.request.user I can use Q if it's needed -
Defining more models in a decorator
I have a pattern that I'd like to make as reproducible as possible, it goes something like this: class TranslatedThing(models.Model): name = models.Charfield(max_length=100) class Thing(models.Model): translation = models.ForeignKey(TranslatedThing) name = models.Charfield(max_length=100) The idea being that in my raw data I have some Things, which map to a reduced set of translated Things. Across many different data sets I have many different types of Things. I already use an Abstract class to reduce the complexity of this pattern: class AbstractThing(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True ------- class TranslatedThing(AbstractThing): pass class Thing(AbstractThing): translated = models.ForeignKey(TranslatedThing) But I'd like to automate the creation and linkage to TranslatedThing. Is this possible with a decorator? e.g. @translate class Thing(AbstractThing): pass ---- Thing.objects.filter(translation__name="foo") #works I've read through but it looks like maybe not. Is there any other way to reduce the repetition of code while using this pattern? -
How to escape single quote for a prop?
I have a Django context variable which is a jsonified list of strings but some of those strings might have a single quote ' import json list_of_strings = ["test", "hello", "I have a'single quote"] return render(request, 'template.html', { 'strings': json.dumps(list_of_strings) }) Then I insert it into a vue component through one of his props which, as you can see, must be wrapped between single quotes. :strings='{{ strings|safe }}' But it crashes, just insert the list until the first single quote and then writes everything else as text in the browser. How can I escape it? -
Sessions not getting created and deleted
i have made a login and logout form this way : http://blog.narenarya.in/right-way-django-authentication.html But now i am facing problem with sessions. As i have used the ways described in the above link, i have not made a login and logout view. Hence the login() and logout() function have not been used. Therefore the session is not getting created everytime i log in and not getting destroyed when i log out. //project/urls.py(the outer one) from django.contrib.auth import views from student.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/login'}), //forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) How do i do that? -
The pointer got nothing?
OrderedDict([('first_name', <django.forms.fields.CharField object at 0x7f9b5bed4c50>), ('last_name', <django.forms.fields.CharField object at 0x7f9b3b7abf50>), ('email', <django.forms.fields.EmailField object at 0x7f9b3b7abf10>)]) I have this dict, when I call self.fields. I am trying to get access the value of email with email = self.fields.get('email', False), which is supposed to be something like test@test.com, but I got . Is it because the space is not used yet? Otherwise, how could I get the value of email? -
Unable to build Solr schema in Django project
I'm going to build a schema using command $ python manage.py build_solr_schema. I'm using Apache Solr 4.10.4 in my Django powered project. When I ran Apache Solr, I got error: SolrCore Initialization Failures blog: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Could not load conf for core blog: Plugin Initializing failure for [schema.xml] fieldType. Schema file is solr/blog/conf/schema.xml Please check your logs for more information Solr logs: WARN - 2017-09-28 15:15:40.335; org.apache.solr.schema.FieldTypePluginLoader; TokenFilterFactory is using deprecated 3.6.0 emulation. You should at some point declare and reindex to at least 4.0, because 3.x emulation is deprecated and will be removed in 5.0 WARN - 2017-09-28 15:15:40.337; org.apache.solr.schema.FieldTypePluginLoader; TokenizerFactory is using deprecated 3.6.0 emulation. You should at some point declare and reindex to at least 4.0, because 3.x emulation is deprecated and will be removed in 5.0 WARN - 2017-09-28 15:15:40.338; org.apache.solr.schema.FieldTypePluginLoader; TokenFilterFactory is using deprecated 3.6.0 emulation. You should at some point declare and reindex to at least 4.0, because 3.x emulation is deprecated and will be removed in 5.0 WARN - 2017-09-28 15:15:40.338; org.apache.solr.schema.FieldTypePluginLoader; TokenFilterFactory is using deprecated 3.6.0 emulation. You should at some point declare and reindex to at least 4.0, because 3.x emulation is deprecated and will be removed in 5.0 WARN - 2017-09-28 … -
Getting a KeyError when edit profile
I am attempting to allow the user to edit user profile however I keep getting a KeyError. What am I doing wrong ? KeyError at /Identity/profile/edit/ 'password' Request Method: POST Request URL: http://127.0.0.1:8000/Identity/profile/edit/ Django Version: 1.10.5 Exception Type: KeyError Exception Value: 'password' Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/forms.py in clean_password, line 145 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 Python Version: 3.5.3 Python Path: ['/Users/iivri.andre/Nesting/Identity', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages'] This is the code the cause the error : UpdateAccount form : I imported these models to enable creation of the updateaccount form : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm I then created the UpdateAccoutnForm class which takes the UserChangeForm argument class UpdateAccountForm(UserChangeForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password' ) Code in views.py document from django.shortcuts import render, redirect from django.urls import reverse from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth.models import User from Identities.forms import CreateAccountForm, UpdateAccountForm This the function based view that will allow the editing the saving of the updated profile def edit_profile(request): if request.method == 'POST': form = UpdateAccountForm(request.POST) if form.is_valid(): form.save() return redirect('Identities:view_profile') else: return redirect('Identity/profile/edit') else: form =UpdateAccountForm(instance = request.user) var = {'form': form} return render(request, 'Identities/edit_profile.html',var) Tool versions … -
authentication login ( DJANGO )
I have an error in django authentication with a user model that extends from AbstracBaseUser and its id is a foreign key from another table. views.py enter image description here ModelsUser enter image description here ModelPeople from django.db import models from apps.area.models import Area from apps.company_dependence.models import CompanyDependence from apps.position.models import Position class People(models.Model): documentPeople = models.AutoField(primary_key=True, null=False) fullname = models.CharField(max_length=50) phone = models.IntegerField() address = models.CharField(max_length=50) email = models.CharField(max_length=50) codeArea = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE) codePosition = models.ForeignKey(Position, null=True, blank=True, on_delete=models.CASCADE) codeCompaDepen = models.ForeignKey(CompanyDependence, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.fullname) in the settings I put AUTH_USER_MODEL = 'user.User' -
Python/Django logging issues (syslog)
Hi, I am posting data to my REST-API, and get an HTTP 500 error. I have a fault in my models.py which I was able to fix already. The problem I have is with logging. I do get an e-mail of this error, but forwarding this error to syslog doesn't work. Syslog works otherwise. E.g. if I get HTTP 404 (Not found) this message is forwarded to syslog without problems. E-mail has this error-info: $ [Sep/28/2017 15:38:28] django.request ERROR Internal Server Error: /api/v1/organizations/ Traceback (most recent call last): File "..dev/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "some_code" violates not-null constraint DETAIL: Failing row contains (...). The above exception was the direct cause of the following exception: Traceback (most recent call last): ........ File "..dev/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "some_code" violates not-null constraint DETAIL: Failing row contains (.....). [Sep/28/2017 15:38:28] django.server ERROR "POST /api/v1/organizations/ HTTP/1.1" 500 22033 Settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format': '%(process)-5d %(thread)d %(name)-50s %(levelname)-8s %(message)s' }, 'simple': { 'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s', 'datefmt': … -
How to do an update method for a nested django rest framework APi Boolean ? [OnetoOneField]
So i have been researching about how to update the nested serializer with onetoonefield. However it has not been able to solve my problem. As i am still new to django rest framework, i am still inexperience about what is the problem as i never done an API before. models.py class Membership(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.BooleanField(default=False) serializers.py class MembershipSerializer(serializers.ModelSerializer): class Meta: model = Membership fields = ('membership',) class UserSerializer(serializers.ModelSerializer): membership = MembershipSerializer(many=False) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'is_staff', 'membership',) read_only_fields = ('id',) def create(self, validated_data): membership_data = validated_data.pop('membership') user = User.objects.create(**validated_data) Membership.objects.create(user=user, **membership_data) return user def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.password = validated_data.get('password', instance.password) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_staff = validated_data.get('is_staff', instance.is_staff) instance.save() membership_data = validated_data.get('membership') membership_id = membership_data.get('id', None) if membership_id: membership_item = Membership.objects.get(id=membership_id, membership=instance) membership_item.membership = membership_data.get('membership', membership_item.name) membership_item.user = membership_data.get('user', membership_item.user) membership_item.save() return instance views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [IsAuthenticated] def get_permissions(self): # allow non-authenticated user to create return (AllowAny() if self.request.method == 'POST' else permissions.IsStaffOrTargetUser()), screenshot of api https://i.imgur.com/dDqthRu.png As you can see above, my membership is null, … -
Django-Haystack: How to pass extra context with FacetedSearchView
This is my current view. class FacetedSearchView(BaseFacetedSearchView): form_class = FacetedProductSearchForm facet_fields = ['TopCategory'] template_name = 'shop-grid-ls.html' paginate_by = 20 context_object_name = 'object_list' extra = TopCategory.objects.all() def extra_context(self): return { 'extra': self.extra, } I can't access the 'extra' objects within my templates. How can I pass context through a FacetedSearchView. Thanks. -
django popup a window to show your mysql table
I want to create a button in the template that if i press submit i want a popup to show off and in that popup i want to display my Table from models.py. Basically i want that popup to have all the columns names and the all the date of that tabled display. with pagination if its possible Can someone please help me ? Thank you -
Long Mysql query results in website high loading time (not loading at all)
I've got a Django site and there is a long mysql query that runs every hour (query that I made) While that query runs, none of the pages on my Django websites can be loaded, it just hangs until the query finish... In general, I also got a PHP site on the same server and I've got the same issue there, so I'm guessing this is a configuration issue in Nginx or php-fpm? -
Saving a zipfile into directory using django
I am trying to save the zip file into one directory on my server. First, I am uploading a zip file using form and in python, I want to save it in one directory for further use. I got some piece of code after googling import os from zipfile import ZipFile zipf = ZipFile(frmUploadZipFile, 'w') zipdir('/data/apps/nms/maps/', zipf) def zipdir(path, ziph): for root, dirs, files in os.walk(path): for file in files: ziph.write(os.path.join(root, file)) Finally, after running this, I am getting some _ApRssiStore.txt file inserted in that folder. But not the zip file. I don't know whats happening in between. -
Django: prefetch_related grants performance only for non paginated requests?
For example, I have 1000 Users with lots of related objects that I use in template. Is it right that this: User.objects.all()[:10] Will always perform better than this: User.objects.all().prefetch_related('educations', 'places')[:10] -
RetrieveAPIView without lookup field?
By default RetrieveAPIView or RetrieveUpdateAPIView requires lookup_field to retrieve Model. However in my case, I want to retrieve my model by self.request.user. Here is views.py example class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileRetrieveAndUpdateSerializer lookup_field = 'user_id' def get_queryset(self): qs = Profile.objects.all() logged_in_user_profile = qs.filter(user=self.request.user) return logged_in_user_profile Can I use RetrieveAPIView without lookup_field? -
How to avoid race updating postgres.JSONField in Django?
Using Django I learned to use F object to mitigate race conditions when updating values on a model. Now I have a bit more complex problem - I have a model using PostgreSQL's JSONField and I want to update a value contained within the field. I tried doing something like this: year = arrow.utcnow().date().year my_model.stats['views'][year] = F('stats__%s' & year) + 1 Unfortunately an error pops up: TypeError: Object of type 'CombinedExpression' is not JSON serializable I understand it can be done by using some intermediate models to simulate JSON structure but it is out of question here. So the problem is as in title - how to do this in Django? If not possible, what SQL syntax would do that?