Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Saving many-to-many within Celery shared task
I'm creating a new object within a Celery shared task. This will save objects to my database, but will not save the django-taggit tags field (a many-to-many field). # models class Something(models.Model): ... tags = TaggableManager() # this is the many-to-many field The form I'm using for new objects will save tags in string format, separated by commas. 'example, tag, here'. I've replicated that when I pass it to the tags field in my tasks.py. # tasks.py @shared_task def save_something(list): for l in list: Something.objects.create( ... tags = l['tags'] ) When I'm using forms.py I'm able to call form.save_m2m() to save the many-to-many relationship; however, I'm struggling to find an equivalent to use in Celery tasks. Any help would be greatly appreciated! -
display uploaded items to a grid on django(html and css)
I have a grid that has to show the uploaded images in 3 columns, first time I tried this I realized that just the first uploaded image is being shown so I added a forloop counter which dint work also. What should I do to show this uploaded images on a grid. views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) if username: post_owner = get_object_or_404(User, username=username) user_posts = Post.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts = Post.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, } return render(request, 'profile.html', args1) models.py class Post(models.Model): images = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) html {% for Post in user_posts %} <div class="grid-wrapper"> {% if forloop.counter|divisibleby:3 %} <div class="grid-item"> {% if Post.video %} <video width="400" style="border-radius: 2px;"> <source src='{{ Post.video.url }}' type='video/mp4'> </video> {% endif %} </div> {% endif %} </div> {% endfor %} css .grid-wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 250px; grid-gap: 1rem; grid-auto-flow: row; } .grid-item { background: red; display: flex; justify-content: center; align-items: center; } -
pip installing in usr/lib/python3.6/site-packages instead of virtualenv on ubuntu server
I'm having a problem when installing packages on my virtualenv.It all started when I upgraded my pip to the latest version. I tried to revert my pip version to where I find it stable. When I try to install, for example, django-tables2, it says: Requirement already satisfied: django-tables2 in /usr/lib/python3.6/site-packages (2.3.1) Requirement already satisfied: Django>=1.11 in /usr/local/lib/python3.6/dist-packages (from django-tables2) (2.2.4) Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-tables2) (2019.2) Requirement already satisfied: sqlparse in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-tables2) (0.3.0) WARNING: You are using pip version 19.3.1; however, version 20.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. But when I check my folder in my virtualenv, it doesn't show there. I tried some commands like which pip and which pip3 and it says this: (unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject# which pip /home/unidaweb/unidaproject/unidaenv/bin/pip (unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject# which pip3 /home/unidaweb/unidaproject/unidaenv/bin/pip3 (unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject# I also tried pip list but I can't find the package that I installed to my virtualenv. I'm getting a bad gateway error when I try to add it on my settings.py, I don't really know how to fix this but when I'm in the version of pip that I know was stable running my project, I don't get this … -
Django Social Auth with Vue.js redirect_uri_mis
I'm trying to get social auth working with Vue.js and Django. I have the following setup for Vue: main.js Vue.use(VueAuthenticate, { providers: { salesforce: { name: "salesforce", url: "http://localhost:8000/api/login/social/token_user/salesforce-oauth2", authorizationEndpoint: "https://login.salesforce.com/services/oauth2/authorize", clientId: "clientId", redirectUri: "http://localhost:8080/profile", requiredUrlParams: ["display", "scope"], scope: ["email"], scopeDelimiter: ",", display: "popup", oauthType: "2.0", popupOptions: { width: 580, height: 400 }, }, }, }); If I change the redirect Uri in Vue, I get a redirect URI mismatch in the popup window. However, with this configuration, I get the following error in the debug logs of Django: {'error': 'redirect_uri_mismatch', 'error_description': 'redirect_uri must match configuration'} Any suggestions on how to resolve this? I have added multiple URIs to the callback URL in the connected app but still have not been able to solve this. -
Foreign keys vs Composite keys in SQL
I have a table just like this: USER_RELATIONSHIP ---------------------- user_id follows_id 1 2 1 3 2 1 3 1 Both user_id and follows_id are Foreign keys that point to a User table. The USER_RELATIONSHIP table is quite large and I am frequently checking to see if a user relationship exists or not (eg. user A follows user B). Given that these Foreign keys are indexed, is SQL able to find a relationship (given a user_id and a follows_id) in O(1)? If not, is it more performant to condense the two fields above into an indexed Composite key that hashes a user_id and a follows_id and having the USER_RELATIONSHIP table like this? USER_RELATIONSHIP ---------------------- composite_key 298437920 219873423 918204329 902348293 -
Django Reason for getting TemplateSyntaxError?
I have created a new app called newsletters. I can access the pages when I write their location directly from local host by writing http://127.0.0.1:8000/newsletters/signup/ but when I try to add their url in the nav bar I am getting an error: TemplateSyntaxError at / Invalid block tag on line 40: 'url'newsletters:subscribe''. Did you forget to register or load this tag? Here are the main project urls: urlpatterns = [ path('admin/', admin.site.urls), path('newsletters/', include('newsletters.urls', namespace='newsletters')), ] Here are newsletters app urls: app_name = 'newsletters' urlpatterns = [ path('signup/', newsletter_signup, name="subscribe"), path('unsubscribe/', newsletter_unsubscribe, name='unsubscribe'), ] here are the nav bar template: <div class="dropdown-divider"></div> <a class="dropdown-item" href=" {% url'newsletters:subscribe' %}">Newsletters</a> <div class="dropdown-divider"></div> How should I fix it and what am I have I done wrong to avoid it? -
Django: cannot unpack non-iterable int obj
I'm a new programmer attempting to put in a "submit comment" page in my project using a generic CreateView. The page displays properly when it first loads, but after clicking the form's "submit" button, I get a "TypeError at /blog/blog/4/create - cannot unpack non-iterable int object." Here is the generic view in question: class BlogCommentCreate(LoginRequiredMixin, CreateView): model = Comment template_name = 'blog/comment_create_form.html' fields = ['content',] def get_context_data(self, **kwargs): context = super(BlogCommentCreate, self).get_context_data(**kwargs) context['blogpost'] = get_object_or_404(BlogPost, pk = self.kwargs['pk']) return context def form_valid(self, form): form.instance.comment_author = self.request.user form.instance.blogpost = get_object_or_404(BlogPost, self.kwargs['pk']) return super(BlogCommentCreate, self).form_valid(form) def get_success_url(self): return reverse('blogpost-detail', kwargs={'pk': self.kwargs['pk'],}) Here are the relevant url patterns. "comment_create" is the create page that is giving me issues with form submission, and "blogpost-detail" is where I'm trying to redirect to: urlpatterns = [ path('blog/<int:pk>', views.BlogPostDetailView.as_view(), name='blogpost-detail'), path('blog/<int:pk>/create', views.BlogCommentCreate.as_view(), name='comment_create') ] And finally, here is the comment model: class Comment(models.Model): date_created = models.DateField(blank=False, default = date.today) content = models.TextField(max_length=200) comment_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) blogpost = models.ForeignKey('BlogPost', on_delete=models.CASCADE) def __str__(self): return self.content Things I have tried: 1. Renaming parameters in my get_object_or_404 call that might overlap with built-in django keywords (as suggested in another thread here) 2. Renaming model fields and playing with capitalization … -
Multiple models with similar fields Django
Say I have 2 models: User Customer They both have the following SHARED fields: First name Last name Pin code Id They also have a shared save() method: def save(self, *args, **kwargs): if not self.pk: id = secrets.token_urlsafe(8) while User.objects.filter(id=id).count() != 0: id = secrets.token_urlsafe(8) self.id = id super(User, self).save(*args, **kwargs) How could I create a Base model that they can extend so that I don't need to define all of these things twice? Thanks!! -
What is the best way to download files from a server in Django?
I want to be able to download files from the server. I'm creating a Django text to speech app where the user will have the option to download the mp3 version of the text file. What is the best way to download mp3 files from the server in Django? -
Auth_Password_Validators syntax error - why am I receiving this error?
I have a model with standardised settings file, however when I run the debug server this returns with: Auth_Password_Validators syntax error Image I have checked that there are no grammatical errors or missing [] or missing {}. Code Please could you let me know how to resolve? -
How to correct virtualenv command output
I am learning to use virtual environments like and I realize that by using the use the virtualenv command: virtualenv env_dj_cuatro my virtual environment is created but at the same time it returns the following information at the end of its creation: diego@computer:~/Documentos/django$ virtualenv env_dj_cuatro created virtual environment CPython3.7.2.final.0-64 in 694ms creator CPython3Posix(dest=/home/diego/Documentos/django/env_dj_cuatro, clear=False, global=False) seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/home/diego/.local/share/virtualenv/seed-app-data/v1.0.1) activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator diego@computer:~/Documentos/django$ I understand that it is as a result of what has been done but I do not understand why it is shown since when reviewing the guide tutorials like this at no time does this information output occur How could I do to remove this information output? Thanks -
The serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'ilan_no'
Whenever I use values() method in queryset I get the error on title. If I use a simpler query in views.py, like Ilan.objects.all() It works fine. So, It seems that the error is due to the value() method. How can I fix it? BTW, ilan_no is a identifier number for each row. I have used ModelSerializers but nothing has changed. Django==2.1 djangorestframework==3.11.0 models.py: class Ilan(models.Model): ilan_no = models.IntegerField(unique=True, blank=True, null=True) url = models.CharField(unique=True, max_length=255, blank=True, null=True) add_date= models.DateField() origin = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=20, blank=True, null=True) district = models.CharField(max_length=30, blank=True, null=True) price = models.IntegerField(blank=True, null=True) serializers.py class IlanSerializer(serializers.Serializer): ilan_no = serializers.IntegerField() url = serializers.CharField() ilan_tarihi = serializers.DateField() origin = serializers.CharField() city = serializers.CharField() district = serializers.CharField() price = serializers.IntegerField() views.py class IlcePriceAndSizeDistributionListView(ListAPIView): queryset = Ilan.objects.annotate(year=ExtractYear('ilan_tarihi')).annotate(month=ExtractMonth('ilan_tarihi')).values( 'district', 'year', 'month').annotate(average_m2=Avg('m2_net')).annotate(average=Avg('price')).annotate(count=Count('ilan_no')).order_by('year', 'month') serializer_class = IlanSerializer Whole error: Got KeyError when attempting to get a value for field `ilan_no` on serializer `IlanSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'ilan_no'. Whole trace_back: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/charts/api/v1/ilce_price_size Django Version: 2.1 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'charts.apps.ChartsConfig', 'predictions.apps.PredictionsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', … -
form.is_valid is false and form.error doesn't
i want to submit a login this my login views def login(request): context = {} print("ok ok ok ok ok") user = request.user if user.is_authenticated: print("ok ici") return render(request, "login.html") form = LoginForm(request.POST or None) if request.POST: print("ok ici1") if form.is_valid(): email = form.POST['email'] password = form.POST['password'] user = authenticate(request, email=email, password=password) print(email) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") elif form.errors: print("errors") print(form.errors) form = AuthenticationForm() context['login_form'] = form return render(request, "login.html", context) and my form class for customuser in form.py class LoginForm(forms.ModelForm): class Meta: model=CustomUser fields ={'email','password'} my html is like this <form method="POST" action="{% url 'businessplan:login' %}"> {% csrf_token %} <h2> Vous ètes un Admin ?</h2> <div class="container" action > <input type="hidden" name="user_type" value="1"> <label for ="id_email"><b>Votre Email</b></label> <input id="id_email" type="text" placeholder="Entrer Votre Email" name="email" required> <label for ="id_password" ><b>Mot de Passe</b></label> <input id="id_password" type="password" placeholder="Entrer Votre Mot de passe" name="password" required> <button type="submit" >Login</button> <label> <input type="checkbox" checked="checked" name="remember"> souviens de moi </label> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">annuler</button> <span class="psw">oublier <a href="#">mot de passe?</a></span> </div> </form> when i submit my form.is_valid return false and the form.errors print (emailUser with this Email already exists.) … -
Neither `fab` (fabric2) nor `django-admin` are recognized commands in anaconda3 environment's Windows 10 cmd line
Upon returning to working on my Django project, I realize that neither django-admin nor fab are recognized commands anymore. I use anaconda3 distribution of Python and run everything i nthe (Anaconda3) shell. Both django and fabric2 were installed with pip and used to work normally a couple of months ago, when I last used them. The packages are present, the modules are imported uneventfully, e.g. the following works ok: import fabric2 from django.shortcuts import render I do not preclude that I inadvertently caused this myself, but all my attemtpts to find what caused it were futile. I did find django-admin and fab commands as .py files in anaconda3\Lib\site-packages folder, and site-packages is not in my %path% variable, but I can't find a clue on how to point to site-packages. Quick fixes as well as references to conceptual resources are very much appreciated. -
Is there a way to add dynamic text fields to django admin?
In the models i have i need to add a dynamic quantity of textfields, is there a way to achieve this? i also need to have them in order something like this: -
Where to find Cpanel python app console logs?
i'm trying to deploy Django app in cpanel after configuring settings and installing requirements i have this error i want the location of log file to check the error -
How to Change Input Forms for ManyToMany Field Django
Picture of Admin interface in Student Model Hello I am trying to change the input form for my admin interface for my ManyToMany Relationship for Students to their Held Licenses and Enrolled Courses. I wanna do checkboxes instead of cmd+clicking each element. Does anyone know how to change the input on the admin interfaces for models? class Student(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) date_of_birth = models.DateField( blank=True, null=True ) photo = models.ImageField( upload_to='users/%Y/%m/%d/', blank=True ) licenses_held = models.ManyToManyField( License, related_name="students" ) enrolled_courses = models.ManyToManyField( Syllabus, ) instructor = models.ForeignKey( to=Instructor, null=True, on_delete=models.SET_NULL, related_name="students" ) def __str__(self): return f'Username for user {self.user.username}' -
Local Database replication to solve simultanous writing and analytical tasks
I have a Django application that writes on the database on very short intervals. I have also a very complicated dashboard that fetches most of the data from the database every 10 seconds or so. When the dashboard refreshes however it blocks the database and I won't be able to write to the database at the same time. Any idea how to solve that? I was looking for local database replication. so I could have primary/secondary identical databases. I would use the first one to insert data and the second one for the dashboard. First of all, would that solve my problem since both of them are local databases? second, I need a way to start implementing this solution since in all the tutorials I have seen so far, the two databases would be on separate servers! But it seems obvious that there should be a non hacky solution for this. Django works of course with all database engines so I don't mind if the solution would be for sqlite, mysql, postgres or whatever. -
Display Objects Related Objects Reference In Django Admin
I have two classes with a one-to-many relationship: class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='students', default=None, null=True) In Django Teacher's Admin page (THIS-> /admin/users/teacher/ , NOT THIS -> /admin/users/teacher/1/change/) I'd like to either: List all a Teacher's students or Display the total number students a Teacher has I would usually add fields to this page using something like: class StudentAdmin(admin.ModelAdmin): list_display = ('user', 'teacher',) But as this is a one-to-many relationship and im accessing the 'many', im lost. Thank you. -
django on heroku: celery worker gets 403 forbidden when accessing s3 media to read and process media files
I'm really stuck on this one because I'm not sure where to start: My Django project allows users to upload a spreadsheet and the app then processes and aggregates the uploaded data. The file is uploaded to the MEDIA_URL using a standard form and Django model with a FileField. Once it's uploaded a celery worker accesses the file and processes it, writing the output to another model. This works fine locally, but is not working in production. I'm deploying to heroku, and using the cookiecutter-django project template. I've set up an s3 bucket and am using the django-storages library. The files upload without a problem - I can access and delete them in the Django admin, and also in the s3 bucket. However when the celery worker tries to read the file, I get an HTTP Error 403: Forbidden. I'm not sure how to approach this problem, because I am not sure which part of the stack contains my mistake. Could it be my tasks.py module, heroku:redis addon, or settings.py module? -
users can submit form only one time in django
I have made a simple Django Polling App where the user logs in and creates his/her Poll. Now I want that user shares that poll to his friends and ask them for vote and polling form should be submitted only one time by his anonymous friend. How can I do that? Should I filter users by their IP addresses? if yes then how can I do that? -
How to create new model with foreignkey in django
class Schedule(models.Model): name = models.CharField(max_length=50) class ScheduleDefinition(models.Model): schedule = models.ForeignKey(Schedule, on_delete=models.DO_NOTHING) config = JSONField(default=dict, blank=True) These are my models. I am trying to create a new ScheduleDefinition(The Schedule already exists and I know the ID I want to use for my foreign_key). I have a predefined Schedule id that I want to use, but it is not working.. Posting this body: { "schedule_id": 1, "config": { "CCC": "ccc" } } Error I get: null value in column "schedule_id" violates not-null constraint What am I doing wrong? When I create new ScheduleDefinition models, the Schedule model will already be created previously. I am never going to be creating new Schedule's when I create new ScheduleDefinition's. Serializer: class ScheduleSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ['id', 'name'] class ScheduleDefinitionSerializer(serializers.ModelSerializer): schedule = ScheduleSerializer(read_only=True, many=False) class Meta: model = ScheduleDefinition fields = ['schedule', 'config'] View: from rest_framework import generics from .models import Schedule, ScheduleDefinition from .serializers import ScheduleSerializer, ScheduleDefinitionSerializer class ScheduleList(generics.ListAPIView): queryset = Schedule.objects.all() serializer_class = ScheduleSerializer class ScheduleDefinitionList(generics.ListCreateAPIView): queryset = ScheduleDefinition.objects.all() serializer_class = ScheduleDefinitionSerializer class ScheduleDefinitionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ScheduleDefinition.objects.all() serializer_class = ScheduleDefinitionSerializer -
Send Django signup information to MailChimp
I would like to add each user that signs up on my django project to one of my mailchimp lists with a specific tag for that user. I want the user email to be sent to mailchimp specifically when a user signups. This is what I have in my views: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) API_KEY = '***' api = mailchimp.Mailchimp(API_KEY) api.lists.subscribe('email': email) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user The current code does not send the email of the person signing up to mailchimp -
Django: null value in column "id" violates not-null constraint after migrate database
I just make migration from my sqlite3 database to postgres using pgloader: pgloader sqlite://db.sqlite3 postgresql://... At first all looks like success, but now i have a problem with updating or creating models. When i trying to update something or create new objects with admin panel i getting an error: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, фывфывфыв, фывфывфыв, 2020-06-16, 2020-06-18, фывфыв, http://asdasd.ru/fsdfsdfsdf). For some reason now django not sending object id, and sending null istead. How can i fix it, and why did it happen? Some info about this table from pgadmin: CREATE TABLE public.pages_exhibitions ( id bigint NOT NULL, city text, name text, start_date date, end_date date, adress text, url text, CONSTRAINT idx_25075_pages_exhibitions_pkey PRIMARY KEY (id) ) WITH ( OIDS=FALSE ); ALTER TABLE public.pages_exhibitions OWNER TO polonika; model in django of this table: class Exhibitions(models.Model): city = models.CharField(max_length=200, blank=False, verbose_name='Город выставки') name = models.CharField(max_length=200, blank=False, verbose_name='Название выставки') start_date = models.DateField(blank=False, verbose_name='Дата начала выставки') end_date = models.DateField(blank=False, verbose_name='Дата окончания выставки') adress = models.CharField(max_length=500, blank=False, verbose_name='Адрес') url = models.URLField(max_length=500, blank=False, verbose_name='Ссылка', null=True) No varchar limits, no timestamps or anything. Did my migration on postgres was with errors? Or its ok? -
Django Google App Engine Upload files greater than 32mb
I have a Django Rest Framework Project that I've integrated with Django-Storages to upload files to GCS. Everything works locally. However, Google App Engine imposes a hard limit of 32mb on the size of each request, I cannot upload any files greater than this described limit. I looked into many posts here on StackOverflow and on the internet. Some of the solutions out listed the use of Blobstore API. However, I cannot find a way to integrate this into Django. Another solution describes the use of django-filetransfers but that plugin is obsolete. I would appreciate it if someone can point me towards an approach I can take to fixing this problem.