Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError when calling CreateView via AJAX
Django 1.10 PostgreSQL 9.5.4 Two models (Frame and FrameDate), one-to-many relationship. When creating a submodel (the one which is for many), I get an IntegrityError. Then I dropped the database and created it anew. So, debugging information shown below is for the first Frame and FrameDate objects in the database. This all is supposed to work via ajax. By the way, if I address to FrameDateCreate from the browser (that is without ajax), it works correctly, no IntegrityErrors. The problem: when addressing FrameDateCreate via ajax I get this: IntegrityError at /frame/1/frame_date_create/ duplicate key value violates unique constraint "frame_date_framedate_frame_id_c4d83903_uniq" DETAIL: Key (frame_id, date)=(1, 2015-01-01) already exists. What Django clarifies in its debugging traceback: return self.cursor.execute(sql, params) params (datetime.date(2015, 1, 1), 'd', 1) self <django.db.backends.utils.CursorDebugWrapper object at 0x7f65d8057f28> sql ('INSERT INTO "frame_date_framedate" ("date", "precision", "frame_id") VALUES ' '(%s, %s, %s) RETURNING "frame_date_framedate"."id"') six.reraise(dj_exc_type, dj_exc_value, traceback) db_exc_type <class 'psycopg2.IntegrityError'> dj_exc_type <class 'django.db.utils.IntegrityError'> dj_exc_value IntegrityError('duplicate key value violates unique constraint "frame_date_framedate_frame_id_c4d83903_uniq"\nDETAIL: Key (frame_id, date)=(1, 2015-01-01) already exists.\n',) exc_type <class 'psycopg2.IntegrityError'> exc_value IntegrityError('duplicate key value violates unique constraint "frame_date_framedate_frame_id_c4d83903_uniq"\nDETAIL: Key (frame_id, date)=(1, 2015-01-01) already exists.\n',) self <django.db.utils.DatabaseErrorWrapper object at 0x7f65d8057048> traceback <traceback object at 0x7f65d808d388> The object itself is created, of course. Well, Django seems … -
Cannot resolve keyword 'name' into field. Choices are: client, client_id, delivered, id, kassa, no_boxes, notes, pub_date
Relevant parts of views.py and models.py are shown below. When I try to register a new order with potentially a new client I get the error shown in the title. I've tried to delete the line new_order = Order(client = client_used, kassa = cd['kassa'], no_boxes = cd['no_boxes'], pub_date = timezone.now(), notes = cd['notes']) but that didn't solve the problem. I use Django version 1.10 and Python 2.7.10. Thanks in advance. Views.py def addclient(request): if request.method == 'POST': form = ClientForm(request.POST) if form.is_valid(): cd = form.cleaned_data if Order.objects.filter(name = cd['name']).exists(): client_used = Order.objects.get(name = cd['name']) else: client_used = Client(name = cd['name'], address = cd['address'], city = cd['city'], date_created=timezone.now()) client_used.save() new_order = Order(client = client_used, kassa = cd['kassa'], no_boxes = cd['no_boxes'], pub_date = timezone.now(), notes = cd['notes']) new_order.save() # redirect to a new URL: return index(request) # if a GET (or any other method) we'll create a blank form else: form = ClientForm() return render(request, 'clients/addclient.html', {'form': form}) Models.py class Client(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=200) date_created = models.DateTimeField('date created') def __str__(self): return self.name class Order(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) kassa = models.CharField(max_length=200) no_boxes = models.IntegerField(default=0) pub_date = models.DateTimeField('date published') delivered = models.NullBooleanField(default=False) notes = models.CharField(max_length=200) def __str__(self): … -
How to pip install a celery task module
I have a django REST API setup on one machine (currently in test on local machine but will be on a web server eventually). Let's call this machine "client". I also have a computing server to run CPU-intensive tasks that requires a long execution time. Let's call this machine "run-server". "run-server" runs a celery worker connected to a local rabbitmq server. The worker currently is in a git module with this structure: proj/ client.py cmd.sh requirements.txt tasks.py The whole thing runs in a virtualenv for what it's worth. The cmd.sh basically executes celery multi start workername -A tasks -l info on "run-server". The client.py is a cli script that can submit a tasks to the "run-server" manually from the shell. I want to run the equivalent of the client script from a django setup without having to copy the tasks.py and client.py code in the django repository. Ideally I would pip install proj from the django code and import proj to use it just like the client script does. How can I package proj to achieve that? I am used to package my own python module with a structure roughly looking like: proj/ bin/ proj proj/ __init__.py __main__.py script.py setup.py … -
i want to pass values in field using updateview django i tried to set the initial values but nothing happen
class SongUpdate(UpdateView): model = Songs form_class = SongsForm template_name = 'music/song_form.html' def get_initial(self): return {'album': self.object.album, 'song_title': self.object.album, 'file_type': self.object.file_type, 'is_favorite': self.object.is_favorite, 'scr': self.object.scr} class SongsForm(forms.ModelForm): class Meta: model = Songs fields = [ 'album', 'song_title', 'file_type', 'is_favorite', 'scr'] -
Translating email templates in Django
I have an HTML template which I send through email using a Django installation. I'm trying to translate the content of the template (I've loaded i18n and all strings are in po files), but I keep getting the email rendered in English. I have the following code: htmly = get_template(self.html_content) self.values_dict['LANGUAGE_CODE'] = 'es' d = Context(self.values_dict) html_content = htmly.render(d) process_mail.delay(subject=self.subject, message=self.message, from_email=self.from_email, recipient_list=self.recipient_list, html_content=html_content, html_type=self.html_type, attaches=self.attaches, mass=mass) For debugging reasons, I've also put this on the template: {% get_language_info for LANGUAGE_CODE as lang %} Language code: {{ lang.code }}<br /> Name of language: {{ lang.name_local }}<br /> Name in English: {{ lang.name }}<br /> Bi-directional: {{ lang.bidi }} Name in the active language: {{ lang.name_translated }} Which outputs Language code: es Name of language: español Name in English: Spanish Bi-directional: False Name in the active language: Do you know what am I doing wrong? Thanks! -
How to get username part from site.com/username/gallery in case of ArchiveIndexView?
Currenly I can get a gallery of currently logged in user via any urls as site.com/user/gallery site.com/user123/gallery site.com/312any-thing/gallery This is not what I want. What I want is to check first, if user exists, and then provide required gallery via ArchiveIndexView. How can I get the username part of site.com/username/gallery in ArchiveIndexView class in order to implement user = get_object_or_404(UserProfile, slug=user.slug) ? # project urls urlpatterns = [ url(r'^(?P<slug>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')), ] # app.urls urlpatterns = [ url(r'^$', views.ProfileDetailView.as_view(), name='profiles_home'), url(r'^gallery/$', views.ProfileGalleryArchiveIndexView.as_view(), name='profiles_gallery'), ] # app.views class ProfileGalleryDateView(object): date_field = 'date_added' allow_empty = True class ProfileGalleryArchiveIndexView(ProfileGalleryDateView, ArchiveIndexView): def get_queryset(self): user = self.request.user # here I want to get username from url user = get_object_or_404(UserProfile, slug=user.slug) return Gallery.objects.filter(galleryextended__user=user).is_public() I tried to get username from url using: def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) user = get_object_or_404(UserProfile, pk=kwargs['object'].pk) but get_queryset executes earlier than get_context_data. -
What is the difference between request.GET['q'] ,request.GET('q'),and request.GET('q',)
What is the difference between request.GET['q'] ,request.GET('q'),and request.GET('q',).Thanks def search(request): if 'q' in request.GET and request.GET['q']: q=request.GET['q'] books=Book.objects.filter(title__icontains=q) return render(request,'search_results.html',{'book':books,'query':q}) else: return HttpResponse('please submit a search term') -
Json response data doesn't append to div
I dont understand what is the problem with the success function as the ajax call works fine and the data is processed in the view, but in the success function, data doesn't get appended to the div. My jquery $(document).ready(function() { $('#other').click(function() { var filename = "{{filename}}"; var count = $("#count").val(); $.ajax({ type: 'POST', url: '/increment_page/', data: {'name':filename,'count':count,'csrfmiddlewaretoken': '{{ csrf_token }}',}, dataType: 'jsonp', success: function(data) { $( "#show" ).html(data.result); } }); }); }); Template <div id="filename">{{filename}}</div> <input type="text" id ="count" value='1'> <button id="other">Click </button> <div id="show"> {{result|first|slice:"1:"}} </div> Views.py def increment_page(request): #If the AJAX request if request.is_ajax() and request.POST: try: #Get the filename name = request.POST['name'] pdf = pyPdf.PdfFileReader(open(name, "rb")) result=[] #Extract the file contents for page in pdf.pages: result.append(page.extractText()) result = [x for x in result if x != ''] #Get the count count = int(request.POST['count']) #Increment the count #Get the list item at the count(position)p result=result[count] my_dict={} my_dict={'result':result,'count':count} #print(my_dict) data =json.dumps(my_dict) return HttpResponse(data,content_type='application/json') except: e = sys.exc_info() return HttpResponse(e) else: raise Http404 #return render(request,'view2.html',{'my_dict':my_dict,'result':result}) -
Django form Datetime field valid error after add django.middleware.locale.LocaleMiddleware'
I use django version 1.10, When a add LocaleMiddleware into settings.py, form valid error Here is my model and form class User(AbstractUser): ... is_first_login = models.BooleanField(default=False) date_expired = models.DateTimeField(default=date_expired_default, blank=True, null=True, verbose_name='Date expired') created_by = models.CharField(max_length=30, default='') class UserAddForm(ModelForm): class Meta: model = User fields = [ 'username', 'name', 'email', 'groups', 'wechat', 'phone', 'enable_otp', 'role', 'date_expired', 'comment', ] help_texts = { 'username': '* required', 'email': '* required', } 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.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django REST Framework - how to get all posts or only user's posts
everyone! models.py: http://pastebin.com/j50AdayS serializers.py: http://pastebin.com/1JZHUYRS views.py: http://pastebin.com/AH9U6fmG url.py: from .views import Register, UserList, UserDetail, PostList, PostDetail from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^register/$', Register.as_view()), url(r'^login/', obtain_jwt_token), url(r'^users/$', UserList.as_view(), name='user-list'), url(r'^users/(?P<pk>[0-9]+)/$', UserDetail.as_view(), name='user-detail'), url(r'^posts/$', PostList.as_view(), name='post-list'), url(r'^posts/(?P<pk>[0-9]+)/$', PostDetail.as_view(), name='post-detail'), ] When I do request - http GET 127.0.0.1:8000/api/posts/ "Authorization: JWT blabla" - I get only the posts that belong to the user whose token I use in request. But I need one more option - to get the posts of all users (via token) as well. Please, help, how can I do this? Thanks!!! -
Django archive via crontab in production
I'm having trouble getting crontab to execute a site backup, using django-archive. crontab file: 0 5 * * * python ~/SBGBook/gbsite/manage.py archive Error: Traceback (most recent call last): File "/home/jgates/SBGBook/gbsite/manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available $ The python manage.py archive command works great if I'm in the gbsite/ directory, but there's some sort of path issue here, I'm guessing. This is all running in a venv on a production server. -
request.user.is_authenticated always returns false
after logging in the user and checking whether request.user isauthenticated in other activity in android. the value is always false. the following code is used for login a user from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view from django.contrib.auth.models import User from django.contrib.auth import authenticate,logout,login @api_view(['POST']) def userRegister(request): user=User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password']) return Response({'ok':'True'},status=status.HTTP_201_CREATED) @api_view(['POST']) def userLogin(request): user=authenticate( username=request.POST['username'], password=request.POST['password'] ) if user is not None: login(request,user) return Response({'ok':'True'},status=status.HTTP_200_OK) else: return Response({'ok':'False'},status=status.HTTP_401_UNAUTHORIZED) the following code is used to check whether the user is authenticated or not from rest_framework.response import Response from rest_framework.decorators import api_view from . import models from . import serializers from django.contrib.auth.models import User from rest_framework import status @api_view(['GET']) def HomeView(request): if request.user.is_authenticated: return Response(data={"ok":'true'}) else: return Response(data={"ok":"false"}) -
how to confirm that provided email address is correct or not?
well, i am creating a website in django and i am using django-registration-redux for registration in which after registration activation code is sent to user's email address but if the email is wrong website still works but it gives me a error on gmail that email address does not exists. i want that if user enter wrong email address then it gives error "email doesn't exists". i have viewed similar question but that does bot works for me. is there any way i can check the email exists or not? -
Django forms.form header field
I want to have a field type in forms.form that just takes in the text of a header to be displayed so the HTML would be something like: This is header text for this section Question Question Question Another header Question Question The idea is I'm declaring all the questions in the form on the fly using a model just for question pages, I need a header for some sections just to say what the sections are about. The inserting the questions on the fly is all working well so far it's just I need the last bit of display code to make it functional for what I need. -
How to design URL to get the data in the view using request.query_params.get
How to design URL to get the data in the view using request.query_params.get in Django application. Here is my view: class BattleListByYear(generics.ListAPIView): serializer_class = BattleSerializer def get_queryset(self): queryset = Battles.objects.all() year = self.request.query_params.get('year',None) if year is not None: queryset = queryset.filter(year__exact=year) return queryset -
Converting GET request parameter to int ... if it is numeric
lets say i'm showing some data to user , i want user to be able to perform some sort of filtering on that data using a GET form so i have something like this code = request.GET.get('code') condition = {} if( code is not None and int(code) > 0 ): condition['code'] = int(code) Somemodel.objects.filter(**condition) but this works only if i code contains a number otherwise i get this error invalid literal for int() with base 10: '' so what is the pythonic way to handle this problem ? should i use try/except block? i perfer to handle this in the same if statement considering i might add other filters -
Hosting static website with Django
I have Django app running live on AWS at, www.domain.com/admin. It doesn't posses any html pages, we only make use of Django-Admin. Now I have to host a website at www.domain.com. I have my website package in this form, site |-sass |-js |-img |-fonts |-css |-index.html I copy-pasted my site folder inside my Django app at my_django_app/templates/ Also, added this : url(r'^$', TemplateView.as_view(template_name='site/index.html')), inside my_django_app/my_django_app/urls.py. And, updated my settings.py with, STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'templates/site'), ] Now when I runserver and go to www.domain.com, it loads my html file without CSS, JS and Images. Please suggest me what I am doing wrong. I am a beginner to python and also never hosted a website ever before. -
database backup is not working with nginx
In my project, I am using postgresql with django. I am trying to backup my database using the following code. def metadatabackup(request): """ This view is for database metadata backup. Only super admin can do the job :return: """ if request.user.is_superuser: database_name = local_settings.DATABASES['default']['NAME'] database_user = local_settings.DATABASES['default']['USER'] database_password = local_settings.DATABASES['default']['PASSWORD'] tempdir = tempfile.mkdtemp() sudo_pass = local_settings.SUDO_PASSWORD command_string = 'echo ' + sudo_pass + ' | sudo -S -u postgres -i pg_dump -c -Fc ' + database_name +' > ' + tempdir + '/metadata.backup' os.system(command_string) file_path = tempdir + '/metadata.backup' fsock = open(file_path,"rb") response = HttpResponse(fsock, content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=metadata.backup' return response else: raise Http404("You dont have permission") My code is working fine if I run my project using python mange.py runserver. But if my request go through nginx then my backup file contains 0 Bytes. Is there any configuration for nginx ?? Please help. -
Name duplicates previous WSGI daemon definition
I'm changing the domain name of a site. For a period I want the old domain name and the new domain name to point to the site. I'm running a Python Django site. My original Apache2 conf works fine and the basis is: <VirtualHost *:80> ServerAdmin name@gmail.com ServerName originalsite.co.uk ServerAlias www.originalsite.co.uk DocumentRoot /var/www/originalsite WSGIDaemonProcess originalsite python-path=/var/www/originalsite:/var/www/originalsite/env/lib/python2.7/site-packages WSGIProcessGroup originalsite WSGIScriptAlias / /var/www/originalsite/originalsite/wsgi.py ... </VirtualHost> I set up a new conf file with only the following changes: ServerName newsite.co.uk ServerAlias www.newsite.co.uk And I'm getting the following error: Name duplicates previous WSGI daemon definition. How do I fix this? Thanks for your help -
django ORM : current month returns None while today and current week return value
im trying to sum my user transaction for today / this week / and this month today = datetime.date.today() start_week = today - datetime.timedelta(today.weekday()) end_week = start_week + datetime.timedelta(7) account_stats = { 'today' : Transactions.objects.filter(account_id = account.id , date__gt=today ).aggregate(Sum('amount')) , 'week' : Transactions.objects.filter(account_id = account.id , date__range=[start_week , end_week] ).aggregate(Sum('amount')) , 'month' : Transactions.objects.filter(account_id = account.id , date__year=today.year, date__month=today.month).aggregate(Sum('amount')) } print('*******************************************************') print(today.year) print(today.month) print(account_stats) here is the output 2016 9 { 'week': {'amount__sum': 3921}, 'today': {'amount__sum': 1000}, 'month': {'amount__sum': None}} here is an actuall date from database 2016-09-04 22:06:06.000000 here is date fild in my model date = models.DateTimeField(auto_now_add=True , editable=False) can it be becuz there is no leading zero in the today.month ? -
Pass current valu(e(instance) in the udpate form
I have an api for updating the object. But update form shows empty field. How can i show form filled with current value? If i want to show current value filled in just django, i would do formname(instance=object). How can i do similar in DRF when using RetrieveAPIView. class RestaurantUpdateAPI(RetrieveAPIView): queryset = Restaurant.objects.all() serializer_class = RestaurantCreateUpdateSerializer def perform_update(self, serializer): print('serializer',serializer) instance = serializer.save() # send_email_confirmation(user=self.request.user, modified=instance) This code gives me empty form. i want the name field should have name of restaurant, city should have city name and so on. How can this be done in DRF RetrieveAPIView? -
filter vs get in Django ORM, when there's only 1 object available for retrieval
I have a Django application. In terms of ORM/query/DB performance, are the following ways of retrieving an object equivalent (imagine there was just a single Car object for owner_id = pk in the table currently): Car.objects.get(owner_id=pk) Car.objects.filter(owner_id=pk).latest('id') owner is a foreign key relationship. -
TypeError: login() takes 1 positional argument but 2 were given
i have written a login view using buid in auth ,django auth.login() gives above error my code with error code o 500 from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view from django.contrib.auth.models import User from django.contrib.auth import authenticate,logout,login @api_view(['POST']) def register(request): user=User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password']) return Response({'ok':'True'},status=status.HTTP_201_CREATED) @api_view(['POST']) def login(request): user=authenticate( username=request.POST['username'], password=request.POST['password'] ) if user is not None: login(request,user) return Response({'ok':'True'},status=status.HTTP_200_OK) else: return Response({'ok':'False'},status=status.HTTP_401_UNAUTHORIZED) -
Django issue with validating and calculating a manytomany field
I have a model with a manytomany field class Participation(models.Model): price = models.DecimalField(max_digits=4, decimal_places=2, default=0) selected_event_services = models.ManyToManyField(EventService, blank=True) My purpose is 1) validate the selected_event_services and if a service is not ok then raise a ValidationError 2) store price in db based on selected services. I dont want to use @property(dont want to dynamically calculate price) or signals(bad practice). I override save method def save(self, *args, **kwargs): super(Participation, self).save(*args, **kwargs) par = Participation.objects.get(pk=self.pk) print par.selected_event_services.count(), self.selected_event_services.count() print self.selected_event_services.aggregate(Sum('extra_price'))['extra_price__sum'] but both variables (par and self.selected_event_services) refered to the previous stores services and not the services that just the user inserted. Thanx -
Sending data from html to database
The following partial code is a mix of HTML and python. Where a products' values (item_name, description, item_price) of the table products from my database are laid out on HTML and has a "add to cart" input button next to each item. {% for product in products %} <li> <b>Name/Model:</b> {{ product['item_name'] }}<br> <b>Description:</b> {{ product['description'] }}<br> <b>Price: </b> {{ product['item_price'] }}$ <input type="submit" value="Add to cart"/> </li> {% endfor %} When add to cart is pressed, is there a way to send the information of the product next to that button to my other table called item_cart? I'm very very new to this kind of mixed language projects, if you need extra code to help you help solve my problem ask in the comments and i will share the part of code you need.