Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Views.py needs to access Class and Function in another python file
in my helper.py I have a class and a function definition: class Suites(): NAME_SUITE = ['NATE', 'TOM', 'TED', 'JAN', 'SAM'] def check_suite(name, suite): my_suite = Suites[suite] #I want my_suite to = ['NATE', 'TOM', 'TED', 'JAN', 'SAM'] return name in suite #I want to return True or False and in views.py I'm trying to find out that user_in_suite is True from .helper import check_suite from .helper import Suites def apps(request): user_name = 'NATE' suite_to_check = 'NAME_SUITE' user_in_suite = check_suite(name=user_name, suite=suite_to_check) But I'm getting an error for helper.py: 'classobj' object has no attribute '__getitem__ -
Model of database for spare parts in django
I'm trying to figure out how to model the database for a spare part app. Main concern now is the quantity of each part. Some are in pieces, meters, Kg and so on. Some parts needs decimals and some should not have decimals. This is my raw idea of a basic model. class Part(models.Model): name = models.CharField(max_length=550) class PartNumber(models.Model): partnumber = models.CharField(max_length=50) part = models.ManyToManyField(Part, related_name='partnumber') class Unit(models.Model): name = models.CharField(max_length=50) si_unit = models.CharField(max_length=10) class Stock(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) unit = models.ManyToManyField(Unit, related_name='unit') part = models.ManyToManyField(Part, related_name='part') Problem is how I should solve the 'quantity' in 'Stock'. Is it better to have two fields? It does not feel right that way either. -
Django Many to Many Data Duplication?
Background I'm storing data about researchers. eg, researcher profiles, metrics for each researcher, journals they published in, papers they have, etc. The Problem My current database design is this: Each Researcher has many journals (they published in). The journals have information about it. Likewise for Subject Areas But currently, this leads to massive data duplication. Eg, the same journal can appear many times in the Journal table, just linked to a different researcher, etc. Is there any better way to tackle this problem? Like right now, I have over 5000 rows in the journal column but only maybe a few hundred unique journals. Thank you! Model - Researcher class Researcher(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) scopus_id = models.BigIntegerField(db_index=True) # Index to make searches quicker academic_rank = models.CharField(max_length=100) title = models.CharField(max_length=200,default=None, blank=True, null=True) salutation = models.CharField(max_length=200,default=None, blank=True, null=True) scopus_first_name = models.CharField(max_length=100) scopus_last_name = models.CharField(max_length=100) affiliation = models.CharField(default=None, blank=True, null=True,max_length = 255) department = models.CharField(default=None, blank=True, null=True,max_length = 255) email = models.EmailField(default=None, blank=True, null=True) properties = JSONField(default=dict) def __str__(self): return "{} {}, Scopus ID {}".format(self.scopus_first_name,self.scopus_last_name,self.scopus_id) Model - Journal class Journal(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) researchers = models.ManyToManyField(Researcher) title = models.TextField() journal_type = models.CharField(max_length=40,default=None,blank=True, null=True) abbreviation = models.TextField(default=None, blank=True, null=True) … -
How do I override the django admin LogEntry model
I want to change the model used for the default LogEntry class so it creates a varchar rather than a clob in the database for the attribute "object_id" The original model is defined in django/contrib/admin/models.py class LogEntry(models.Model): action_time = models.DateTimeField(_('action time'), auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.TextField(_('object id'), blank=True, null=True) object_repr = models.CharField(_('object repr'), max_length=200) action_flag = models.PositiveSmallIntegerField(_('action flag')) change_message = models.TextField(_('change message'), blank=True) I want to change the definition of object_id to object_id = models.Charfield(_('object id'), max_length=1000, blank=True, null=True) I'm aware that this could cause issues if someone defined a primary key on an entity which is larger than a varchar(1000), but I wouldn't want an entity with a PK defined like that so I'm happy with the limitation. This will greatly improve the efficiency of the queries when accessing the history log. I don't really want to hack the actual model definition, but I can't find out how to elegantly override the model definition. Any ideas? -
FAILED (failures=1) Destroying test database for alias 'default' Is it ok?
I wrote test code,and run the file. I wrote this code from django.test import TestCase from app.models import User # Create your tests here. class UserModelTests(TestCase): def test_is_empty(self): saved_db = list(User.objects.values()[:2]) expected = [{'name': Tom,'user_id': 1,'nationarity': America, 'dormitory':'A', 'group': 3,'name': Bob,'user_id': 2,'nationarity': China, 'dormitory':'B', 'group': 4}] self.assertEqual(expected, saved_db) so the result is System check identified 60 issues (0 silenced). F ====================================================================== FAIL: test_is_empty (app.tests.UserModelTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/app/tests.py", line 12, in test_is_empty self.assertEqual(expected, saved_db) AssertionError: Lists differ: [{'name': 1, 'fixed_constructi[4938 chars]: 0}] != [] First list contains 1 additional elements. First extra element 0: {'name': Tom,'user_id': 1,'nationarity': America, 'dormitory':'A', 'group': 3,'name': Bob,'user_id': 2,'nationarity': China, 'dormitory':'B', 'group': 4} Diff is 5605 characters long. Set self.maxDiff to None to see it. ---------------------------------------------------------------------- Ran 1 test in 0.013s FAILED (failures=1) Destroying test database for alias 'default'... I cannot understand this code is ok or not.When I print out saved_db several times,the order of the list is changed each time.So I doubt I can compare list of expected& saved_db correctory.Is it ok?Should I fix this? -
Accessing the database from an external application, with Django REST Framework
Since I need an external application (based on C) to get data from the database of my Django application, I have built an API based on Django REST framework. Here's my serializers.py from rest_framework import serializers from .models import Step, Cycle, Program, MotorSetting, GeneralSetting class ProgramSerializer(serializers.ModelSerializer): class Meta: model = Program fields = '__all__' Now, when I access the url linked to the API, I can definitely see the JSON string correctly. However, when I try and use a software like Packet Sender to see if I can receive the JSON data, it does not work. I get a 400 error. Does anyone know what could be the cause? Is there any detail that I'm leaving out from my code? Thanks in advance. -
Wagtail ignoring settings such as ALLOWED_HOSTS
I'm running nginx, gunicorn and wagtail on Ubuntu 16.04. I am not using virtualenv. Both nginx and gunicorn seem to work just fine but when I go to my domain in a browser (let's say myweb.com) I get a disallowed host error. This seems like a simple problem but I have already added myweb.com as an allowed host in base.py like so: ALLOWED_HOSTS = ['myweb.com']. It even says in the request information that myweb.com is an allowed host in the settings file but it seems like wagtail is just ignoring that. I also tried turning debug off in the dev settings but it still showed me the debug screen. -
Django authenticate is None
def user_login(request): if request.method == "POST": user_name = request.POST.get("username",'') pass_word = request.POST.get("password",'') user = authenticate(user_name=user_name,password=pass_word) if user is not None: login(request,user) return render(request,'index.html') else: return render(request,'login.html',{ }) elif request.method == "GET": return render(request,"login.html",{ }) I've already set up the super user and updated the database, but the backstage password user still returns None -
Django 'dict' object has no attribute 'save' on UpdateView
I am trying to update my model with UpdateView but when I click update I get this error: 'dict' object has no attribute 'save' forms.py class InvoiceUpdateForm(forms.ModelForm): class Meta: model = Invoice fields = [ 'filed1', 'filed2', 'filed3', 'filed4', 'filed5', 'filed6', 'filed7', ] models.py class InvoiceUpdate(LoginRequiredMixin, generic.UpdateView): model = Invoice login_url = '/accounts/login' redirect_field_name = 'redirect_to' form_class = InvoiceUpdateForm success_url = '/' template_name = 'invoice/invoice_update.html' def form_valid(self, form): #save cleaned post data clean = form.cleaned_data context = {} self.object = context.save(clean) return super(NarocilnicaPosodobi, self).form_valid(form) -
Can't use self.request in Serializer: Any way to check logged-in user in Serializer?
I'm facing the inevitable situation that I have to check user's logged in in Serializer. It returns whether logged-in user have liked the post or not Here is PostDetailView. class PostDetailView(generics.RetrieveAPIView): queryset = Outfit.objects.all() serializer_class = PostDetailSerializer lookup_field = 'pk' This is its serializer class PostDetailSerializer(serializers.ModelSerializer): ... like_count = serializers.SerializerMethodField() liked = serializers.SerializerMethodField() ... class Meta: model = Post fields = ( ... 'like_count', 'liked', ... ) def get_liked(self, obj): content_type = obj.get_content_type object_id = obj.id ### Right Here! I can't get self.request.user; my_like = Like.objects.filter_by_instance(obj).filter(user=self.request.user) if my_like == 0: return False return True # this is just an example def get_like_count(self, obj): content_type = obj.get_content_type object_id = obj.id like_count = Like.objects.filter_by_instance(obj).count() return like_count Since Serializer doesn't have request attribute, we can't import it. How can I return whether the post is liked or not? More info: I have explicit Like model to store user's likes class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) class Post(models.Model): ... Maybe I can use ModelManager to solve this problem. But ModelManager doesn't have request either! Frustrating... :( -
Django 403 Forbidden Error
When I try the ajax in same page to html it works. Like this; <html> <head> ... </head> <body> .... <script> $.ajax({ url: /test/, method: 'POST', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: { name: a, surname: b}, dataType: 'json', success: function (data) { getList(data); } }); </script> </body> </html> When I try the call same javascript as external. It doesn't work. Why? <html> <head> ... </head> <body> .... <script src="{% static 'js/test.js' %}"></script> </body> </html> -
Allow 1 view generation per user in Django
Having this question I came up with the code below. The behavior should be as follows: each Suggestion can receive several Vote Only 1 Vote per user is allowed It works fine but I was wondering what's the best way to do this? vote_form.html <form action="{% url 'add_vote' suggestion.id %}" method="post"> {% csrf_token %} <input type="submit" value="I want to vote"> </form> urls.py urlpatterns = [ url(r'^suggestion/(?P<pk>\d+)/$', views.SuggestionDetail.as_view(), name="suggestion_detail"), url(r'^suggestion/(?P<pk>\d+)/vote/$', views.add_vote, name='add_vote'), ] models.py class Vote(models.Model): suggestion = models.ForeignKey(Suggestion) voter = models.ForeignKey('auth.User') vote_count = models.BooleanField() views.py def add_vote(request, pk): suggestion = get_object_or_404(Suggestion, pk=pk) vote = Vote( suggestion = suggestion, voter = request.user, vote_count = True) has_user_voted = Vote.objects.filter(voter=request.user, suggestion=suggestion).count() if has_user_voted < 1: vote.save() else: messages.error(request, 'It seems you have already voted, only one vote is allowed') return HttpResponseRedirect(reverse('suggestion_detail', args=(suggestion.id,))) -
AngularJS html5mode in a django app deployed in Heroku
I have a django + angularjs app that is deployed in Heroku. I am trying to serve /admin, /api urls from django app and all others from angular-route. I found that the best practice is to change the configuration of my server so that based on the resource requested, to decide if it will reply with index.html (so that angular-route will handle it) or will forward the request to urls.py. https://jee-appy.blogspot.gr/2016/11/remove-hash-from-angularjs-urls.html The problem is that i dont know how to configure heroku. i cannot find apache2.conf or any other file. -
How to make a model show up in the admin-section, in Django?
I am new to Django and Python. Currently, I am creating a website for weightlifting. Below is a simple model, with a lifter and results: class Lifter(models.Model): name = models.CharField(max_length=250) gender = models.CharField(max_length=1); person_photo = models.CharField(max_length=1000); def __str__(self): return self.name + ' - ' + self.gender class Results(models.Model): lifter = models.ForeignKey(Lifter, on_delete=models.CASCADE) points = models.CharField(max_length=4, default=0); In the same app, there is a file called admin.py where I wrote: from django.contrib import admin from .models import Lifter admin.site.register(Lifter) Unfortunately, when I log into the admin-panel, there is no lifter-model to be seen. I have made sure to create the admin as a super-user, so the permissions should be there. In addition to this, the "usermanagement"-app (where the Lifter-model is stored) , has been added to settings.py in the main app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'athlitikos', 'usermanagement', ] Does anyone know what I should change to make this work? Thank you! -
AttributeError: 'UserMF' object has no attribute 'id'
In the models.py, please attent there I did not give the id in User model: class User(models.Model): username = models.CharField(max_length=16) password = models.CharField(max_length=16) ... In the ModelForm, I put the id in the UserFM: class UserMF(ModelForm): class Meta: model = models.User fields = ('id', 'username', 'password', 'phone', 'email') When I get the user's id, I will get the bellow error: AttributeError: 'UserMF' object has no attribute 'id' How to solve this issue, who can help me with that? -
Django 1.11 Custom User-model with Groups
I am trying to add a ForeignKey between my User(AbstractBaseUser)-model and the built-in Group-model. My issue now is that I cannot create a superuser, as it requires to fill the group field with 'something'. I have created a group through the shell, called admin with id 1. However, I can't find a way to create my superuser and set the group to admin on creation ... Here is models.py in my /accounts app: from django.db import models from django.forms import ModelForm from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, Group ) class UserManager(BaseUserManager): def create_user(self, email, group, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = UserManager.normalize_email(email), password = password, group = group ) user.set_password(password) user.save() return user def create_superuser(self, email, group, password): user = self.create_user( email = UserManager.normalize_email(email), group = group ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save() return user class User(AbstractBaseUser): objects = UserManager() date_added = models.DateField(auto_now=False, auto_now_add=True) email = models.EmailField(unique=True, db_index=True) group = models.ForeignKey(Group) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['group'] is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_perms(self, perm, obj=None): … -
Upload path argument error on form.save()
I'm trying fileuploads in Django - I'm having issues with saving a form with a file field in it. I have similar views to this that work absolutely fine, I don't understand why an error is being raised on this one. from django.conf import settings from django.core.files.storage import FileSystemStorage def view1(request): ... if request.FILES['pdf']: pdf = request.FILES['pdf'] save = FileSystemStorage(location=upload_path("apple", "cherry", "grapefruit") if form.is_valid(): form.save() ... Then in my models.py def upload_path(var1, var2, var3): return "{}/{}/{}/".format(var1, var2, var3) Here's the traceback Internal Server Error: /app/view1/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Code\app\views.py", line 216, in view1 form.save() File "C:\Python27\lib\site-packages\django\forms\models.py", line 463, in save self.instance.save() File "C:\Python27\lib\site-packages\django\db\models\base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python27\lib\site-packages\django\db\models\base.py", line 962, in _do_insert using=using, raw=raw) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1076, … -
django REST framework - limited queryset for nested ModelSerializer based on requesting user
How can I limit a the queryset of a related field with custom model serialiser based on the request user? I have implemented this with a SerializerMethodField, but it seems not the best solution. -
How to add extra attributes to queryset in django rest api using serialiser and listViewAPI?
How do I add additional fields like count, status_code to the queryset in the django rest api ? class SongList(generics.ListAPIView): """ API endpoint that allows users to be viewed or edited===1111. """ serializer_class = SongSerialier def get_queryset(self): queryset = Song.objects.all() id = self.request.query_params.get('id', None) test=QuerySet() return queryset Above code returns only the content in the SongSerialier in the form of list, for example[ { "song_title": "song1", "file_type": "mp3", "album": 1, "test": "1", "my_field": false }, { "song_title": "song1", "file_type": "mp3", "album": 2, "test": "1", "my_field": false } ] I want my out like the below format As { status_code:200, count:2, total_count:4, data:[ { "song_title": "song1", "file_type": "mp3", "album": 1, "test": "1", "my_field": false }, { "song_title": "song1", "file_type": "mp3", "album": 2, "test": "1", "my_field": false } ] }## This is my first post, So please ignore if any issues in the question ## -
How to solve the "CASCADE() missing required positional arguments" TypeError
I am new to Django and Python. I have created some models in Django, and now can no longer run the application because of the following error: "TypeError: CASCADE() missing 4 required positional arguments: 'collector', 'field', 'sub_objs', and 'using'" Here is the model code: class Lifter(models.Model): name = models.CharField(max_length=250) age = models.IntegerField(max_length=100); gender = models.CharField(max_length=1); person_photo = models.CharField(max_length=1000); def __str__(self): return self.name + ' - ' + self.gender class Results(models.Model): lifter = models.ForeignKey(Lifter, on_delete=models.CASCADE()) Any idea on what is wrong? Thank you! -
Like we use __str__ to return strings what do we use to return numbers. I mean Integerfield and deciamlfield? [on hold]
average = models.DecimalField(max_digits=4, decimal_places=2) def __str__(self): return self.average what to use to return a decimafield? Also if I wanted to return both charfield and decimalfield, what should I use? Thank you. -
how to deploy django project into production server? [on hold]
I am new at django please help me how i can deploy my project into production server. when i apply "fab deploy" command into my terminal then i have got this error "zsh: command not found: fab". secondly, how to fix errors if the production server isn not working but local server is working fine. -
Python - 'bytes' object has no attribute 'encode' [on hold]
When I try to run this code using Python 3.6.1 for date, row in df_stocks.T.iteritems(): try: sentence = unicodedata.normalize('NFKD', df_stocks.loc[date, 'articles']).encode('ascii', 'ignore') I get an error shown below. Any ideas how can I solve it? Traceback (most recent call last): File "/Users/myuser/Projects/TestPrediction/test2.py", line 33, in <module> ss = sid.polarity_scores(sentence) File "/Users/myuser/Projects/DeepLearning/lib/python3.6/site-packages/nltk/sentiment/vader.py", line 223, in polarity_scores sentitext = SentiText(text) File "/Users/myuser/Projects/DeepLearning/lib/python3.6/site-packages/nltk/sentiment/vader.py", line 158, in __init__ text = str(text.encode('utf-8')) AttributeError: 'bytes' object has no attribute 'encode' -
Request headers in Django are received only for POST, but not for GET method
I'm having a weird issue: When sending a GET request with headers from my local machine to our server, I cannot see these headers in the Django backend: I send the request like so: import requests r = requests.get('https://example.com/', headers = { 'X-Forwarded-Host': 'foo.bar' }) In Django, I check for the header like this: if 'HTTP_X_FORWARDED_HOST' in request.META: # do something It does work properly, though, when making POST requests: import requests r = requests.post('https://example.com/', headers = { 'X-Forwarded-Host': 'foo.bar' }) The only header that works, is Host ... and I'm at the end of my wits :-P The requests are received by an NGINX server using WSGI. Any idea what could coulde POST headers to get passed through, and GET headers to be removed or cleared? -
How to query the fields which contains comma seperated values in db?
I have a table called Demo which consits of two fields i.e; Name,hobbies. hobbies contains comma seperated values in db. for example: "eating,sleeping,dancing" now i have to query for the field hobbies which contains "eating,sleeping". I have tried Demo.object.get(hobbies__in=['eating','sleeping']) I am getting matching query does not exists How can i solve this