Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
REST Framework authentication tokens changed / deleted after Django 1.9 -> 2.1 and rest framework 3.6.3 -> 3.8.2 update
We have noticed, that at least some of our authentication tokens have changed (or been invalidated) since we updated to Django 2.1 Does anyone have any Ideas what could have caused this? While using a refresh token etc. would be good, I thought these tokens to be permanent. -
django bulk create with many=True, need save foreignkey from a different field in foreign table?
#Models class User(models.Model): email = models.EmailField() class Session(models.Model): user = models.ForeignKey(User) name = models.TextField() class SessionSerializer: fields=['name', 'email'] I need to create multiple objects with session serializer but how to get the user by using the email that is passed? -
Django: delete auxiliary annotation from queryset
I am building a complicated queryset over a complicated datamodel. The queryset must return a selection of model objects A with an annotation ann. For computing ann, I need an auxiliary annotation aux, but no aux is allowed to exist in the final results of the queryset. qs = A.objects.filter(...) # complicated qs = qs.annotate(aux=...) # complicated qs = qs.annotate(ann=Case( When(condition=Q(aux=0), then Value('some')), When(condition=Q(aux_gt=0), then Value('other')))) How to return qs with ann but without aux? (Alternatively: If aux is a count and ann discriminates zero and non-zero aux, is there a better way to approach the whole problem?) -
PostgreSQL; connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5433"?
I'm trying to create a project using cookiecutter Django but when I try to do something related to PostgreSQL, always this error happens and I cannot do anything. I'm using WSL.(Ubuntu on Windows) createuser: could not connect to database postgres: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5433"? First of all why is this number 5433 not 5432? How can I change this? Second what is the cause of this error and how can I fix this? -
add field value to datefield in django
Parent Model: id = auto_generated add_me = IntegerField() Child Model: id = ForeignKey(Parent) my_date= DateTime(auto_now_add=True) and, today = django.util.timezone.now() time = today - timedelta(days=10) now I want to retieve records as: child.objects.filter(my_date__lte= time + (timedelta(days=1)*F('id__add_me'))) Everthing works fine except: (timedelta(days=1)*F('id__add_me')) I am using MYSQL: I get: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; Query Generated is like: SELECT* FROM `child INNER JOIN `parent` ON (`child`.`id` = `parent`.`id`) WHERE ( `child`.`my_date` <= ((2018-07-30 09:11:18.670900+00:00 + (INTERVAL '86400.000000' SECOND_MICROSECOND * `parent`.`add_me`)))) As you can see * (multiplication) is with INTERVAL. I hard coded query putting the parent.add_me inside the INTERVAL and got it right, how can I do so via Django? i.e. DATE_ADD in django I want to reduce days from a datetime field, where days are stored in master table field. -
Log Stacktrace of Python in PostgreSQL trigger
I try to find a not reproducible bug which happens from time to time on our development server. Some value in the DB gets changed in a way which I don't want it to. I could write a PostgreSQL trigger which fires if this bug happens. Raising a Exception in the PostgreSQL trigger would be a solution. I would see the Python traceback which executes the unwanted SQL statement. But in this case I don't want to stop the processing of the request. Is there a way to log the Python/Django traceback from within a PostgreSQL trigger? I am using Python, Django, PostgreSQL, Linux. Please ask if you need further information. -
Django FOREIGN KEY constraint failed
My app is a shopping cart. I have a function in views.py that is triggered when someone adds an item to the cart. The function checks if the user has an active order (one that is in the cart but hasn't been paid for). But the code fails at `user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False) @login_required() def add_to_cart(request, **kwargs): #get the user profile user_profile = get_object_or_404(UserProfile, user=request.user) #filter products by id producto = Producto.objects.filter(id=kwargs.get("pk", "")).first() #create OrderItem, of the selected product order_item, status = OrderItem.objects.get_or_create(producto=producto) if status == False: #adds one to the order_item order_item.quantity += 1 order_item.save() print(order_item.quantity) #create order associated with the user user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False) user_order.items.add(order_item) #print(user_order.items.all()) #queries the items #print(user_order) #date is not beign added # generate a reference code user_order.ref_code =random.randint(0,100000) user_order.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Relevant models: class Order(models.Model): fecha_reparto = models.OneToOneField(DiasDeReparto, on_delete=models.CASCADE, default= 1) order_nodo = models.OneToOneField(Nodo, on_delete=models.CASCADE, default= 1) ref_code = models.CharField(max_length=15) owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(null=True) def get_cart_items(self): return self.items.all() def get_cart_total(self): return sum([item.producto.precio * item.quantity for item in self.items.all()]) def __str__(self): return self.ref_code class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class OrderItem(models.Model): producto = models.OneToOneField(Producto, on_delete=models.SET_NULL, null = True) quantity = models.IntegerField(default=1) is_ordered = β¦ -
how to write this code in class based views
How can I write the following code in class based views using updateview @login_required(login_url='Mel/login.html') def change_password(request): if request.method == 'POST': form = SetPasswordForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('Mel:index') else: messages.error(request, 'Please correct the error below.') else: form = SetPasswordForm(request.user) return render(request, 'Mel/change_password.html', { 'form': form }) -
How can i give django formset instance
How can i give formset instance in django formset.I created one question with 4 choices.Here choices are choiceformset.Now I want to open the created question form, then how can i pass the instance for the choice formset. choice_instance=Choice.objects.filter(question=question_instance) choice_formset=ChoiceFormSet(prefix='choice') -
Displaying all the posts of user in Django
I want to get all posts that a user send. For example user: admin, it will show admin's posts. I write some code, but probably I made a mistake and I got an error. The error that I get: AttributeError at /index_page/ 'WSGIRequest' object has no attribute 'models' Here is my code: views.py def index_page(request): logged_in_user = request.models.author logged_in_user_posts = Post.objects.filter(author=user) return render(request, 'blog/post_list.html', {'posts': logged_in_user_posts}) models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title post_list.html <div> {% for post in posts %} Username: {{ post.author.username }} Post: {{ post.text }} <br> {% endfor %} Where is my mistake? -
Django | Dynamic textfield show depends on selected checkbox
I want to show specific textfield next to checkbox, but my id's and values of checkbox is dynamic from table fields. If i click checkbox "id" i want to show "id" textfield. How it looks like My template <legend>Choose columns to show:</legend> {% for dict in content %} {% if forloop.first %} {% for key, value in dict.items %} <div style="float:left"> <input type="checkbox" id="{{ key }}" name="column" value="{{ key }}"/> <label for="{{ key }}">{{ key }}</label> </div> <div style="margin-left:200px"> <span class="show_text"> <input type="text" name="contains" value="{{ key }}" placeholder="{{ key }}"/> <br/> </span> </div> <br/> {% endfor %} {% endif %} {% endfor %} My JS $(function () { $('input[name="contains"]').hide(); $('input[name="column"]').on('click', function () { if ($(this).is(':checked')) { //alert($(this).val()) $('input[name="contains"]').fadeIn() } else { $('input[name="contains"]').fadeOut() } }) }) My code showing all of the textfields, but i dont know how to show specific one. -
How to build a form who contains items of a collection
I have 2 models: a wishlist model and a wish model. A wishlist is made of n wish (wish have a reference to his wishlist). I would like update a wishlist with a form. Here is the form i'd like to have: input:text wishlist.name for wish in wishlist: input:text wish.name input:number wish.price I'm new to django and dont know how to build a form that handle two models. # models.py class WishList(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_date = models.DateTimeField('date of creation') class Wish(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=24, decimal_places=2) description = models.TextField(max_length=200) wishlist = models.ForeignKey(WishList, on_delete=models.CASCADE) -
|_ in django template tag
I work as content manager and have access to CMS of a website. It is built with Django. In some templates objects are taken as {{object_name.object_atribute|_}}. I cannot understand what |_ do -
Convert Function Based View to Class Based View
I have a Django 2.1 views.py that I wanted to convert to Class Based View, I am NOT Django advanced user, and I know that I did translate the Functions the wrong way. The code was ment to serve a Bootstrap Modal Ajax form, and don't ask me to go see some solution already built out there, I tried everything, even the ones that worked fine in standalone, they are not compatible/conflict with my template (Maybe jquery or ..). I did convert List View and so far Create View, but I keep getting this Error : UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " Here's my views.py that I want to convert to CBV : from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string from .models import Book from .forms import BookForm from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView #The Old function List view #def book_list(request): # books = Book.objects.all() # return render(request, 'books/book_list.html', {'books': books}) #The New Class List view class Book_list(ListView): β¦ -
Can't understand the Regex in django URls
So the urls.py in django project contains this url: url(pgettext_lazy('postman_url', r'^inbox/(?:(?P<option>m)/)?$'), InboxView.as_view(), name='inbox'), What does it mean? when i type 127.0.0.1:8000/messages/inbox, the page is blank -
CookieCutter Django; cannot create db
I'm kind of beginner and I am trying to use cookiecutter Django now. But I have trouble with creating db. When I try to create db, this error happens createdb: could not connect to database template1: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5433"? How can I create db? I already installed PostgreSQL into my computer. ANd I'm using WSL. -
How to pause program and display Django message.error before form.save?
I would like to know how to display Django message.error before form.save, , I don't know whether I put them at wrong place or anything else reason, I can definitely get the right value about for loop and if else, but if a user's work_times >= 8 hours, page didn't display that error message, and project can save like before, but I did add for loop and if else!! The partial code of views.py is like this: class ProjectCreateView(CreateView): model = Project form_class = ProjectForm def form_valid(self, form): request = self.request for u in user_project: user_times = int(sum(t['learn_times'] for t in times)) if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8: messages.error(self.request, u.username + "'s learn_times is more than 8 hours, please check!") else: pass project = form.save(commit=False) project.save() form.save_m2m() Thanks so much for any advice. -
django TemplateDoesNotExist error but only one page occurs this error
I write this project locally and put it to my server today but only one page will get a TemplateDoesNotExist error everything works perfectly when i run it locally this is my views.py class RegisterView(View): def get(self, request): register_form = RegisterForm() return render(request, 'Register.html', { 'register_form': register_form }) this is my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] only this register.html django can't find, all the pages are in the same directory I am using django==1.11.14 and python2.7 -
Import Error in django view?
THis is my project directory βββ feed β βββ admin.py β βββ apps.py β βββ __init__.py β βββ __init__.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0002_auto_20180722_1431.py β β β βββ models.py β βββ __pycache__ β β β βββ templates β β βββ feed β β βββ base.html β β βββ footer.html β β βββ header.html β β βββ hindustantimes.html β β βββ index.html β β βββ ndtv.html β β βββ News_Home.html β β βββ republic.html β β βββ tredns.html β βββ tests.py β βββ twitter β β βββ __init__.py β β βββ __pycache__ β β β βββ twitter_credentials.cpython-36.pyc β β βββ trends.py β β βββ tweets.py β β βββ twitter_credentials.py β βββ urls.py β βββ views.py βββ __init__.py βββ manage.py βββ os βββ pironews β βββ __init__.py β | β βββ __pycache__ β β βββ __init__.cpython-36.pyc β β βββ settings.cpython-36.pyc β β βββ urls.cpython-36.pyc β β βββ wsgi.cpython-36.pyc β βββ settings.py β | β βββ urls.py β βββ wsgi.py βββ __pycache__ I want to import the trends.py file in my views: I am doing the following in the views file from pironews.feed.twitter.trends import main def twitter_trend(request): output = main() print(output) return HttpResponse(output, content_type='text/plain') This is my β¦ -
how to implement the case scenario?
I am newbie in django and I want to implement a case scenario like a user has many form_ids and against one form_id many users are there. how to implement this. I try this class ClientForms(models.Model): user = models.ForeignKey(User,blank=False,related_name='client_assign_form',on_delete=models.CASCADE) form_id=models.ManyToManyField("self",blank=True) Thanks in advance -
How to add a field in the admin -> app which should be exclusive to the admin site only?
I'm working on leave management system where the employee requests his manager for a leave, the manager should either accept or deny it. For accepting/denying I wanted to put a column with a checkbox or a button, instead I put a boolean field. In the models.py I have added a field called "accepted", which I did not mention in my forms.py. Now how do I make it exclusive to admin site and interactive upon clicking it?? models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 15) designation = models.CharField(max_length = 15) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField() to_date = models.DateField() reporting_manager = models.CharField(max_length = 50, default = None) reason = models.CharField(max_length= 180) accepted = models.BooleanField(('status'), default=False) def __str__(self): return self.name I'm new django and stackoverflow. Please point out if I need to be more/less descriptive in asking questions. thanks. -
How to call rest api in python which is present in other system
Please provide me any example and installation process in python. Example required is: Python file should available in localhost and server file should available in other system or remote server.So when I run the python file then Api should call for return json from the server file which is present in remote system Thanks.Please help me in urgent. -
Create Model From view in django?
I want to dynamically create model in django. For Example i will get field names from user input in view.py like First Name , Last Name etc etc Now i want to know how to make model on fly with fields First Name , Last Name -
How to test some API interface everyday
I have a DRF project and the project has some API for users. How can I test these API automatically in every morning? -
Django custom authentication back-end doesn't work
I want my Django project to authenticate users with their email instead of their user name. I followed this suggestion, but it doesn't work. This is my EmailBackend from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwars): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None I have added AUTHENTICATION_BACKENDS = ['GeneralApp.utils.EmailBackend'] to settings.py and, when it is commented, I can login using user name, and when I uncomment it, I cannot login anymore. I have traced out that the code of GeneralApp.utils.EmailBackend.authenticate() is never executed.