Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while serializing queryset object in Django Rest Framework
I am trying to serialize my queryset object and getting error as below, Exception Type: AttributeError Exception Value: Got AttributeError when attempting to get a value for field `fullName` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'fullName'. Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/user/crud/ Django Version: 1.9 Python Version: 2.7.10 Installed Applications: ['rest_framework', 'background_task', 'userApp', 'imageUpload', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\viewsets.py" in view 87. return self.dispatch(request, *args, **kwargs) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch 466. response = self.handle_exception(exc) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\views.py" in dispatch 463. response = handler(request, *args, **kwargs) File "C:\Users\JpG\Desktop\CYC_Heroku\userApp\views.py" in create 24. return Response(data=serializer.data) # {"detail": "Mobile Number already exist"}) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data 503. ret = super(Serializer, self).data File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in data 239. self._data = self.to_representation(self.instance) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\serializers.py" in to_representation 463. attribute = field.get_attribute(instance) File "C:\Users\JpG\Desktop\herokuEnv\lib\site-packages\rest_framework\fields.py" in get_attribute 422. raise type(exc)(msg) Exception Type: AttributeError at … -
How to create new object by form if no result is found in Django-autocomplete-light V3
Django-autocomplete-light has provided create new choice feature. However, is there a way to create object by pop-up form on the fly (filled out all the fields rather than only create_field) instead of searching keywords only. I've searched the relevant topics, but it seems that the only related topic is this issue asked by @blueyed, and it seemed to be outdated. Could anyone give me some advices how to implement it? Or maybe some alternative packages will be fine. Thank you in advance. -
Primary key not updating automatically when using Django to insert into the DB
I have a postgres table: Table "public.channels" Column | Type | Modifiers | Storage | Stats target | Description ------------+-----------------------------+-------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('channels_id_seq'::regclass) | plain | | area | character varying(12) | not null | extended | | measure | integer | Indexes: "channels_pkey" PRIMARY KEY, btree (id) I can insert into this table using psql, and the id column, which I don't specify, increments each time. I end up with several entries in the table. I have this Django model for this table: class Channels(models.Model): area = models.CharField(primary_key=True, max_length=12, editable=True) measure = models.IntegerField(blank=False, null=False) def __str__(self): return str(self.measure) class Meta: verbose_name_plural = 'Channels' managed = False db_table = 'channels' I am trying to insert like this: area = 'site b' for sample in samples: measure = sample['measure'] ch = Channels(area=area, measure=measure) ch.save() This inserts each measurement into the table. But the primary key does not increment, and at the end, the last measurement is the only one in the table. It has the data from the last sample from samples. Why isn't the primary key incrementing automatically, so that each measurement goes into its own row? -
how to set up Django filter_horizontal filtering in admin page?
I have been reading quite a few threads and postings about this build in filter_horizontal provided by django. Somehow I tried and just wouldn't get it to work. Can someone please give me a hand? Also, I am not trying to add this into any public view. I am trying to add it into an admin page. I have these 3 models: group, file, student student to file is a many to many field. Let's say this works as.... students signs up, I as admin will put the student into a certain group. Let's say Group Vacation. I will also upload a file from admin page. Then what I really want here is...I need to assign the file created into a group. BUT when I do the assign file to a group, it uses a dropdown like the image below. Let's say if I have 100 files, 100 groups or even more. It'll be annoying to go through the dropdown though. So I want to try doing something such as or at least something close to it. It has a filter, and I can see the selections in multiple select options. Been searching around and saw the filter_horizontal but, I … -
Styling error messages with bootstrap
I'm building my own form to git rid of help text, As I can't change the builtin form in django to remove the help text. So far so good, but I can't style the error messages. It's showing basic ul and il style. How can I do it ? Thanks. <form class="" method="post"> {% csrf_token %} <label for="id_new_password1"> Senha </label><br> <div class=""> <input required text="password" class="form-control" placeholder="Senha" name="new_password1"/> {{ form.new_password1.errors }} </div><br> <label for="id_new_password2"> Confirmar senha </label><br> <div class=""> <input required text="password" class="form-control" placeholder="Confirmar senha" name="new_password2"/> {{ form.new_password2.errors }} </div><br> <input type="submit" class="btn btn-primary col-sm-12" value="Confirmar" /> </form> -
oDjango many to many field with available app_labels
Hi is it possible for a model to have a ManyToManyField with all the available apps as its choices? Let's say I have these apps on the INSTALLED_APPS in my settings.py Then in my models.py I have this model class IPAddreses(models.Model): ip = models.GenericIPAddressField() apps = models.ManyToManyField(ContentType, blank=True) # The apps field should be the one with the choices of the avialable apps # on the settings.py Is it possible? -
Parse queryset in templates
hi all Have a structure objects userfavs = UserFavs.objects.filter( user_id=self.request.user.id) userfavs dish (id = 3) shop (id = 1) dish (id = 30) shop (id = 2) dish (id = 5) shop (id = 1) dish (id = 15) shop (id = 2) in template i should have shop (1) - shop(2) dish (3) - dish (15) dish (5) - dish (30) I can't understand how i should regroup query set for give needed result? can u help me? -
Django how to get something by foreign key' value?
I have a model: from django.contrib.auth.models import User # Create your models here. class Strategy(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mod_date = models.DateTimeField(auto_now=True) strategy_name = models.CharField(max_length=20) strategy = models.TextField() position = models.TextField() I want to get username = "leo". But in Strategy's user is using user_id. How to get "models.Strategy.objects.get" or "models.Strategy.objects.filter" using username = "leo"? Thank you. -
500 Internal Server error from mod_wsgi and django rest
I have looked at every similar question about this and still can't figure out what's wrong. I'm try to set up a python REST service on my VPS alongside my wordpress site. I can get a "Hello world" wsgi file to run no problem, but when I point to my django rest wsgi file, I get a 500 server error. My wordpress site is in /var/www/html/mysite/public_html, and the rest service is in /var/www/html/mysite/myrest. www-data has ownership of everything in the mysite folder. I've installed all dependencies, and started the project with python manage.py runserver just to make sure it's not missing anything. This is my wsgi file. import os import sys import site site.addsitedir('/var/www/html/mysite/myrest/lib/python2.7/site-packages') sys.path.append('/var/www/html/mysite/myrest') os.environ['PYTHON_EGG_CACHE'] = '/var/www/html/mysite/.python-egg' os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Before it didn't have the site.addsitedir stuff, that got added as I tried different solutions. There's some weird stuff going on in the apache logs, but I couldn't make sense of it. [Sun Feb 19 20:39:33.697146 2017] [core:notice] [pid 26048] AH00094: Command line: '/usr/sbin/apache2' [Sun Feb 19 20:41:30.804083 2017] [mpm_prefork:notice] [pid 26048] AH00169: caught SIGTERM, shutting down [Sun Feb 19 20:41:31.707014 2017] [wsgi:warn] [pid 26721] mod_wsgi: Compiled for Python/2.7.11. [Sun Feb 19 20:41:31.707037 2017] … -
Django object.image.url not displaying even though path is correct
I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere? Models.py: from django.db import models # Create your models here. class Connect(models.Model): title = models.CharField(max_length=70) short_description = models.TextField(null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='media', blank=True, null=True) def __str__(self): return self.title views.py: def index(request): about = About.objects.all() staff = Staffmembers.objects.all() ministries = Ministries.objects.all() connect = Connect.objects.all() context = { 'template': 'home', 'connect': connect, 'about': about, 'staff': staff, 'ministries': ministries, } return render(request,'home/index.html', context) template(index.html): <div class="connect-wrapper row"> <h1 class="title connect-title">Connect</h1> {% for object in connect %} <div class="home-div connect-div col-md-4"> <h4>{{ object.title }}</h4> <p>{{ object.short_description }}</p> {% if object.image %} <img class="connect-image-home" src="{{object.image.url}}" alt="connect"> <p>{{object.image.url}}</p> //sanity check {% endif %} </div> {% endfor %} </div> settings.py: STATIC_URL = '/static/' … -
Django ValidationError
I have a form which the user can input and I want to test for validation. The user will input a field called Project Name and I want to check if this value already exists in the database. If it does, then raise a warning. Here is my code: views.py if form.is_valid(): team_profile = get_object_or_None(Team, Team_ID=profile.team_id) return render(request,'teams/my_team.html', {'team_profile': team_profile}) else: return render(request,"teams/team_form.html", {'form':CreateTeamForm()}) models.py def validate_id_exists(value): incident = Team.objects.filter(Project_name=value) if incident: # check if any object exists raise ValidationError('This already exists not exist.') class Team(models.Model): Project_name = models.CharField(max_length=250, validators=[validate_id_exists]) So currently, if the user inputs an already existing project_name it will cause the form to be invalid. However, I do not how to show the error message on the screen. Currently, if I submit with an already existing project_name it will just return to the original form which makes sense according to what I wrote. However, I want to display the error message while staying on the form page. Any ideas? -
Why is my django template setting user to the same as object?
I'm a definite newbie to django, and have used tutorials and stack overflow a lot to design my app. My app tracks casework for users. One thing I need it to be able to do is to be logged in as one user, and look at the caseload for another user. When this page comes up, the bit that would normally say "Logout Joe Bloggs", where Joe Bloggs is the logged in user, says "Logout Fitzwilliam Darcy" where Fitzwilliam Darcy is the user I should be viewing the casework of. I don't really want to continue developing the app until I've fixed it, in case this is a symptom of an underlying problem that will cause more issues in future. I'll add what I think all the relevant bits are here, but if there's anything else needed, let me know and I'll be happy to edit. #urls.py url(r'cases/(?P<slug>\w+)',views.UserCasesView.as_view(),name='cases'), #views.py @method_decorator(login_required,name='dispatch') class UserCasesView(generic.DetailView): model = models.User template_name = 'caseworkclub/caseworker_detail.html' slug_field = 'username' #models.py class User(AbstractUser): association = models.ForeignKey('Association',null=True) def full_name(self): return("{} {}".format(self.first_name,self.last_name) def open_cases(self): return(Case.objects.filter(closed__isnull=True,caseworker=self)) The slug bit is so that the username can be in the URL according to this answer to another question It might also be worth explaining, … -
how to set sentry directory? django
I am trying to set up sentry. there is this piece of code that I am putting into my settings.py which contains using git (I am still not sure why git is needed here) somehow I just can't get the git header right. I have my file structure as... I have tried something like but this only gets me as far as parent directory, I believe I need to go one more directory up in order to get where the git head is. print os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) Thanks in advance for any help. -
Undersanding Django's get_absolute_url using reverse
I'm trying to write an app that, among other things, will generate a list of dogs that are available for adoption. At the moment when I try to generate that list I get the following error: Reverse for 'dog' with arguments '()' and keyword arguments '{'dog_id': 3, 'name': 'Rex'}' not found. 1 pattern(s) tried: ['ForeverHomes/Dog/(?P<dog_id>\\d+)/(P?<name>[A-Za-z ]+)'] Which is being raise when Django tries to get the absolute url via: def get_absolute_url(self): return reverse('ForeverHomes:dog', kwargs={"dog_id": self.dog_id, "name": self.name}, current_app="ForeverHomes") The pattern that it's trying to match is the correct pattern, but what I don't understand is how my Dog object is ever meant to match to a regular expression. My Dog objects all have a dog_id and a name, if that matters. -
Django-filter 'in' filter, when left empty, defaults to [] after submitting
I'm using django-filter to build a filterable table, with the filters laid out in a form. One capability it has is finding all entries in the table whose attribute 'b' is in a list of possible values as entered by the user. However, sometimes the user doesn't need to filter in that way, and will leave that particular filter in the filtering form blank. When the user clicks 'Submit', the values entered into the form stay the same after the table updates, except for the 'in' filter box: which gets the brackets instead of staying blank. This is a problem because if the user presses 'Submit' again, the brackets are entered as a value, and no entry in the table has attribute 'b' equalling '[]', so nothing matches. How can I force this field to stay blank after the user submits the form? Here's the code: filters.py class MyFilter(django_filters.FilterSet): class Meta: model = MyModel fields = { 'a': ['icontains'], 'b': ['icontains', 'in'] } models.py @python_2_unicode_compatible class MyModel(models.Model): a = models.CharField(max_length=50) b = models.CharField(max_length=200) views.py class MyView(django_tables2.SingleTableView): filter_class = MyFilter table_class = MyTable template_name = 'app/table.html' model = MyModel def get_table_data(self): self.filter = self.filter_class(self.request.GET, queryset=super(MyView, self).get_table_data()) return self.filter.qs def get_context_data(self, **kwargs): … -
django makemigrations import error
File "E:\PhytonProgects\natarelke\users\models.py", line 6, in <module> from catalog.models import Dish File "E:\PhytonProgects\natarelke\catalog\models.py", line 5, in <module> from users.models import RegModel ImportError: cannot import name RegModel try do makemigrations but have an error if i will remove from users.models import RegModel i will give another an error File "E:\PhytonProgects\natarelke\catalog\models.py", line 115, in Review user = models.ForeignKey(RegModel, verbose_name=u'123', NameError: name 'RegModel' is not defined How i can fix it? Have it after add dish field in table class UserFavs(models.Model): user = models.ForeignKey(RegModel, verbose_name=u'Пользователь', related_name="user", null=True) dish = models.ForeignKey(Dish, verbose_name=u'Блюдо', related_name="dish") -
Django Rest dynamically choose fields to render
In my models, I have UserProfile that has a field called public_profile. The serializer for Event model (another model) is: class EventSerializer(serializers.ModelSerializer): going = UserProfSerializer(read_only=True, many=True) notGoing = UserProfSerializer(read_only=True, many=True) class Meta: model = Event fields = ('name', 'place', 'date', 'going', 'notGoing', 'slug') Where going and notGoing is a many-to-many relation in the database to UserProfile. My question is how I can select which fields to render in the UserProfSerializer depending on the profile configuration if it is public or not. For example, I want the user pk and profile picture to show but not the username. -
Django QuerySet Issue
I have a model with a column team_id that can be null. I want to check if it is null or None. team_id = Profile.objects.values_list('team_id').filter(user_id=request.user) print(team_id) if not team_id: print("none") else: print("not none") I get the following output: <QuerySet [(None,)]> not none So team_id is None but it still prints out not none. I googled and searched many times but the solution is same as mine. I also tried this: if team_id is not None: But gave me the same result...Any ideas? -
Django version of a database tirgger?
I have two tables: Cameras & Timestamp, Timestamp has a foreign key to cameraID. Both camera and timestamp have a 'State' field. Each timestamp entry has a camera and a current state. I want to update the Camera.State value when Timestamp.State for that camera is updated. In SQL I know how to do this with a database trigger. But I am not sure how to achieve this in Django -
Trouble with making endless threaded comments
Right now i'm able to render a queryset of Comments with replies (which are also Comments). However I'm unsure how to go further than this, and allow replies to replies, and so on. Here's my code: class Comment(models.Model): user = models.ForeignKey(User, blank=True, null=True) destination = models.CharField(default='1', max_length=12, blank=True) parent_id = models.IntegerField(default=0) parent_comment = models.ForeignKey('self', related_name='replies', related_query_name='replies', blank=True, null=True) comment_text = models.TextField(max_length=350, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now, blank=True) children = models.IntegerField(default=0) def __str__(self): return str(self.comment_text) my parent comment view: def user_comment(request): if request.is_ajax(): comment = CommentForm(request.POST or None) ajax_comment = request.POST.get('text') id = request.POST.get('id') comment_length = len(str(ajax_comment)) if comment.is_valid() and request.user.is_authenticated: comment = Comment.objects.create(comment_text=ajax_comment, destination=id, user=request.user) username = str(request.user) return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username, 'id': comment.id}) else: return HttpResponse() and my reply view: def comment_reply(request): if request.is_ajax(): comment = CommentForm(request.POST or None) reply_text = request.POST.get('reply_text') id = request.POST.get('id') parent_id = request.POST.get('parent_id') parent = Comment.objects.get(id=parent_id) parent.children += 1 parent.save() if comment.is_valid() and request.user.is_authenticated: comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent_id=parent_id, parent_comment=parent) username = str(request.user) return JsonResponse({'reply_text': reply_text, 'username': username}) else: return HttpResponse() ajax calls var str = window.location.href.split('?')[0]; var path = str.split("/")[4]; $('.comment_form').on('submit', function(e) { e.preventDefault(); var c = $(this).find('.comment_text').val() console.log('this:', c); $.ajax({ type: 'POST', url: '/user_comment/', data: { text: $(this).find('.comment_text').val(), … -
parameter in POST request not appearing in kwargs
I have a custom manager that creates an object from a POST request. The issue is that the 2 manytomany parameters aren't passing any info. Here is the method (in a custom manager) def create_condition(self, *args, **kwargs): print(args) for i in kwargs: print i, kwargs[i] condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], speciality=kwargs['speciality']) condition_obj.save() return condition_obj Here is the POST request POST request Here is the log () treatable True name epilepsy treatment 1 contagious False severeity 7 Internal Server Error: /conditions/new/condition/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler return func(*args, **kwargs) File "/Users/prashantcraju/medicalrecords/conditions/views.py", line 20, in create_condition serializer.save() File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 214, in save self.instance = self.create(validated_data) File "/Users/prashantcraju/medicalrecords/conditions/serializers.py", line 21, in create return Condition.new.create_condition(**attrs) File "/Users/prashantcraju/medicalrecords/conditions/managers.py", line … -
How can i change primary key id in django somethink like uuid?
Yes, simple question. Django is using primary key which is 1,2,3,4,5,6 However, I want more securing in my server and I want to do more complicated like `2Y4e1a7 How can I do this ? -
Sphinx Note Block in a list under a code block?
I've got a problem. If I want to put a note block in a list under a code block, it gets included in the code block. If I unindent it, the listing number restart after the note. So basically, what I need is: Fixed list example ------------------ #. First do spam #. Then do ``eggs``:: some_code_stuff() .. note:: Nobody expects the Spanish Inquisistion #. Then do spam and ``eggs``. The List should continue with 3 after the note block. But currently, the ..note block is just displayed, as if it was code (due to the code block before). Any ideas? A bit related to: Sphinx: Resume list numbering after a note section -
Django - an equality check in annotate-clause
In my Django 1.9 project I am trying to output something like this: return MyModel.objects.values(...).\ annotate(flg = ExpressionWrapper(F('rgt') - F('lft') > 0, output_field = BooleanField())) This yields AttributeError: 'bool' object has no attribute 'resolve_expression' error. I try to rewrite it using Case-when syntax: return MyModel.objects.values(...)\ .annotate(flg = Case(When(F('rgt') - F('lft') > 0, then = True, output_field = BooleanField()))) This time, I end up with TypeError: __init__() takes either a Q object or lookups as keyword arguments error. I am lost. Any ideas ? -
Unkown IntegrityError in Django
So I have this small project to create my bills through Django and Latex which worked flawlessly until today. Now when I try to add another costumer, Django throws duplicate key value violates unique constraint "kunden_kundearbeitsamt_pkey" DETAIL: Key (id)=(4) already exists. These are the model definitions in question: class Kunde(models.Model): name = models.CharField('Name', max_length = 200) vorname = models.CharField('Vorname', max_length = 200) geburtsdatum = models.DateField('Geburtsdatum', max_length = 200) untersuchungsdatum = models.DateField('Untersuchungsdatum', max_length = 200) class Meta: abstract = True class KundeArbeitsamt(Kunde): kundennummer = models.CharField('Kundennummer', max_length = 100) bglnummer = models.CharField('BGL-Nummer', max_length = 100) empfaenger = models.ForeignKey('rechnungen.NumberToEmpfaenger', blank = True, null = True) class Meta: verbose_name = "Proband Arbeitsamt" verbose_name_plural = "Proband Arbeitsamt" def __str__(self): return '{}, {}'.format(self.name, self.vorname) I swear, I did not make any migrations or other changes to the database whatsoever. What is causing this error and how to fix it?