Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django make a list of objects from queryset
i have a field in models with name answer ,This field has 4 values either a,b,c and d . I am writing a view to create a list of this answer.. I have user the code platform = get_object_or_404(Platform, user=request.user, test_key=article) b = json.loads(platform.list) ans = list(Upload.objects.filter(id__in=b).values_list('answer',flat=True)) and this gives me ans as [(u'a',), (u'b',), (u'c',), (u'b',), (u'c',), (u'b',), (u'c',)] but i want the list as [a,b,c,b,c] I am stuck with this -
How to implicitly pass user from a request to corresponding serializer?
I have a following code: class Article(models.Model): ... owner = models.ForeignKey(User, on_delete=models.CASCADE) class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id', 'title', 'content', 'owner') extra_kwargs = { 'owner': {'write_only': True}, } class ArticleList(generics.ListCreateAPIView): serializer_class = ArticleSerializer def get_queryset(self): user = self.request.user return Article.objects.filter(owner=user.id) def post(self, request, *args, **kwargs): request.data['owner'] = self.request.user.id return self.create(request, *args, **kwargs) I have to explicitly pass user from request in post method of ArticleList ApiView to satisfy ForeignKey non-empty requirement. This is fine. But I have another models with a ForeignKey to User and as a result it leads to many copy-paste lines, especially in POST and PUT methods. Does anybody knows more elegant DRY solution? -
How to get to Django server logs if server is started in Docker
Folks, I created a Django project and I started it in Docker. Therefore I don't see server logs and I need to know how POST and GET methods look like. How I can get acces to this logs? BR, Damian -
Cross-Origin Request Blocked issue using Aagular 4 and DJango
I have two applications on two machine. Backend app using DJango (example 123.431.234.123:8080) Frontend app using angular (example 123.431.234.124:4200) Now I am trying to post request from angular this.http.post<any>('http://123.431.234.123:8080/login/', { username: username, password: password }) I am getting error on browser: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://123.431.234.123:8080/login/. (Reason: CORS header âAccess-Control-Allow-Originâ missing). When I am trying with curl command on my ubuntu machine, I am able to get the response successfully. curl -d '{"username":"admin" ,"password":"carpediem"}' -H "Content-Type: application/json" http://123.431.234.123:8080/login/ I tried to follow many links and also setup my django setting.py file as link 1 link 2 and did step by step configuration as below pip install django-cors-headers Adds to installed apps INSTALLED_APPS = ( ... 'corsheaders', ... ) Add MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL=True After all changes, I am still facing the same issue. It might be duplicate question, But Please help me to solve it. I am using Mozila firefox, Do I need to do any changes in browser or any other seetings? -
How the hell to add a field on django 1.7 admin panel?
I see a list of fields in the model, but if I add one it won't appear in the admin form, where I need to add a variable to let it appear in the admin html form? code: class Test(models.Model): name = models.CharField('name', max_length=100) f1 = models.CharField('f1', max_length=100, blank=True) f2 = models.CharField('f2', max_length=100, blank=True, null=True, default=None) f3 = models.TextField("f3", blank=True, null=True, default=None) f4 = models.ManyToManyField(Genre, blank=True) f5 = models.ImageField('f5', upload_to=poster_directory_path, blank=True, null=True, default=None) f6 = models.PositiveIntegerField("f6", blank=True, null=True, default=None) f7 = models.DateField('f7', blank=True, null=True, default=None, max_length=50) f8 = models.PositiveIntegerField("f8", blank=True, null=True, default=None, unique=True) f9 = models.FloatField('f9', blank=True, null=True, default=None) f10 = models.FloatField('f10', blank=True, null=True, default=None) -
Is there a way to set DateField nullable=True in SQLAlchemy?
I want to pass empty date into the database (psycopg2.DataError) invalid input syntax for type date: "" My serializer allows it, the database doesn't allow because constraints are not configured. reg_date= Column(Date, nullable=True) -
I cannot access user_detail url
I cannot access user_detail url.I wrote urls.py like from django.conf.urls import url from . import views app_name = 'users' urlpatterns = [ url(r'^(?P<user_id>[0-9a-zA-Z]{20})/user_detail$', views.UserDataSet.get_user_detail, name='user_detail'), url(r'^', views.UserDataSet.get_users, name='get_users'), ] I can access get_users's url by http://localhost:8000/users , but when I access http://localhost:8000/users/sdc452ne3n9mtt6j5k8a/user_detail,I cannot access the page.sdc452ne3n9mtt6j5k8a's user id is ok.I tried to the url like http://localhost:8000?users/sdc452ne3n9mtt6j5k8a/user_detail,I cannot access the page too.I really cannot understand why I can't access the page.What is wrong?How can I access it? -
Django one to one field RelatedObjectDoesNotExist
I made these models: class Post(models.Model): title = models.CharField(max_length=50, blank=True, null=True) class OrderInfo(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, primary_key=True) position = models.CharField(max_length=50, blank=True, null=True) @receiver(post_save, sender=Post) def update_order_info(sender, instance, created, **kwargs): if created: OrderInfo.objects.create(post=instance) instance.orderinfo.save() In View, ... post.orderinfo.position = form.cleaned_data.get('position') ... and It returns RelatedObjectDoesNotExist Error. Post has no orderinfo. What shoud I do? (I think Django System is handling .orderinfo as a post's column.. But Why?) -
DRF: How to make field in serializer required only for object creation?
I'm using Django Rest Framework and have a following serializer (minimal example): class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id', 'brand', 'color') extra_kwargs = { 'brand': {'required': True}, } So using POST it works as expected and prevents car creation without a brand in request params. But then I want to update some Car entity in DB and modify only a color field. Using PUT (or PATCH) like this: http PUT :8000/cars/123/ color="red" There are some errors: { "brand": [ "This field is required." ] } How can I make the brand field required only for object creation but not for modifying? -
How do I push my Bitbucket repo to my DigitalOcean server?
I've created a DigitalOcean server (droplet) for my Django site, running Ubuntu 16.04 with Nginx & Gunicorn. I've got my Django project in a Bitbucket repo - how do I push this to my DigitalOcean server? I've tried to search and there are many different/confusing answers and they all seem more complicated that it should be. Help appreciated. -
Django Integrity Error Not null
i am learning django and trying to practice by making my own website that will quiz me with questions that i submit in to it. I get this error and i dont know why. IntegrityError at /questions/new/ NOT NULL constraint failed: questions_question.date_created This is the relevent traceback i believe enter image description here here is my relevant code: questions/Views.py from django.shortcuts import render from django.views import generic from django.core.urlresolvers import reverse_lazy from django.contrib import messages from . import models from . import forms # Create your views here. class QuestionList(generic.ListView): model = models.Question class QuestionDetail(generic.DetailView): model = models.Question def get_queryset(self): queryset = super().get_queryset() class CreateQuestion(generic.CreateView): model = models.Question # form = QuestionForm fields = ('question', 'answer') def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeleteQuestion(generic.DeleteView): model = models.Question success_url = reverse_lazy('questions:all') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Question Deleted") return super().delete(*args, **kwargs) Here is my models.py from django.db import models from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse User = get_user_model() import misaka # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=225) intro_text = models.TextField(null=True) date_created = models.DateTimeField() date_updated = models.DateTimeField(auto_now=True, null=True) class Question(models.Model): user = models.ForeignKey(User, related_name="question", … -
Why the `/admin/` only have few models?
I use the admin account login to the /admin/: Why there are only these field I can edit? I have write tons models in my project. why do not show up? -
'Request' object is not iterable
I am trying to do simple crud demo project API's for mobile using django rest framework and getting below error Project Name : crud_demo App Name : crud_operations crud_demo/urls.py from django.conf.urls import include, url from django.urls import path urlpatterns= [ path('models/', views.model_list), path('models/<int:pk>/', views.model_detail), ] crud_operations/models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) crud_operations/serializers.py from crud_operations.models import Member from rest_framework import serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('firstname', 'lastname') crud_operations/views.py from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Member from crud_operations.serializers import MemberSerializer @api_view(['GET', 'POST']) def model_list(request): if request == 'GET': member = Member.objects.all() serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'POST': serializer = MemberSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'key': request}, status=status.HTTP_200_OK) @api_view(['GET', 'PUT', 'DELETE']) def model_detail(request, pk): try: member = Member.objects.get(pk=pk) except Member.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request == 'GET': serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'PUT': serializer = MemberSerializer(member, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': member.delete() return Response(status=status.HTTP_204_NO_CONTENT) return Response({'key': 'value'}, status=status.HTTP_200_OK) -
After login the `rest-auth`, how to return more information?
I use django-rest-auth in my Django project. After login the rest-auth/login/, how to return more information? In the rest-auth/login/, when I login the user, it returns a key. I want to also return the user's information, how can I get this? -
django migrations in postgresql fails (Even default migrations but works in sqlite and mysql)
I created a new django project and added the following database settings in setings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '5432', 'OPTIONS':{'options': '-c search_path=resttest'} } } I just ran "python manage.py migrate" But it this error django.db.utils.ProgrammingError: constraint "django_admin_log_user_id_c564eba6_fk" does not exist When is try changing the Database setting with default sqlite or to MySQL it works fine. I even tried using 'ENGINE': 'django.db.backends.postgresql' as shown in the documentation. Can someone help me out in guessing what the problem is? -
Dynamically add properties to Django model
Currently I have the following Django model class TestUser(models.Model): name = models.CharField(max_length=250) email = models.CharField(max_length=250) ... class Meta: db_table = 'temp_user' and I've the following method. def print_name(self): return self.name I want to add this method as a property to TempUser model. I know this can be done by putting the method inside TempUser class and user @property. But I want to do it dynamically. I tried this from python shell. In [10]: TempUser.print_name = property(print_name) In [11]: TempUser.print_name Out[11]: <property at 0x7efc374e7c58> In [12]: user = TempUser.objects.get(pk=1) In [13]: user.print_name Out[13]: u'Test User' But once I exit the shell, I loose the property. Is there any way to add the property permanently. -
django S3 - trim imagefield filename but not the url path
this is a followup to my question here: ImageField / FileField Django form Currently unable to trim the path to filename In my Django app, there is an imagefield uploaded to S3 After trim the imagefile path name, the image is not accessible because the url is trimmed. How can i trim the display but dont trim the path ? I manage to trim the display showing the filename like this class CustomClearableFileInput(ClearableFileInput): def get_context(self, name, value, attrs): logging.debug("%s",name) logging.debug("%s",value) value.name = path.basename(value.name) context = super().get_context(name, value, attrs) return context class CompanySettingEdit(forms.ModelForm): company_logo = forms.ImageField(widget=CustomClearableFileInput) this is the output: https://imgur.com/a/M42Mz <-- display correct https://bucketname.s3.amazonaws.com/media/certiport_logo.png <-- invalid url If I dont trim it: class CustomClearableFileInput(ClearableFileInput): def get_context(self, name, value, attrs): logging.debug("%s",name) logging.debug("%s",value) # value.name = path.basename(value.name) <-- remove this context = super().get_context(name, value, attrs) return context class CompanySettingEdit(forms.ModelForm): company_logo = forms.ImageField(widget=CustomClearableFileInput) this is the output: https://imgur.com/a/rGi8f <-- display incorrect https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png <--valid url my goal is to: display: certiport_logo.png url: https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png How can I achieve this ? -
django.core.exceptions.ImproperlyConfigured. The included URLconf does not appear to have any patterns in it
I am trying to do simple crud demo project API's for mobile using django rest framework and getting below error django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Project Name : crud_demo App Name : crud_operations crud_demo/urls.py from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns= [ url(r'^admin/', admin.site.urls), url(r'^crud_operations/', include('crud_operations.urls')), ] crud_operations/models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) crud_operations/serializers.py from crud_operations.models import Member from rest_framework import serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('firstname', 'lastname') crud_operations/urls.py from crud_operations import views urlpatterns = [ url(r'^models/$', include(views.model_list)), url(r'^models/(?P<pk>[0-9]+)$', include(views.model_detail)), ] crud_operations/views.py from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Member from crud_operations.serializers import MemberSerializer @api_view(['GET', 'POST']) def model_list(request): if request == 'GET': member = Member.objects.all() serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'POST': serializer = MemberSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'key': request}, status=status.HTTP_200_OK) @api_view(['GET', 'PUT', 'DELETE']) def model_detail(request, pk): try: member … -
How to avoid ValueError save() prohibited to prevent data loss due to unsaved related object?
I have (2) models - Recipes and RecipeIngredient, related by foreign key. The user creates a recipe (core information) and saves it, then can later CRUD associated elements (like ingredients, procedures, etc.) The Formview/modelformset is called by passing the pk of the recipe all the forms will use as a FK. After posting the view assigns the FK's pk to the appropriate field in each form. Unfortunately, I get the "save() prohibited" error, and after reading through many SO questions/comments about this error occurring, I don't see a clear answer on how to avoid/correct this. To me this seems like a central method of relating objects to each other, and there should be a way to accomplish this. If I don't assign the FK manually, it won't save without the mandatory relationship being specified. If I DO assign it, I get this save() error. The error always occurs Django attempts to save the first form of the loop. The error: save() prohibited to prevent data loss due to unsaved related object 'parent_recipe' The models: class RecipeBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) creation_date = models.DateField("Record creation date",auto_now_add=True) creation_user = models.CharField("Record creation user",max_length=150) lastupdated_date = models.DateField(auto_now=True) lastupdated_user = models.CharField(max_length=150) category = … -
Django rest serializer don't work with many to many relationship
I'm trying to create an personal project based on a simple kanban, the model task have a relationship with model board. When I try renderize it, I get the items: title and slug, but, the relationship with model board is missing, can someone help me with this error please, what I doing wrong? OBS: I know, here in stackoverflow have many posts with the same subject, but unfortunately I did not find the solution :/ here is my model code: class Board(models.Model): BACKLOG = 'Backlog' PROCESS = 'In progress' QA = 'QA' COMPLETE = 'Complete' _status = ((BACKLOG, 'Backlog'), (PROCESS, 'In progress'), (QA, 'QA'), (COMPLETE, 'Complete')) LOW = 'Low' NORMAL = 'Normal' HIGH = 'High' _priority = ((LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High')) status = models.CharField(_('Status'), max_length=20, choices=_status, default=BACKLOG, help_text='Selecione o status da task') priority = models.CharField(_('Priority'), max_length=20, choices=_priority, default=NORMAL, help_text='Selecione a prioridade da task') description = models.TextField() class Meta: verbose_name = 'Board' verbose_name_plural = 'Boards' ordering = ['priority',] def __str__(self): return "{} - {}".format(self.description, self.priority) class Task(models.Model): title = models.CharField(_('Tittle'), max_length=100, help_text='Titulo da task') slug = models.SlugField(db_index=True) board = models.ManyToManyField(Board) class Meta: verbose_name = 'Task' verbose_name_plural = 'Tasks' ordering = ['title',] def __str__(self): return "{}".format(self.title) in my serializers file … -
Is the default Permissions have API?
Is the default Permissions have API for edit? This is my urls conf(sorry about the ): I want to edit the permissions, such as its name, or others information. But you see there is no url conf for it. how can I edit it? I mean in my custom interface to edit it, there need the permissions' API. -
How to set a variable in if statement and return in function?
I want to set a variable: correct_captcha, in if statement and return it from the function to HTML, the views is as below: def list(request): correct_captcha = None if request.method == 'POST': file = request.FILES.get('file', False) ca_mode = request.POST.get('mode', 'word').lower() assert ca_mode in ['number', 'word', 'four_number'] captcha = request.POST.get('captcha') ca = Captcha(request) if ca.validate(captcha): if 'file' in request.FILES: fs = FileSystemStorage() fs.save('(' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ')' + file.name, file) filesname= str('(' + datetime.now().strftime('%Y-%m-%d-%H- %M-%S') + ')' + file.name) else: filesname = '' add_obj = enquiry(file=filesname) add_obj.save() correct_captcha = 0 return correct_captcha else: correct_captcha = 1 return correct_captcha return render(request, 'list.html', {'correct_captcha':correct_captcha}) But it did not work, how can I do to return this variable in function? -
Can't access Graphite web (error 500)
After updating the Whisper package (from 0.9.12 to 1.1.1) using pip, I'm not able to access my Graphite instance anymore (even after downgrading...) The logs say the target script can't be loaded as a Python module. Here are some informations about the system. Python version: 2.7 Carbon, Graphite web, Whisper versions: 0.9.12 I tried changing the rights of /usr/share/graphite-web/graphite.wsgi and /opt/graphite/conf/graphite.wsgi but it didn't solve the problem. My error log: [Thu Jan 18 14:53:17.260272 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] mod_wsgi (pid=16527): Target WSGI script '/usr/share/graphite-web/graphite.wsgi' cannot be loaded as Python module. [Thu Jan 18 14:53:17.260431 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] mod_wsgi (pid=16527): Exception occurred processing WSGI script '/usr/share/graphite-web/graphite.wsgi'. [Thu Jan 18 14:53:17.260470 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] Traceback (most recent call last): [Thu Jan 18 14:53:17.260507 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/share/graphite-web/graphite.wsgi", line 16, in <module> [Thu Jan 18 14:53:17.260552 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] application = get_wsgi_application() [Thu Jan 18 14:53:17.260564 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Jan 18 14:53:17.260586 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] django.setup(set_prefix=False) [Thu Jan 18 14:53:17.260597 2018] [:error] [pid 16527] [remote 203.80.55.88:18829] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup [Thu Jan 18 … -
How do I customize the Group in Django?
I write a Django project, and I use the default Groups and Permissions. When I list or retrieve the Group, the data is bellow: { "id": 2, "name": "group02", "permissions": [ 22, 23, 24 ] } I can not see the permissions name and the users belong to the Group instance. How can I optimize this to satisfy my requirement? -
How do i change the default primary key in django?
I'm new to learning django. I'm using PostgreSQL as my database. I created an app called gplus and a model I created looks something like this class Account(AbstractBaseUser): email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_of_birth = models.DateTimeField() I applied the migrations and then wanted to change the primary key field from default 'id' to 'username'. So, in the psql command line I ran the following commands ALTER TABLE gplus_account DROP CONSTRAINT gplus_account_pkey; ALTER TABLE gplus_account ADD PRIMARY KEY (username); ALTER TABLE gplus_account DROP COLUMN id; Then in the models.py, I edited the username field as username = models.CharField(max_length=50, primary_key=true) Now, when I try to apply the migrations, I get the error django.db.utils.ProgrammingError: column "id" of relation "gplus_account" does not exist It seems Django needs to know there is no 'id' field in the table anymore. How can I do that? Thanks