Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
create a separate app for my REST api or inside my working app "Django"?
I'm building simple gis system on geodjango. the app displays set of maps and I'm also attending to provide RESTFULL api for these maps, but I'm facing a decision weather to create separate app for the api or working inside my existing app, the two apps are logically separate but they share the same models. So what is better??? -
Get unicode string rather than id when getting Foreign Key field values
I have a function that returns the field names and values of an object for a custom template tag in Django. def get_obj_fields(obj): try: return [(field.verbose_name, field.value_to_string(obj)) for field in obj._meta.fields] except: return But field.value_to_string(obj) is returning the Foreign Key IDs, and I want to print the __unicode__(self) result. Is there a simple way to do this? So if I run the function on an item, I want it to return the Category name rather than the ID. class Item(models.Model): category = models.ForeignKey(Category, verbose_name="Category") class Category(models.Model): name = models.CharField(max_length = 30, verbose_name="Name") def __unicode__(self): return str(self.name) Thanks -
How do I automatically backup db.sqlite3 file in Django App hosted on Azure Web Apps?
I have a Django web application hosted on _________.azurewebsites.net The folder structure is as follows: - Github Repository - settingsFolder - app1folder - app2folder - manage.py - web.config - db.sqlite3 I have Azure set up to where a push to my remote github branch causes Azure to sync the files with my Github branch to my /site/wwwroot/ folder. Explicitly, git push origin branch This causes a problem. Everytime I try to add changes to my website, using git push, the db.sqlite3 DOES NOT reflect the changes within the website environment. Thus, if someone were to save data to /site/wwwroot/db.sqlite3, then my github repository would be UNAWARE of the changes. Updating my github repository would take the OLD db.sqlite3 and reupload THIS OLD during a file sync between Azure and github. Consequently, the db.sqlite3 on /site/wwwroot/ gets overwritten and data would be lost. One solution is to manually make backups by connecting to my /site/wwwroot folder, saving db.sqlite3, and replacing it regularly in my Github repository. Is it possible to automate this? If so, what resources does Azure provide me to do so? -
Django add field to query set
Hi i have 3 models in my django projects: Material(has id,default price, and other informations for material) Dealer(has id, and informations about dealer) MaterialDealerDiscount(has material_id,dealer_id,and discount_ percent) when user send request i have his dealer_id i need return query set with info about material from Material table and for each row add discount_percent from last model where dealer_id = current dealer_id and row id. Please help me if you have answer. -
Django one user login per IP
How can I allow only one user login per IP in django? limiting number of concurrent users. I am new to django and quick and easy solutions will be appreciated. -
Creating multiple django objects with multiple django form entries
I'm trying to essentially create a quiz for a web app (user creates the quiz given a certain input of 1-25 questions). From here they can view a page with their set number of entry fields (1-25) and submit them to associate the questions and answers entered with the quiz they made (e.g. NewQuiz might have 5 questions and answers). My problem is, I don't know how to create 5 questions and answers in the one form with 1 submit button, and currently submitting all fields just saves the most recent field in the list (question and answer 5 will be saved out of 1-5 questions and answers). Would anyone be able to direct me on how to submit multiple objects of the same type over the one form? This is what I'm currently doing: views.py form = EditQuizForm(request.POST or None) if form.is_valid(): question_text = form.cleaned_data['question_text'] answer_text = form.cleaned_data['answer_text'] try: get_latestq = Question.objects.latest('id') latest_idq = get_latestq.id get_latesta = Answer.objects.latest('id') latest_ida = get_latesta.id except ObjectDoesNotExist: latest_idq = 0 latest_ida = 0 newQuestion = Question(question_text = question_text, exam = examInstance, related_quiz = examInstance.exam_id, id = latest_idq + 1) newQuestion.save() newAnswer = Answer(text = answer_text, question = newQuestion, related_quiz = examInstance.exam_id, id = … -
How to add not null unique value to existing Django Model with default attribute
I need to add slug field to django model, and i thing it's better when it not null. So i'm trying to add slug to model slug = models.SlugField( 'URL', unique=True, default=id_generator, ) my id_generator: import string import random def id_generator(): size=16 chars=string.ascii_lowercase + string.digits return ''.join(random.choice(chars) for x in range(size)) The problem is when i migrate changes. Method id_generator is calling one time and uses the same value for all model objects. So i have dupliicate entrie in unique field. How can i generate unique values? Django 1.11.5 P.S. I understand, that i can set null=True and customize model's save method to add slug when saving. -
Use django ORM with multiprocessing?
I have a Django ORM database (mysql or sqlite), and would like to process each row with a fairly computationally intensive operation. What I have right now is something like: entries = Entry.objects.filter(language='') for e in entry: e.language = detect_language(e.text) e.save() If the database was the bottleneck, I would use a transaction to speed it up. However, the detect_language function is what takes the most time. I could try to run the script multiple times in parallel, but that would introduce a race condition. I think this could be done with multiprocessing using Pool.map() - the main process fetches the DB entries, the child processes run detect_language. I am not sure how to do it in detail, e.g. whether to save the entries in the child process or in the main process. Is there anything to take care of when passing ORM objects between processes? Can you give a short example how to use the ORM with multiprocessing?