Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django concatenate list queries from two models
As a Django newbie, I am trying to return JSON Objects from two models with each object containing the username, id, ticketID. Right now the code is simply putting the lists together without indexing. I should point out that there is a relationship between user and ticket so that can be traversed also. {"username":"Paul","id":2}, {"username":"Paul","id":2}, {"username":"Ron","id":19}, {"id":"1c6f039c"}, {"id":"6480e439"}, {"id":"a97cf1s"} class UsersforEvent(APIView): def post(self, request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) value = body['event'] queryset = Ticket.objects.filter(event = value) referenced_users = User.objects.filter(ticket_owner__in=queryset.values('id')) result_list = list(itertools.chain(referenced_users.values('username', 'id'), queryset.values('id'))) return Response((result_list)) -
Django RestFramework: two way ForeignKey relation
There are two models Parent and Children. class Parent(models.Model): name = models.CharField(max_length=128) children = ? class Children(models.Model): name = models.CharField(max_length=128) parent = ? If we need the children instances to have parent as link to model Parent we can use ForeignKey in Children and vice versa. If parent A has children B and C and we want A to have ids of children B and C and children B and C to have id of parent A. i.e. A.children = (B.id, C.id) and B.parent = A.id, C.parent = A.id. How can we achieve this? parent = models.ForeignKey(Parent, related_name='children') can this be used? -
NoReverseMatch at /signup/
when the user registers, does not show the page that the confirmation email was sent and does not send the confirmation email.django -
Django: relation "django_site" does not exist in app with psql using sites framework
after switching from sqlite to postgres for local dev db, I am unable to migrate my app. Several fixes and approaches I've attempted have not resolved (ex: Django: relation "django_site" does not exist). python: 3.6.3 Django Version: 1.11.9 psql (PostgreSQL): 10.1 err: File "/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: SELECT (1) AS "a" FROM "django_site" LIMIT 1 installed apps: DJANGO_APPS = ( # Default Django apps: 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.admin', ) THIRD_PARTY_APPS = ( 'widget_tweaks', 'mptt', 'channels', 'honeypot', 'gunicorn', 'djangosecure', # Allauth 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ) LOCAL_APPS = ( 'users.apps.UsersConfig', #because of a signal 'common', 'geo', 'community', 'objects', ) INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS in .env file: SITE_ID=1 solutions I have attempted: Cleared all migrations and migration files and ran: $ ./manage.py makemigrations then I have attempted sequential and manual migrations of apps starting with django.contrib, such as: $ ./manage.py migrate sites (first) then applying additional migrations. but regardless of how I order app migrations does not change err or allow migration to complete. I have also tried migrations with --fake-initial. it looks like it is calling a site object before creating … -
Where should user specific model filters live in Django
I am designing a school app where users will be provided with model objects wrt their positions and roles. Now generally this seems to be handled by custom manager methods. However, they also need to be user specific, and user is in the request. So, how do I design a system without breaking the separation of concerns, i.e., MVC. I also intend to use Guardian app for object permissions in addition to the default authorization backend. I am not sure how to coordinate them either. -
can we use django authentication as a micro service in different project?
In my project we are trying to create micro service type architecture using djnago/django-rest-framework. We've some services like: User management service Asset Management Service Tool management service All three services running on different Ports with different database. Now my question is, Can we use user management service in Asset and tools service for Token authentication? -
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order
I have a problem with django. Actually I want to create a login panel in my new site but when I try to write address the debugger respond me a error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/account/login Using the URLconf defined in firmowa.urls, Django tried these URL patterns, in this order: admin/ ^account/ The current path, account/login, didn't match any of these. My firmowa.urls is from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(r'^account/', include('account.urls')), ] And the project urls.py is: from django.urls import path from . import views urlpatterns = [ path(r'^login/$', views.user_login, name='login'), ] I'm looking a solution from few hours but still nothing. -
Trying to upload multiple files, but getting str error
So I am trying to upload multiple files and get this error : __str__ returned non-string (type int) The thing is related to my str function. If I leave it like return self.file, then it will just show object, not real filname. Also, tried using os.basename but unsuccessfully. class FileUpload(models.Model): file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.file.name class AnotherClas(models.Model): file_upload = models.ForeignKey('FileUpload', on_delete=models.CASCADE, blank=True) -
Is there a limit for requests in db.sqlite3 in Django ?
I'm working with Django and I have a db.sqlite3 database. With my Django Website I want to add rows (Tweets collected with the Twitter API to be precised) to my database by clicking on a button. It works but it can't add more for than 100 rows for each click on the button. Here is the code : for tweet in tweets[:200]: q = Question(question_text=tweet.text, pub_date=timezone.now()) q.save() After I clicked on my button, there is 100 more rows in my database but not 200. So do you know if there is a limit of 100 rows by request in db.sqlite3 in Django ? And do you know how to remove that limit ? Thank you very much by advance for your answer :) -
Django model objects and Graphene get_node
So far I was able to play around with Graphene without needing DjangoObjectType. I try to avoid it as I'm not planning to stay too close to my Django model classes. However I'm having issues when implementing Relay with Graphene: class HouseholdNode(graphene.ObjectType): class Meta: interfaces = (graphene.relay.Node,) name = graphene.String() @classmethod def get_node(cls, info, id): return Household.objects.get(pk=id) This fails with the following error: Abstract type Node must resolve to an Object type at runtime for field Query.node with value "Test", received "None". "Test" comes straight from Household's __str__ function. Next try: @classmethod def get_node(cls, info, id): return cls(Household.objects.get(pk=id)) cls is Household (the node). However this yields the wrong result: "node": { "id": "SG91c2Vob2xkOlRlc3Q=", "name": null } The ID is actually "Test". Solution that works: @classmethod def get_node(cls, info, id): household = Household.objects.get(pk=id) return cls(name=household.name) However I highly doubt that this is all Graphene can do for me. Do I really have to wrap the real data object into HouseholdNode? I already have resolve functions, can't those simply be used instead? The documentation is highly lacking on those edges, please enlighten me. -
How can I link model in new app with specific model data in allauth?
In Django, I have installed allauth. Then I have created a new app, where user's actions will be. I want to link each of the actions with allauth's user data within EmailAddress model. My questions are: Normally, data is defined by user_action = models.CharField(max_length=200) and such. ForeignKey on user action does not allow defining field types, at least from what I've seen. How can I define it, or is it okay not to define it? How can I define the relationship with data in allauth's model that's not anywhere near this new app? For example, I have: from django.db import models import allauth.account.models class Button(models.Model): button_one = models.ForeignKey('EmailAddress', on_delete=models.CASCADE) def __str__(self): return self.button_one It does not work. The error shows: input.Button.comment: (fields.E300) Field defines a relation with model 'EmailAddress', which is either not installed, or is abstract. input.Button.comment: (fields.E307) The field input.Button.comment was declared with a lazy reference to 'input.emailaddress', but app 'input' doesn't provide model 'emailaddress'. The allauth model data ("user") in question is: class EmailAddress(models.Model): user = models.ForeignKey(allauth_app_settings.USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) email = models.EmailField(unique=app_settings.UNIQUE_EMAIL, max_length=app_settings.EMAIL_MAX_LENGTH, verbose_name=_('e-mail address')) verified = models.BooleanField(verbose_name=_('verified'), default=False) primary = models.BooleanField(verbose_name=_('primary'), default=False) objects = EmailAddressManager() I'm using virtualenv and have allauth installed within the project. -
Django email sending: Attach zip file as well as HTML template
I am trying to email both html content and a zip file attached using EmailMultiAlternatives from django. Not sure why at a time only one of them can be attached. # import from django.core.mail import EmailMultiAlternatives mail = EmailMultiAlternatives('Subject', "", 'from emails', 'to emails') if file: mail.attach_file(file) mail.attach_alternative(html_content, "text/html") mail.send() -
Django. Get related field id
room = Reserved.objects.get(room=id) ?? I want to get id of that field exists in the one model. For example: models.py class Room(models.Model): number = models.OneToOneField(RoomNumber) class Reserved(models.Model): room = models.OneToOneField(Room, on_delete=models.PROTECT) Id of room that exits in Reserved table. How to get it? Thanks:) -
"Truncated incorrect DOUBLE value: X_XX"
Django's ORM just isn't clicking for me, but I intend to spend the weekend reading through the documentation in order to make it click. Meanwhile, I have an issue I need to resolve that I haven't been able to. The first I had was here, which was resolved with the answer provided: ValueError: invalid literal for int() with base 10 seems to be related to ForeignKey I have modified my query to: # data['product_id] = 78 # returns A_17 product_code = Products.objects.get(id=data['product_id']).code # this is where the error occurs print(ProductPositions.objects.filter(product_code__code=product_code)) /mnt/c/dev/current/client/.venv/client/lib/python3.6/site-packages/pymysql/cursors.py:166: Warning: (1292, "Truncated incorrect DOUBLE value: 'A_15'") result = self._query(query) I am not even sure why it is looking at A_15 because it should only be filtering on A_17, so that is one issue I don't understand To explain these tables because I don't think it is really intuitive. The Products will look something like this (with columns not relevant to this removed): -- Products table id code -------------- 77 A_16 78 A_17 81 M_15 There are multiple of the code in the ProductPositions. code is more like a line of products and and product_no (which I haven't got to yet and is the next step) are the products … -
Django restframework permissions
it is a basic api, I have 3 kinds of users -> admin, companies, employees. admin can view, edit and delete all of them, companies can view and delete it's employees and employees can only see the videos updated by it's companie. So each companie will have an admin panel that they can upload training videos and register it's employees, so each companie has it's own panel, they don't see other companies. Do I need to create a custom user model to do that? How would I create that model, How can I set those permissions? How can I manage the register form, login, urls that the companies and employees can or can't access -
'Mixed Content' warning when accessing localhost
I have a website backed by Nginx and Django using HTTPS. I also have a client program that runs locally on my computer. The website is accessed with HTTPS and makes Post requests to the client at http://localhost. I use jQuery for the request to localhost: jQuery.ajax({ url: "http://localhost:5555/command", data : data type : "POST", }); I get the following error message from Chrome: Mixed Content: The page at 'https://example.com/whatever/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://localhost:5555/'. This request has been blocked; the content must be served over HTTPS. This warning is normally useful, but it seems kind of pointless for localhost. How can I allow this access? Note: this question is similar to this one, but different because I care about localhost in particular and not an arbitrary http website: "Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page -
Django, listing the query-set of connected Models
I would like to list all conversations of a User. As seen from picture below, Conversation Model is not Directly connected to the User table. This is a freelancer site project, where users can register as workers to do jobs posted by users. The result I want is: my_conversations = User.Conversation.all() I'm adding this picture, since it paints everything that I will summarise below. Let's images I have 2 users, one of which is a registered worker. Then it looks as follows: **Users** id Name ... 1 John 2 Bob **Worker** id user_id ... 1 2 John posted some job. We add 1 new entry to the JOB table. **Job** id title user_id 1 Help me design a database 1 This is a M-to-M relationship (worker can apply for many jobs and one job can have many workers), we define a new table where job_has_worker. For each job_has_worker, there should be a way to communicate between worker and job poster. Now what I would like Django to do is load all conversations the user who is logged in e.g. load a list of my conversations for the jobs I posted. Views - My Posted Jobs User = request.user Jobs = … -
Got InvalidClientIdError (invalid_request) Mismatching redirect URI. using requests_oauthlib
I am trying to simulate token exchange between consumer and provider (server_to_server) using library requests_oauthlib. I getting error after I receive the code after authorization at provider side and exchanging the code for the token. So I get my code in my callback function but it is saying that redirect uri doesn't match. I already checked Redirect uri in provider's DB. They are the same. (as variable redirect_uri in code below) See my Django implementation: views.py # create session from importlib import import_module SessionStore = import_module(settings.SESSION_ENGINE).SessionStore session = SessionStore() client_id = "123456" client_secret = "123456" authorization_base_url = 'http://localhost:8000/o/authorize/' token_url = 'http://localhost:8000/o/token/' redirect_uri = 'http://localhost:8888/callback' # ONLY FOR A LOCALHOST import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' def index(request): provider = OAuth2Session(client_id, redirect_uri=redirect_uri) authorization_url, state = provider .authorization_url(authorization_base_url) # state is used to prevent CSRF, keep this for later. session['oauth_state'] = state # redirect to provider return redirect(authorization_url) def callback(request): # handles code from provider and redirects to profile page redirect_response = request.build_absolute_uri() # (http://localhost:8888/callback?code=123456&state=SomeStateCode) state = session.get('oauth_state') laas = OAuth2Session(client_id, state=state) token = laas.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response) # here is mismatch error session['oauth_token'] = token return HttpResponseRedirect(reverse('app:profile')) def profile(request): # shows access token if existing if session.get('oauth_token') is not None: return HttpResponse("Token: " … -
Django Rest: Add data to a "required" field automatically
I want to automatically assign a value for a required field in django rest framework, without the value having to be given in the post request. My View: class WaitercallCreate(CreateAPIView): serializer_class = WaitercallCreateSerializer permission_classes = (IsAuthenticated, ) The Serializer: class WaitercallCreateSerializer(serializers.ModelSerializer): class Meta: model = Waitercall fields = ('order', 'user', 'done', 'type_of_call') read_only_fields = ('user', 'done') Users should be able to do a postrequest, only giving their token in the header and the order id as the body. I want to set the value for user by default to the requests user. I tried overwriting the perform_create method in my view like this: def perform_create(self, serializer): serializer.save(user=self.request.user) This didn't work. Then I tried overwriting the create method in the view like this: def create(self, request, *args, **kwargs): data = request.data data['user'] = request.user serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Which also didn't work, because Orderdicts are immutable. For the first (and the last try, read further) I allways get the same response: { "user": [ "This field is required." ] } Lastly I found this stackoverflow post, which recommends overwriting the create method in the serializer. Like this: def create(self, validated_data): print(self.context['request'].user) validated_data['user'] = … -
django pagination "That page contains no results"
I want to use django pagination. The first page able to load products but last page not showing. my index view here def index(request): categories = Category.objects.filter(parent_category=None) product_list = Product.objects.filter(is_deleted=False).order_by('created_at') paginator = Paginator(product_list, 1) # Show 25 contacts per page page = request.GET.get("page",1) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(1) context = { 'products': products, 'categories': categories } return render(request, 'product/urunler.html', context) here is .html <div class="blog-pagination"> <ul class="flat-pagination style1"> {% if products.has_previous %} <li class="prev"> <a href="?page={{products.previous_page_number}}" title=""> <img src="{% static 'images/icons/left-1.png' %}" alt="">Önceki Sayfa </a> </li> {% else %} <li class="prev"> <a href="#" title=""> <img src="{% static 'images/icons/left-1.png' %}" alt="">Önceki Sayfa </a> </li> {% endif %} {% for i in products.paginator.page_range %} {% if products.number == i %} <li class="active"> <a href="?page={{i}}" class="waves-effect" title="">{{i}}</a> </li> {% else %} <li> <a href="?page={{i}}" class="waves-effect" title="">{{i}}</a> </li> {% endif %} {% endfor %} {% if products.has_previous %} <li class="next"> <a href="?page={{products.next_page_number}}" title=""> Sonraki Sayfa <img src="{% static 'images/icons/right-1.png' %}" alt=""> </a> </li> {% else %} {% if products.has_next %} <li class="next"> <a href="" title=""> Sonraki Sayfa <img src="{% static 'images/icons/right-1.png' %}" alt=""> </a> </li> {% endif %} {% endif %} </ul> <div class="clearfix"></div> </div> … -
Why null field for foreign key?
Using django 1.11 I am using an API backend for a django accounts project. The following is an example of a class: from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.conf import settings import datetime class Credit(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=200) payment_reference = models.IntegerField() amount = models.IntegerField() payment_type = models.CharField(max_length=200,default='Paypal') country = models.CharField(max_length=200,default='Ireland') payment_location = models.CharField(max_length=200,default='On-site') date = models.DateTimeField(auto_now_add=True) The standard user was over-written in another app called profiles and I have included this in settings.py - 'AUTH_USER_MODEL = 'profiles.User' from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from django.utils import timezone # Create your models here. class Profile(UserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): objects = Profile() When I try to run makemigrations however I am told that I am trying to change the nullable field 'user' to non-nullable without a default. Why would I need a default if im making reference to the active user? I want the foreign key value to be … -
Django: Correct request to database to calculate DAU
Could someone find a mistake(s) in my request to the database in Django? So, I have the next model: class GameEvent(models.Model): game = models.ForeignKey(Game, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) app_id = models.CharField(max_length=255, blank=False) datetime = models.DateTimeField(blank=False) def __str__(self): return u"%s [ %s ]" % (self.game.title, self.name) @receiver(models.signals.pre_save, sender=GameEvent) def update_datetime(sender, instance, **kwargs): instance.datetime = datetime.datetime.now() I create the record in the database each time when my game sends me some event like:level complete, level failed etc. To recognize which copy of application sends me the events the copy has unique app_id. So the question is how to calculate DAU. I make the next request to database but it returns wrong answer: dau = GameEvent.objects.filter(game = game, datetime__gte = date_start, datetime__lte = date_end) .extra({'date' :'date(datetime)'}) .values('date') .annotate(count=Count('app_id', disntict=True)) .order_by('date') If I choose date range for one day it returns dau[0].count = 1200, but the next request which calculates the count of unique app_id returns 100: app_ids = GameEvent.objects.filter(game = game, datetime__gte = date_start, datetime__lte = date_end) .values_list('app_id', flat=True).distinct() So, where is mistake? Thanks for helping -
Django template doesn't render models as I would expect
So I have this Lecture class. Now for this class, I have 2 choices: "Classes" and "Seminars", and I want that each time I add a lecture to either one, the template will shows firstly the choice and then all the lectures. Example: Classes will have Lecture1, Lecture2, Lecture3 etc. Problem is that right now when I iterate, choice shows each time, for every lecture and I want each choice to show only ONCE. class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.IntegerField(choices=((0, "Classes "), (1, "Seminars"), )) lecture_title = models.CharField(max_length=100) content = models.TextField() link = models.URLField(blank=True) file = models.FileField(upload_to='documents', blank=True) def __str__(self): return self.lecture_title <ul> {% for c in lectures %} <b>{{ c.get_lecture_category_display }}</b> <p>.......................</p> <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% if c.link %} <li>{{ c.link }}</li> {% if c.file %} <li><a href='{{ MEDIA_URL }}{{ c.file.url }}'>download</a></li> {% endif %} {% endif %} {% endfor %} <hr/> </ul> -
Use a model field to query another model field in django
I have two models in our django app class Reg(models.Model): transactions = ManyToMany price = IntegerField class Transaction(models.Model) amount = IntegerField Now I would like to make a lookup like: Registration.objects.filter(reg__price==transaction__amount) Previously we used the following approach: Registration has a property is_paid that computes wether a transaction with equal amount exists [r for r in Registration.objects.filter(...) if r.is_paid] This is ofc very query-consuming and inefficient. I wonder whether there would be a better way to do this! Any hint is appreciated :) -
how to use Websocket in Angularjs
I'm trying to use Websocket in Angularjs. I have added this implementation in a factory becouse want to use it in different controllers, so this is my code .factory('webSocketBridge', function () { const webSocketBridge = new WebSocketBridge(); webSocketBridge.connect('/ws/user-notification/'); webSocketBridge.listen(function(action, stream) { console.log(action, stream); }); webSocketBridge.socket.addEventListener('message', function() { console.log("message"); }); webSocketBridge.socket.addEventListener('open', function() { console.log("Connected to WebSocket"); webSocketBridge.send({prop1: 'value1', prop2: 'value1'}); }); return webSocketBridge; }); Open event working and I see "Connected to WebSocket" console but Message event not working. Can someone show me how I can send message and get it