Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
auto login url for a specific user
I'm trying to auto login user on the link that I've created, so I'm trying to enable a specific url gateway only for that. So I have a simple login View: from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import redirect, render from django.views.generic import View from django.contrib.auth import login, authenticate import logging logger = logging.getLogger(__name__) class SpecialUserGatewayView(View): def post(self, request): token = request.POST['token'] user = authenticate(token=token) if user is not None: if user.is_specific_user: return HttpResponseRedirect('dashboard') else: return HttpResponse("This user is not Specific User!") else: return HttpResponseRedirect('/') and the url for this is url(r'^special_user/login/(?P<token>[0-9A-Za-z])/$,', SpecialGatewayView.as_view(), name="special-login") Now I'm generating token using rest framework jwt, and my login url should be something like this https://mywebpage/special_user/login/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImExQGExc3VwZXJ1c2VyLmNvbSIsImVtYWlsIjoiYTFAYTFzdXBlcnVzZXIuY29tIiwiZXhwIjoxNTI2MzE5OTk0LCJ1c2VyX2lkIjo1Miwib3JpZ19pYXQiOjE1MjYzMTY5OTR9.-pUBVjiAbRhgfuj5IFQP7Qh9KXRX4K_Tyn0nsucF1pM, The error is: Page not found (404) Request Method: GET Request URL: http://localhost:8888/special_user/login/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImExQGExc3VwZXJ1c2VyLmNvbSIsImVtYWlsIjoiYTFAYTFzdXBlcnVzZXIuY29tIiwiZXhwIjoxNTI2MzE5OTk0LCJ1c2VyX2lkIjo1Miwib3JpZ19pYXQiOjE1MjYzMTY5OTR9.-pUBVjiAbRhgfuj5IFQP7Qh9KXRX4K_Tyn0nsucF1pM/?next=/dashboard/ As you can see I'm not sending good url to my application and more, so can someone please help me and explain how can I overcome this, thanks. -
Password reset in Django on nginx server writes to log file instead of sending email
I have a Django app running on a server with uWSGI and nginx. In my local_settings.py file I have this: ############### # EMAIL SETUP # ############### EMAIL_HOST = 'smtp.privateemail.com' EMAIL_HOST_USER = 'support@mydomain.com' EMAIL_HOST_PASSWORD = 'MY EMAIL PASSWORD' EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True ######################## # OTHER EMAIL SETTINGS # ######################## ADMIN_EMAIL = "admin@mydomain.com" SUPPORT_EMAIL = "support@mydomain.com" When I fill out the /password_reset/ template with an email and submit the form, the address I enter gets no password-reset message. Nothing is logged to error.log. Here's what I see in uwsgi.log [pid: 3354|app: 0|req: 1489/2206] 73.49.35.42 () {44 vars in 948 bytes} [Mon May 14 16:59:06 2018] GET /login-register/ => generated 7480 bytes in 39 msecs (HTTP/1.1 200) 3 headers in 102 bytes (2 switches on core 0) [pid: 3355|app: 0|req: 718/2207] 73.49.35.42 () {44 vars in 994 bytes} [Mon May 14 16:59:14 2018] GET /password_reset/ => generated 3669 bytes in 38 msecs (HTTP/1.1 200) 4 headers in 256 bytes (1 switches on core 0) MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: Password reset on Default From: webmaster@localhost To: email.to.send.password.reset@gmail.com Date: Mon, 14 May 2018 16:59:16 -0000 Message-ID: <20180514165916.3354.5092@my-ubuntu-server-hostname.mydomain.com> Hello, You received this email because a request was … -
Django - Context that is always rendered
I'm writing a blog - it has top bar menu which contains Categories objects. The problem is that Every view in this blog has to return a context with Categories.objects.all(). Is there a better way to solve that problem (adding same queryset to context to every view)? My code: models.py class Category(models.Model): name = models.CharField(max_length=60) slug = models.SlugField(unique=True, blank=True, null=True) base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Blog</title> </head> <body> {% block menu %} <div id="menu"> {% for item in categories %} <a href="{% url 'category_detail' item.slug %}"> <div class="category">{{ item.name }}</div> </a> {% endfor %} </div> {% endblock %} {% block content %} <!-- I want extend only that block in every view --> {% endblock %} </body> </html> -
Django - PostgreSQL doesn't match default attribute
I have the following model at Django: class Community(models.Model): name = models.CharField(max_length=255) members = models.ManyToManyField(User, through='Membership') date_created = models.DateTimeField(auto_now_add=True) But when I check the structure of the table (using Postico for PostgreSQL) the field of date_created after applying the migrations shows no default. I have also tried with explicitly default=date.today() but it does not work. Any ideas what I am missing? Thanks, Pablo -
No such table Django Database
So I created a model for storing credentials from Gmail users. I wanted to make migrations but it says that there is no such table: django.db.utils.OperationalError: no such table: mainApp_credentialsmodel My models: from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models import json class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True,on_delete=models.CASCADE) credential = models.CharField(max_length=1000) Calling that model for checking authorization: SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' store = CredentialsModel.objects.all() creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('mainApp/client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) -
Redirection according to the user group after login
I would like to create a redirection of the user after login in function of the group. I have two groups A and B in my admin. Redirect link for group A: / add_name / Redirect link for group B: / validate_name / I have already done this in my settings.py: LOGIN_REDIRECT_URL = "validate_name". But by doing this, all the users write on the same link. What is the right way to do it? Thank you -
No module named 'oauth2client.contrib.django_orm'
I have a Django project connected to Gmail API and I need to store somehow every user's credentials in a database. I found this but pasting that code into my models makes one line red: from oauth2client.contrib.django_orm import CredentialsField -
Model change reflected in admin page but not in django form template why?
Models.py class Question(models.Model): name = models.CharField(max_length=300, unique=True) desc = HTMLField() img = models.CharField(max_length=100) topic = models.ForeignKey(Topic, related_name='question') created_by = models.ForeignKey(User, related_name='question') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name template <form method="post"> {% csrf_token %} {%include 'includes/form.html' %} <input type="submit" class="btn btn-success" value="Post Answer" /> </form> I am using tinymce for rich textarea purpose. Here i have added field "desc" as HTMLField and successfully applied migrations. I am able to see desc added in admin page but not in my template. Please point my mistake ? -
No reverse match error but the function exists?
I am trying to implement a "renew" function for a key inventory system. But when I render that page, it shows a Reversematcherror even though I mapped the correct URL and used the correct function name. Here is my template:(The url tag is on the suuuper long line all the way to the right) {% block content %} <h1>All Borrowed Keys</h1> {% if keyinstance_list %} <ul> {% for keyinst in keyinstance_list %} <li class="{% if keyinst.is_overdue %}text-danger{% endif %}"> <a href="{% url 'roomkey-detail' keyinst.roomkey.pk %}">{{keyinst.roomkey}}</a> ({{ keyinst.due_back }}) {% if user.is_staff %}- {{ keyinst.borrower }}{% endif %} {% if perms.catalog.can_mark_returned %}- <a href="{% url 'views.renew_key_user' pk=keyinst.id %}">Renew</a> {% endif %} </li> {% endfor %} </ul> {% else %} <p>There are no keys borrowed.</p> {% endif %} {% endblock %} My urls.py: `path('key/<uuid:pk>/renew/', views.renew_key_user, name='renew-key-user'),` Views.py: @permission_required('catalog.can_mark_returned') def renew_key_user(request, pk): """ View function for renewing a specific keyInstance by admin """ key_inst=get_object_or_404(KeyInstance, pk = pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewKeyForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data … -
How to get data to template with FormMixin in a posts DetailView?
I have the code below, and would like to know how to display the saved data from the form in the same view? I have the Detailview of the Post, and the form to Answer this Post in the same view, but how do I also display the data saved from this form? class PostDetailView(FormMixin, DetailView): model = Post form_class = AnswerForm template_name = 'main/postdetail.html' context_object_name = 'posts' success_url = '/' def get_success_url(self): return reverse('postdetail', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = AnswerForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): instance = form.save(commit=False) instance.created_by = self.request.user instance.post = self.object instance.save() return super(PostDetailView, self).form_valid(form) -
Adding list filter to django admin for content_type objects
Is it possible to add list filter to django admin for content type objects? I have a class Item that can be related to Merchant or to Outlet as shown below. Furthermore Outlet is related 1:n with Merchant via merchant_id. class Item(models.Model): ... # Generic FK to Merchant or Outlet content_type = models.ForeignKey(ContentType, limit_choices_to=shop_models, on_delete=models.CASCADE) object_id = gfklookupwidget.fields.GfkLookupField('content_type', null=True) content_object = GenericForeignKey('content_type', 'object_id') I would like to add a list filter to django admin that will enable filtering by Merchant so that it will show all Items related to a Merchant or merchant's outlets. I found some information about custom filters here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter. And it seems to me that it should be enough to correctly define lookups and queryset methods. I would like to know if is it possible to use existing filter (e.g. RelatedFieldListFilter) or is it needed to extend one to a custom filter? If solution already exists, can you please point me to it? -
name 'Employee' is not defined CBV ListView
urls.py from django.conf.urls import url from system import views app_name = 'project' urlpatterns = [ ... url(r'^cust/([\w-]+)/$',views.PublisherBookList.as_view()), ... ] views.py class PublisherBookList(ListView): def get_queryset(self): self.name = get_object_or_404(Customer, name=self.args[0]) return Customer.objects.filter(name=self.name) models.py class Customer(models.Model): name = models.CharField(max_length=255) I do visit http://127.0.0.1:8000/project/custo/customername/ got error name 'Customer' is not defined whats i missed here?... -
Need to provide a view / a report about change made on the model? Advice about package to use?
I need to provide a view / a report about the change made on the model? Advice about package to use? https://djangopackages.org/grids/g/model-audit/ -
Kubernetes Django Disallowed Hosts
I'm trying to deploy a Django app via Kubernetes. After creating my pod definition, LoadBalancer service, and routing DNS traffic to my LoadBalancer, I'm getting a Disallowed Hosts error. I think I need to add the name of the LoadBalancer to my allowed hosts, but how do I do that when the LoadBalancer is created when I run kubectl create -f service.yaml? pod.yaml: apiVersion: v1 kind: Pod metadata: name: test.example.com labels: app: my-pod spec: containers: - name: my-container image: my-image:1.0 ports: - name: my-port containerPort: 8000 service.yaml apiVersion: v1 kind: Service metadata: name: mgmt-service spec: ports: - port: 80 targetPort: mgmt-port protocol: TCP selector: app: mgmt_reporting type: LoadBalancer -
Django REST Framework SesstionAuthentication not working with TokenAuthentication
I'm using Django 2.0 and Django RESET Framework to write REST API for my application. I have configured following authentication methods REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } But on accessing http://127.0.0.1:3333/api/contacts/ from web browser, it is giving error as { "detail": "Authentication credentials were not provided." } while accessing from curl using Authorization header is working fine. curl -X GET 127.0.0.1:3333/api/contacts/ -H 'Authorization: Token <Token>' What I want is to allow few users (probably superadmin users) to be able to access API from Session Authentication or from web browser by logging in. -
Using HDF5 to store Pandas data frames in Django
I am very new to Django. Learning the basics by watching videos and practicing it on my own. My objective is to scrape websites using scrapers that I have written and gather the needed data, process it using pandas operations, and store using HDF5. I have separate code snippets for all these operations. Now I am unable to find resources online that demonstrate how to use HDF5 with Django. Any pointer and tips would be much appreciated. Thank you. -
How to ignore custom model manager in admin?
I override delete method (have made object non-deleteable and set active field to false) in custom QuerySet in custom ModelManager. Is there any way to ignore custom manager in admin panel so I can actually delete objects from there? -
How to allow visitors to search record by entering specific value in search box in django
I am creating a Django application where students record will be stored. Student table has the following details : Name, address, roll, no. gender. Now I want to allow the visitor to just enter the roll number and see the student details. How can I do that? I have created the basic model and views by which I can display every record. -
Trying to send a form to a view, but cant grab the correct 'post_id' that the view requires.
I have a form created in comments/forms.py from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) this form has a template in comments/comment_form.html: <h2>this is the comment form</h2> <form class="post-form" method="post" action="{% url 'comments:create' post.id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> as you can see, I am sending this form to comments:create. this is the view for handling the form: def create(request, post_id): post = get_object_or_404(Post, pk= post_id) group = post.group if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.pub_date = timezone.now() comment.save() return redirect('/groups/' + str(group.id)) else: form = CommentForm() return render(request, 'comments/comment_form.html', {'form':form}) The issue is that I'm rendering the form on the 'groups/detail.html': {% include "comments/comment_form.html" %} the problem is that this form obviously requires a post_id because the comment belongs to a post. THE ISSUE IS THAT I DONT HAVE ACCESS TO AN INDIVIDUAL POST ON THE GROUPS DETAIL PAGE, OR I AT LEAST DONT KNOW HOW TO ACCESS AN INDIVIDUAL POST. below is the group detail view: def detail(request, group_id): group = get_object_or_404(Group, pk= group_id) posts = Post.objects.filter(group__id = … -
Getting the aggregate sum of a field from the other model in Listview
I have the following two models: models.py class Model_Item(models.Model): item_name = models.CharField(max_length = 100, null = False, blank = False, unique = True) def __unicode__(self): return self.item_name class Model_ItemTransaction(models.Model): item = models.ForeignKey(Model_Item, to_field = "item_name") item_sold = models.FloatField(null = True, blank = True) def __unicode__(self): return self.item With this listview: views.py class View_Item(ListView): def get_queryset(self): queryset = Model_Item.objects.all() queryset = queryset.annotate( sum_ = Sum(When(model_itemtransaction__item_sold)) ) return queryset And my goal is to get the total value of "item_sold" for each item, and display this value on Listview. How can I make this work? I have been looking at the conditional expression and this stackoverflow post, but to no avail. -
Django _ NOT NULL constraint failed: authtoken_token.user_id
I'm trying to create tokens for my User Model that inherits from AbstractBaseUser with signals but when I try to create User errors comes up: django.db.utils.IntegrityError: NOT NULL constraint failed: authtoken_token.user_id class User(AbstractBaseUser): username = models.CharField(max_length=20, blank=True) email = models.EmailField(verbose_name='email address',blank=True, null=True, max_length=255, unique=True, default=None) phonenumber = models.CharField(validators=[phone_regex], max_length=17, null=True, unique=True) first_token = models.ForeignKey(FirstToken, on_delete=models.SET_NULL, null=True, related_name='first_token', blank=True) active = models.BooleanField(default=True) # authtoken = models.OneToOneField(Token, related_name='token', on_delete=models.CASCADE) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'phonenumber' REQUIRED_FIELDS = [] def save(self, *args, **kwargs): token = FirstToken.objects.create() self.first_token = token if self.email is not None and self.email.strip() =="": self.email = None super(User, self).save(*args, **kwargs) and this is my signal : @receiver(post_save, sender=AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): print(instance) if created: Token.objects.create(pk=instance.id) in settings.py i changed auth_user_model : AUTH_USER_MODEL = 'blog.User' serializers.py class UserCreateSerializer(serializers.ModelSerializer): """User django serilization""" class Meta: model = User fields = ['phonenumber','id','email', 'username', ] def create(self, validate_data): user = User(**validate_data) user.save() return user -
How to set user_id field using JWT in DRF
I want to set user_id field using JWT token and store in database table when new reservation is created. there can be single or multiple reservation request. whenever user create reservation i want to store there user_id in our table. currently there is no foreign key associated with it. it is simply an integer field. I am able to fetch user_id from JWT.but its not updating in database I know this question had been asked previously i tried all the answer of previous post but its not working for me. i dont know why model.py class reservations(models.Model): pet_id=models.IntegerField() user_id=models.IntegerField(default=0) location=models.PositiveSmallIntegerField() arrival=models.DateTimeField() depature=models.DateTimeField() comments=models.TextField(max_length=200) view.py class requestReservation(CreateAPIView): serializer_class = requestReservationSerailizer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): serializer = requestReservationSerailizer(data=request.data,context={'user_id': request.user.id}, many=True) if not serializer.is_valid(raise_exception=False): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK) serializer.py class requestReservationSerailizer(ModelSerializer): user_id = SerializerMethodField('set_user_id') class Meta: model=reservations fields = [ 'pet_id', 'user_id', 'location', 'arrival', 'depature', 'comments', ] def set_user_id(self, obj): obj.user_id = self.context.get("user_id") return obj.user_id currently it is simply storing user_id as 0 which is default set in model. -
How to get form (connected with generic contenttype to model in detailview) in CreateView into DetailView?
I tried with FormMixins in DetailView and got my form, but the problem is obviously that they can't have the same view at all, or atleast not the same URL, so how does this work? I also tried with a post() function in the class. How would you manage a form that you need in several places on the same page(preferably using the built in class based views)? -
Django - Trying to save previous data
I've problem saving previuous data after clicking save. I want to compare manytomany field where i have queues. I override save method which adding users in queues, this queues is chosen by user using manytomany field, now i'm trying to write code which will do thing like this: when i remove any queue from that field, i want to also delete users from that queue which. But the problem is that i can't detect which queue is removed now and for that i need previuos data to compare new data and detect changes. This is code class QueueRoles(models.Model): role_name = models.CharField(max_length=256, blank=True, null=True, verbose_name="Name") role_queue = models.ManyToManyField(Queue, blank=True, null=True, verbose_name="Queues") role_users = models.ManyToManyField(User, blank=True, null=True, verbose_name="Users") def __unicode__(self): return self.role_name class Meta: db_table = 'qt_queue_roles' verbose_name = 'Queue Roles' verbose_name_plural = 'Queue Roles' def save(self, *args, **kwargs): if self.id: for queue in self.role_queue.all(): for user in self.role_users.all(): _tmp = QueueUser() _tmp.user = user _tmp.queue = queue if _tmp.user in self.role_queue.get(id=queue.id).user.all(): pass else: _tmp.save() super(QueueRoles, self).save(*args, **kwargs) -
How to operate with two models in one view
There are two models "Sensors" with information about them and "Measurments" . class Sensor(models.Model): date_start = models.DateField() Latitude = models.DecimalField(max_digits=18, decimal_places=15) Longitude = models.DecimalField(max_digits=18, decimal_places=15) def __str__(self): return 'id:%s / %s' % (self.id, self.date_start) class Measurment(models.Model): sens = models.ForeignKey(Sensor, on_delete=models.PROTECT) time_of_measurment = models.DateTimeField() humidity = models.PositiveSmallIntegerField() temperature1 = models.DecimalField(max_digits=5, decimal_places=2) temperature2 = models.DecimalField(max_digits=5, decimal_places=2) temperature3 = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return 'sens_id:%s, time:%s' % (self.sens.id, self.time_of_measurment) From each sensor I serially recive measurments. On the page, it is necessary to display the sensor data and the latest measurement data from the "Measurments" model corresponding for each sensor. for displaying data about sensor I used ListView: view: from .models import Sensor, Measurment class SenorsListView(generic.ListView): model = Sensor, Measurment context_object_name = 'sensors_list' template_name = 'sensors_list.html' queryset = Sensor.objects.all().order_by('-date_start') template "sensors_list.html": {% extends "base_generic.html" %} {% block content %} <h1>Sensors List</h1> {% if sensors_list %} <table class="table"> <tr> <td><h4>ID sens<h4></td> <td><h4>Date of install<h4></td> <td><h4>Latitude<h4></td> <td><h4>Longitude<h4></td> <td><h4>Data from last measurments<h4></td> </tr> {% for sensor in sensors_list %} <tr> <td>{{sensor.id}}</td> <td>{{sensor.date_start}}</td> <td>{{sensor.Latitude}}</td> <td>{{sensor.Longitude}}</td> <td>{{}}</td> </tr> {% endfor %} </table> {% else %} <p>There are no sensors in the DB.</p> {% endif %} {% endblock %} But dont know How to display data about last measurments. …