Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Manytomany to template
I have the following code: from django.db import models class Friend(models.Model): name = models.CharField(max_length=100) invited = models.ManyToManyField( 'self', through='Invites', symmetrical=False ) I then have an intermediary table that tracks the relationship history between friends. class Invites(models.Model) sent_invite = models.ForeignKey( Friend, on_delete=models.CASCADE, null=True related_name='sent_invite' ) received_invite = models.ForeignKey( Friend, on_delete=models.CASCADE, null=True, related_name='received_invite' ) As you can see, the Friend class maintains a Many to Many relationship with itself. Suppose I ran a query on Invites, assume user_id is the logged in Friend. received_invites_from = Invites.objects.filter(received_invite=user_id) This will return a query set looking like: Friend ID | User ID Friend ID | User ID Freind ID | User ID MAIN QUESTION How do I parse the Friend ID's through the Friend list a second time, and create an object list that can be rendered in a Django template? -
query data from one model, filter from another
I would like to display values from one table, but filter these values based on avalue from another table. for example: I want to display values from data/models.py that are filtered by the customerTag in the customer table (accounts/models.py). These are related tables, but I can't figure out the right syntax to filter this view. Any ideas? Or is this not possible with my current schema.. data/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Data from django.contrib.auth.mixins import LoginRequiredMixin #this ensures the user is logged in to view a specific page from rest_framework import generics from .models import Data from .models import accounts from .serializers import DataSerializer from .permissions import IsAuthorOrReadOnly class DataListView(LoginRequiredMixin,ListView): queryset = Data.objects.all() context = { "object_list": queryset } template_name = 'data_list.html' login_url = 'login' accounts/models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): customer_Tag = models.CharField(max_length=50,) isAdmin = models.BooleanField(default = False,) notifications = models.BooleanField(default = True,) deviceSerial= models.CharField(max_length=50,) machineName= models.CharField(max_length=50,default="ESP1",) machineDescription = models.CharField(max_length=200,) class Customer(models.Model): customerTag= models.CharField(max_length=50,) #make this == user.customerTag for queries? customerName = models.CharField(max_length=50,) mainContact = models.CharField(max_length=100,default='',) Address = models.CharField(max_length=100,default='',) city = models.CharField(max_length=100,default='',) website = models.URLField(max_length=100,default='',) phone = models.IntegerField(default=0,) def __str__(self): … -
cannot create a new post from django admin panel , but from python shell its created
from python shell i can add new post to my data base but from django admin panel its showing type error. i am using django with mysql with sqlite3 its working fine but what is the problem with mysql. TypeError at /admin/blog/post/1/change/ not all arguments converted during string formatting Request Method: POST Request URL: http://127.0.0.1:8000/admin/blog/post/1/change/ Django Version: 2.1.1 Exception Type: TypeError Exception Value: not all arguments converted during string formatting Exception Location: F:\myproject\venv\lib\site- packages\django\db\models\lookups.py in process_lhs, line 157 Python Executable: F:\myproject\venv\Scripts\python.exe Python Version: 3.6.4 Python Path: ['F:\\myproject', 'F:\\myproject\\venv\\Scripts\\python36.zip', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Anuj\\AppData\\Local\\Programs\\Python\\Python36', 'F:\\myproject\\venv', 'F:\\myproject\\venv\\lib\\site-packages', 'F:\\myproject\\venv\\lib\\site-packages\\setuptools-39.1.0- py3.6.egg', 'F:\\myproject\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg'] Server time: Fri, 7 Sep 2018 18:28:47 +0000 -
Playing a video in the home page by Django
I want to have a home page wich plays a video when the site runs, and has a button inorder to skip the video and go to the first page of the site any advice to do it ? -
Django Admin: 'id' is not a callable or method of model?
It's in the question. Why would my model not have the 'id' attribute? Isn't that created by default in Django? -
Django 'int' object is not subscriptable shows while adding images to database
I'm Inserting multiple images to database. I have saved the new Image name is Dictonary. But while inserting the data to table i'm getting ERROR : 'int' object is not subscriptable' I have searched everywhere but couldn't find solution. Here is below how Dictonary looks like { "0" = { "blog_id" = "". "blog_image_path" = "07-09-2018__17-54-152069weather.jpg". "is_deleted" = 0 }. "1" = { "blog_id" = "". "blog_image_path" = "07-09-2018__17-54-152069user.png". "is_deleted" = 0 }. "2" = { "blog_id" = "". "blog_image_path" = "07-09-2018__17-54-152069tick.png". "is_deleted" = 0 } } Now while adding the DB for image in blog_images_data: blog_image_data = BlogImages(blog_id=int(blog_id), blog_image_path=image['blog_image_path'], is_deleted=int(image['is_deleted']))# I GET ERROR IN THIS LINE blog_image_data.save() I have even changed the datatype to INT but still error persists. Below is the Model Details class BlogImages(models.Model): blog_image_id = models.AutoField(primary_key=True) blog = models.ForeignKey(Blog, null=True, on_delete=models.CASCADE) blog_image_path = models.TextField(null=True) is_deleted = models.SmallIntegerField(default=0, editable=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'tbl_blog_images' THANKS IN ADVANCE -
Djnago. String format using class field
I want to upload photos to difrent directory. The directory name should has a "title" from class field. I tried this. image = models.ImageField(upload_to=f"image/posts/{title}") It created: enter image description here Where in place <django.db.models.fields.CharField>I wanted to see post title. How can I get text from this Field (to save text I used django admin panel) models.py class Post(models.Model): # ... title = models.CharField(max_length=250) image = models.ImageField(upload_to=f"image/posts/{title}") -
Activate user Django 2.1
I came across a problem while developing my Django application. I need to register users and send a link to activate the user account, but when I click the link it does not activate the account, it just returns to my home page. How can I activate the user account? My code for urls.py: from django.contrib import admin from django.urls import path from contas.views import home, nova_transacao, update, delete, notSuper, signUp, activation_sent, activate urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='url_home'), path('update/<int:pk>/', update, name='url_update'), path('delete/<int:pk>/', delete, name='url_delete'), path('403/', notSuper, name='url_notSuper'), path('form/', nova_transacao, name='url_novaTransacao'), path('signup/', signUp, name='url_signUp'), path('signup/activation_sent/', activation_sent, name='url_activationSent'), path('activate/<slug:uidb64>/<slug:token>', activate, name='activate'), ] My code for views.py: from django.contrib.auth import login from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.template.loader import render_to_string from django.urls import reverse from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from contas.tokens import account_activation_token from .models import Transacao from .form import TransacaoForm, SignUpForm from django.core.mail import send_mail from django.conf import settings import datetime, time # Create your views here. def home(request): data = {} data["transacoes"] = Transacao.objects.all() data["now"] = datetime.datetime.now() return render(request, "contas/home.html", data) def nova_transacao(request): form = TransacaoForm(request.POST or None) if form.is_valid(): … -
How to check if a user liked a post in django
How do you check if a user liked a post in django template Post Model(fields removed for brevity* | likes is a counter) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) likes = models.IntegerField(blank=True, default=0) LikePost Model user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) How do I check if a user liked a post in my template using a generic list view. Any good answer would be appreciated. -
Django testrunner failing with IntegrityError
When trying to run Django tests, the process fails seemingly on the admin post migrate signal. I can't find anything about this particular error. It appears that the signal is attempting to create a permission record that already exists - but I haven't modified anything with this particular model. Traceback (most recent call last): File "/Users/username/.virtualenvs/app_name/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "auth_permission_content_type_id_codename_01ab375a_uniq" DETAIL: Key (content_type_id, codename)=(1, view_logentry) already exists. -
Django getting an objects foreignkey
I have an object called userprofile, which has a city ('ciudad') field. I'm trying to get it with current_user.ciudad but I get an error message "Ciudad matching query does not exist". Traceback: http://dpaste.com/2BMH8EG def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_user = self.request.user.userprofile print(current_user.ciudad) return context My models look like this class Ciudad(models.Model): ciudad = models.CharField(max_length=500) def __str__(self): return self.ciudad class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nombre = models.CharField(max_length=250, default=".") apellido = models.CharField(max_length=250, default=".") email = models.CharField(max_length=250, default="error") telefono = models.IntegerField(default=0) ciudad = models.ForeignKey(Ciudad, default=0, on_delete=models.SET_DEFAULT) is_productor = models.BooleanField(default=False) is_nodo = models.BooleanField(default=False) def __str__(self): return str(self.user) -
Django how to use webhook and post data?
i am confused about django webhooks because i am beginner in python and django. Most of the things i see for the documentation. how do i connect to my app and Post data.Can anyone tell me how do i set my webhook for my data. i want to Post data to zapier. Models.py class Driver(models.Model): class Meta(): db_table = "driver" verbose_name = "Driver" verbose_name_plural = "Drivers" ordering = ['driver_firstname', 'driver_lastname'] driver_firstname = models.CharField( max_length=64, blank=True, null=True ) driver_lastname = models.CharField( max_length=64, blank=True, null=True ) driver_email= models.CharField( max_length=64, blank=True, null=True ) Views.py def drivers(request): if request.method == 'POST': if request.POST['driver_firstname'] and request.POST['driver_lastname'] and request.POST['driver_email'] driver = Driver() driver.driver_firstname = request.POST['driver_firstname'] driver.driver_lastname = request.POST['driver_lastname'] driver.driver_email = request.POST['driver_email'] driver.save() -
What is Django commend equivalent to Rails' $ rails db drop
Something must be very very wrong. It can't be this hard. I'm trying to drop tables on my Django app, which is made from default sqlite3 ORM. Every time I want to $ python manage.py makemigrations, Django asks me how I want to handle new field on already existing rows and I hate it. So what I want to do is just drop all tables from my model 'Post' and make new migrations. This is easily done by $ rails db drop; rails db migrate on Rails but I can't find any commend equivalent to this on Django. I've googled and I found a commend like $ python manage.py flush but it effectively flushes all my tables, even my Superuser. I don't want that and I want to drop a table from a specific app. Some posts even said I have to manually delete all migrations files and db.sqlite3 but I bet there's another way. One more alternative I think think of is to open manage.py shell and delete them like below (which I learned from the official documentation's tutorial) $ python manage.py shell >> from posts.models import Post >> Post.objects.all().delete() I hope it's not the way it should be. -
Reading Shopify shop metafields with Django/Python: Discrepancy between AJAX call and backend view behavior
Getting the list of shop metaifleds works great if running on the server in a simple Django view: def my_view(request): with request.user.session: shop = shopify.Shop().current() print(shop.metafields()) # returns [(metafield(1232543), metafields(143534534), etc] However, if I do something like this (don't panic, I'm just experimenting) in an AJAX handler, it returns an empty array. @csrf_exempt def proxy_request(request): shop_user = AuthAppShopUser.objects.get(myshopify_domain=site) user = auth.authenticate(request=request, myshopify_domain=site, token=shop_user.token) if user: auth.login(request, user) with request.user.session: shop = shopify.Shop().current() print(shop.metafields()) # returns [] Thank you for any insight! -
Special markup from text to html tags (with PHP)
I'm importing data from website - written in python(django), and content data are in format: text paragraph text paragraph text paragraph<br> text paragraph text paragraph text paragraph<br> h2. Any title<br> text paragraph text paragraph text paragraph<br> h3. Any title<br> "more in":http://www.example.com/<br> which in final format should be: <p>text paragraph text paragraph text paragraph</p> <p>text paragraph text paragraph text paragraph</p> <h2>Any title</h2> <p>text paragraph text paragraph text paragraph</p> <h3>Any title</h3> <a href="http://www.example.com/">more in</a> i tried php function nl2br() which at least got me breaks at line, but need if exist any great function which make me final format. I can try my own fcn but still i can't get, how can i replace for example h3. with <h3> and end of line with </h3> Any help you can offer is greatly appreciated. -
django 2 no reverse macth on passing url <a href="{% url 'detailinfo' infos.id %}"></a>
my model = Infos this my urls.py path('infos/<int:infos_id>/', views.detailinfo, name='detailinfo'), this my views.py #pages detail infos def detailinfo(request, infos_id): infos = get_object_or_404(Infos, pk=infos_id) return render(request,'uplus/detailinfo.html',{'infos': infos}) the link to access to page detailinfos on my browser http://127.0.0.1:8080/infos/1/ the url passing <a href="{% url 'detailinfo' infos.id %}"></a> -
Django Serialization KeyError (Django Rest Framework)
I need to write custome create method to make nested serialization, so i have this: def create(self, validated_data): images = validated_data['commodity']['images'] del validated_data['commodity']['images'] commodity = Commodity.objects.create(**validated_data['commodity']) del validated_data['commodity'] for image in images: CommodityImage.objects.create(commodity=commodity, **image) sizes = validated_data['outwear']['sizes'] del validated_data['outwear']['sizes'] clother = Clother.objects.create(commodity=commodity, **validated_data) outwear = Outwear.objects.create(clother=clother, **validated_data['outwear']) for size in sizes: outwear.sizes.add(size) return clother Most of lines doing fine and outwear instance creates, but in can't add sizes to outwear instance, which has sizes as ManyToMany field in it's model and finally i get KeyError 'sizes' with no description. What am I doing wrong? Thanks! -
Create Temporary Table For Testing Unmanged Model in Django
I've got a django app that has a couple models that read from tables in an unmanaged database. I'm just trying to create tests appropriately to make sure that the application can be as well tested as possible. I'm using factory_boy to assist with the creation of test data. One of my unmanaged models looks like this: class EmpGroup(models.Model): id = models.IntegerField(db_column='id', primary_key=True) staff_group = models.ForeignKey( StaffGroup, db_column='staff_group_id', on_delete=models.PROTECT ) user = models.ForeignKey( settings.AUTH_USER_MODEL, db_column='user_id', on_delete=models.PROTECT ) location = models.ForeignKey( Location, db_column='base_loc', on_delete=models.PROTECT ) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) location_name = models.CharField(max_length=50) def __str__(self): return f'{self.last_name}, {self.first_name}' class Meta(object): managed = getattr(settings, 'UNDER_TEST', False) db_table = 'control_v_empGroup' Because that model is unmanaged - there is no migration to tell it to create the table control_v_empGroup when setting up the test DB's. So when I run my tests - I get the the error that the table doesn't exist! My EmpGroupFactory looks like this: class EmpGroupFactory(factory.django.DjangoModelFactory): class Meta: model = models.EmpGroup id = 1 staff_group = factory.SubFactory(StaffGroupFactory) user = factory.SubFactory(UserFactory) location = factory.SubFactory(LocationFactory) first_name = 'Test' last_name = 'Grp' location_name = 'Test' In my settings I have this: UNDER_TEST = (len(sys.argv) > 1 and sys.argv[1] == 'test') if UNDER_TEST: DATABASES … -
How can I get value of radio button's input?
How can I get value of input?I wrote codes in html, <form action="{% url 'app:top' %}" method="POST"> <input type="radio" name="no" value="1"> <label>No</label> <input type="radio" name="yes" value="1"> <label>Yes</label> <input class="disabled" type="submit" value="POST"> </form> in views.py def top(request): no = request.POST.get("no","0") yes = request.POST.get("yes","0") print(no) print(yes) When I No label and put send button,0 is print out.Putting Yes button is same.Why does it happens?Why can't I print out 1?How should I do it? -
How to connect Ejabberd with Node.js (or Django)
I what to develop a backend server for a chat application using node.js (or Django) and Ejabberd. And consume this API on a React Native app that should have push notifications. The idea is to manage the user profile and metadata and also the authentication ( OAuth 2.0 - social login ) through my own server, then let the management of the chat stuff to the Ejabberd server. The problems come on how to make the connection between the servers. I want to login through my server and don't make the user aware of the existing Ejabberd server. Any idea on how can I make the connection between the servers? -
Django; What is preferable way to upload some images?
I've been working on Django project. Currently, user can upload only one image but now I want to change it so user can upload some images. models.py is like this. class Entry(models.Model): photo = models.ImageField(...) I am thinking of just adding photo2 and photo3 inside Entry model. But I'm wondering if there's a better way to do it. I don't want to delete images that are already uploaded. Anyone who could give me tips? Also, I don't like the file upload form's design and some people use just button-like form. I also want to know how to create button-like form. -
How to Create a UpdateForm with TemplateView?
I need to create a UpdateForm with a TemplateView. Why with TemplateView? Because, I has a attribute what is geo_location, and I'm using LeafLet maps, and LeafLet maps doesn't work with generic.UpdateView or others the same type. Here my views from Update: class UpdateStore(LoginRequiredMixin, TemplateView): template_name = 'store_form' success_url = reverse_lazy('register:store_list') def post(self, request, *args, **kwargs): store_id = kwargs['store'] store = get_object_or_404(Store, pk=store_id) form = StoreForm(request.POST, on_edit=True) if form.is_valid(): form.save() return redirect(reverse('register:store_list')) else: context = self.get_context_data() context['data_form'] = form return render(request, self.template_name, context) return self.get(request) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) store_id = self.kwargs['store'] store = get_object_or_404(Store, pk=store_id) data = { 'name': store.name, 'description': store.description, 'address': store.address, 'geo_loc': store.geo_loc, 'opened': store.opened } context['editing'] = True context['data_form'] = StoreForm(initial=data, on_edit=True) context['store'] = store return context I trying this, but in my template, the Forms doesn't load, and my template are blanked :(. Someone knows why? I need another method for get anything else? Thanks. -
Prefetch of ForeignKey in Serializer.is_valid() in Django
I am attempting to create many model instances in one POST using a Mixin to support POST of arrays. My use case will involve creating 1000s of model instances in each call. This very quickly becomes slow with DRF due to each model being created one at a time. In an attempt to optimise the creation, I have changed to use bulk_create(). While this does result in a significant improvement, I noticed that for each model instance being created, a SELECT statement was being run to get the ForeignKey, which I traced to the call to serializer.is_valid(). As such, adding n instances would result in n SELECT queries to get the ForeignKey and 1 INSERT query. As an example: Models (using automatic ID fields): class Customer(models.Model): name = models.CharField(max_length=100, blank=False) joined = models.DateTimeField(auto_now_add=True) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) timestamp = models.DateTimeField() price = models.FloatField() POST data to api/orders/: [ { "customer": 13, ... }, { "customer": 14, ... }, { "customer": 14, ... } ] This would result in 3 SELECT statements to get the Customer for each of the Orders, followed by 1 INSERT statement to push the data in. Similar to prefetch_related() for queries when fetching data … -
Django Channels 2 stops sending message after a while but keeps receiving from client side
I have a problem with sending a group message when receiving message from client after some time of starting a server. First a first half an hour or so messages are beign received and sent successevly. If I got this error and just change some code in python to restart code execution then problem disappears untill next time. I'm using: Django 2 (latest), Django Channels 2 (latest) in async mode, Redis, Postgresql All of this wrapped to a Docker containers (that's why redis config is 'redis' not localhost or so) -
Django forms cleaned data
I have a written library for application. Library methods accepts ids of objects of integer type. Instead of User objects it accepts username and so on. Where i have to convert the data from my forms into proper type? Can i do this in clean methods of my forms or i should do this in my views? Does it follows the rules or clean method is used only for validation? def clean_object_id(self): if self.cleaned_data['object_id']: return int(self.cleaned_date['object_id'])