Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get Subclass on ManyToManyField Django
Here is my Django model schema: Employee: - Name: CharField - Email: EmailField Software Engineer (extends Employee): - Favorite language: CharField Janitor (extends Employee): - Cleaning location: CharField Team: - Name: CharField - Employees: ManyToManyField with Employee The problem occurs with the ManyToManyField in the Team model. When I try to access a team's employees: team = Team.objects.get(id=1) employees = team.employees.all() The employees variable is a QuerySet of Employee models, not of Software Engineer and Janitor models. How can I retain the subclass? I looked into InheritanceManager, but can't figure it out. Anything helps! Thanks! -
Why isn't AWS Elasticache caching in Django app
I am running a Django application through AWS ElasticBeanstalk and trying to connect it to an AWS ElastiCache Memcached instance. The cache works fine locally (using 127.0.0.1:11211) but is not caching in the ElasticBeanstalk environment. I'm defining the cache in settings.py as follows: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': os.environ.get('CACHE_LOCATION','127.0.0.1:11211'), } } In my ElasticBeanstalk configuration I have a variable CACHE_LOCATION = application-name.abcdef.ghi.euw2.cache.amazonaws.com:11211 To check the cache is working I have the following log within my code logger.warning(f"Cache for {query} is {cache.get(slugify(query))} at {datetime.datetime.now()}") The result is always None when running on ElasticBeanstalk but works locally What is wrong with my setup? -
data is not saving mailvalidation in models
I am creating signup page with email verification but I am getting type error mailvalidation() got an unexpected keyword argument 'user_id' views.py def signup(request): if request.method=='POST': username=request.POST['username'] email=request.POST['email'] password=request.POST['password'] cpassword=request.POST['cpassword'] userdetails(name=username,email=email,password=password).save() user = userdetails.objects.get(email=email) token = default_token_generator.make_token(user) #print(user.id) #print(user.email) #print(user.name) #print(token) mailvalidation(user_id=user.id, user_email=user.email, user_name=user.name, key=token).save() sendmail(email, token) return HttpResponse('We have sent a email verification please check your email') return render(request,'credentials/register.html') models.py class userdetails(models.Model): name=models.CharField(max_length=50) email=models.CharField(max_length=50) password=models.CharField(max_length=20) valid_email=models.IntegerField(default=0) last_login=models.DateTimeField(default=today) class Meta: db_table='user_details' class mailvalidation(models.Model): user_id=models.IntegerField(default=0) user_email=models.EmailField(max_length=100) user_name=models.CharField(max_length=100) key=models.TextField() class Meta: db_table='mail_validation' I am getting a error -
communciation error between channely layer and Redis
I installed Redis version 6.0.6 in Linux I am following this tutorial on Django channels, and I ran the following code: >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel',{'type':'hello'}) >>> async_to_sync(channel_layer.receive)('test_channel') and I got the error like this Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/peacekim/chat/venv/lib/python3.6/site-packages/asgiref/sync.py", line 139, in __call__ return call_result.result() File "/usr/lib/python3.6/concurrent/futures/_base.py", line 425, in result return self.__get_result() File "/usr/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/home/peacekim/chat/venv/lib/python3.6/site-packages/asgiref/sync.py", line 204, in main_wrap result = await self.awaitable(*args, **kwargs) File "/home/peacekim/chat/venv/lib/python3.6/site-packages/channels_redis/core.py", line 485, in receive return (await self.receive_single(channel))[1] File "/home/peacekim/chat/venv/lib/python3.6/site-packages/channels_redis/core.py", line 508, in receive_single index, channel_key, timeout=self.brpop_timeout File "/home/peacekim/chat/venv/lib/python3.6/site-packages/channels_redis/core.py", line 345, in _brpop_with_clean result = await connection.bzpopmin(channel, timeout=timeout) aioredis.errors.ReplyError: ERR unknown command 'BZPOPMIN' How can I solve this error.please... -
How to send array of file objects through ajax with form serialize()?
I am trying send my form fields along with an array of file objects through ajax call. I used the answer from this question to add/choose multiple files. This answer stores files in an array and sends the files as FormData Object, But in my code i have other forms fields also. I am sending those data from ajax using form.serialize() method. Now i have to send the array of file object together with my all the old data. So i tried this, $('#myform').submit(function () { var formData = new FormData(); files.forEach(file => { formData.append('file', file); }); $.ajax({ type: "POST", url: url, data: form.serialize() + "&filedata=" + formData, ... ... }) } I am using django in the backend, i receive like this, request.POST.get('filedata') But using this i receive filedata field as a string "[object FormData]".My question is how to send FormData together with form.serialize() This is my html: <form method="POST" action="/" id="myform"> <input type="text" name="name"/> <input id="myInput" type="file" name="files" multiple style="display:none" /> <button id="myButton" type="button">Add Files</button> <!-- <button id="mySubmitButton" type="button">Upload Files</button> this button is not required as i want upload files on clicking submit --> <div id="myFiles"></div> <input type="submit" /> </form> I don't want to upload files on clicking … -
Django allauth Social application accessing extra data
I have added Google authentication for my Django web application using allauth package. I want to access the extra data(shown in field 4(Extra data) of social account users I have tried this but, I do not import SocialAccount(I dont know what module/package does it belongs to). data=SocialAccount.objects.get(user=request.user).extra_data Please let me know which module should I import to use SocialAccount or tell me other way how can I access extra data. -
Django group by Month
Models class Link(models.Model): url = models.URLField("URL", max_length=500) key = models.CharField("Key", max_length=100, unique=True, primary_key=True, blank=True) def __str__(self): return self.key class Statistic(models.Model): link = models.ForeignKey(Link, on_delete=models.CASCADE) date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.link.key Views def statistic(request): data = dict() if request.method == "POST": key = request.POST.get("key") link = Link.objects.filter(key=key) if link.exists(): # analyze = Statistic.objects.filter(link=link[0]) data["statistic"] = True return render(request, "statistic.html", data) What should I do to get the output ["id_month or Month": count * 12 Months] with this line: analyze = Statistic.objects.filter(link=link[0]) -
Assign Same Value to Django Rest Framework
I faced a problem while using Django with React. I am using Django Rest Framework to serialize objects but then I faced an error in React's frontend saying that each object needs a "key" property. I have been wondering if it's possible, seeing that there is a default ID, to add another field in Rest Framework that has the same value as Django model's primary key field? Putting into context, let's say I have this: # models.py class Todo(models.Model): # the id field is auto-generated by django title = models.CharField(_('title'), max_length=50) desc = models.TextField(_('description'), max_length=500, blank=True) created = models.DateTimeField(_('date created'), auto_now_add=True) def __str__(self): return self.title Is it possible if I can do something like this below? # serializers.py class TodoSerializer(serializers.ModelSerializer): # assign the value of id to a new field named "key" <-- this action!!! title = serializers.CharField(max_length=50, trim_whitespace=True) desc = serializers.CharField(max_length=500, allow_blank=True) created = serializers.DateTimeField() class Meta: model = Todo fields = ['id', 'key', 'title', 'desc', 'level', 'created'] The reason that I want to do this is that React recognizes the "key" property instead of "id", which lead me to this problem. At the same time, I don't want to discard the "id" column as migrating the data will … -
programmatic method to get a list of "published" images in wagtail?
I'm playing with wagtail and considering using it for a site. In the process I'm looking into serving the site through a combination of django-storages and wagtail-bakery. At the moment I'm trying to get the images served and want to obtain a list of wagtail images that are considered "published". I looked at the properties of the Image model, but I don't see anything that sticks out as a way to define if the Image is published or not. Is there a way to determine if an Image is published or not, or get a list of Images belonging to publshed pages? >>> from wagtail.images.models import Image >>> >>> img = Image.objects.all()[0] >>> for i in sorted(dir(img)): ... print(i) ... DoesNotExist Meta MultipleObjectsReturned __class__ __delattr__ __dict__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __getstate__ __gt__ __hash__ __init__ __init_subclass__ __le__ __lt__ __module__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __setstate__ __sizeof__ __str__ __subclasshook__ __weakref__ _check_column_name_clashes _check_constraints _check_field_name_clashes _check_fields _check_id_field _check_index_together _check_indexes _check_local_fields _check_long_column_names _check_m2m_through_same_relationship _check_managers _check_model _check_model_name_db_lookup_clashes _check_ordering _check_property_name_related_field_accessor_clashes _check_search_fields _check_single_primary_key _check_swappable _check_unique_together _do_insert _do_update _get_FIELD_display _get_next_or_previous_by_FIELD _get_next_or_previous_in_order _get_pk_val _get_unique_checks _has_field _meta _perform_date_checks _perform_unique_checks _save_parents _save_table _set_file_hash _set_pk_val _state admin_form_fields check clean clean_fields collection collection_id created_at date_error_message default_alt_text delete file file_hash file_size filename … -
How to chat with other devices as well (channels)?
i am a beginner in django and right now studying about django-channels. I have implemented chat application successfully but obviously i cannot test it on other devices. using 127.0.0.1:8000 i want to connect my phone so that i can chat over it. Please help me how to chat with other devices ? -
ModuleNotFoundError: No module named 'project.models'
project details: To Add Authentication to Your App with Flask-Login init.py: from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager # init SQLAlchemy so we can use it later in our models db = SQLAlchemy() def create_app(): app = Flask(__name__) app.config['SECRET_KEY'] = 'secret-key-goes-here' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' db.init_app(app) login_manager = LoginManager() login_manager.login_view = 'auth.login' login_manager.init_app(app) from .models import User @login_manager.user_loader def load_user(user_id): # since the user_id is just the primary key of our user table, use it in the query for the user return User.query.get(int(user_id)) # blueprint for auth routes in our app from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint) # blueprint for non-auth parts of app from .main import main as main_blueprint app.register_blueprint(main_blueprint) return app auth.py: from flask import Blueprint, render_template, redirect, url_for, request, flash from werkzeug.security import generate_password_hash, check_password_hash from flask_login import login_user, logout_user, login_required from .models import User from . import db auth = Blueprint('auth', __name__) @auth.route('/login', methods=['POST']) def login_post(): email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False login_user(user, remember=remember) user = User.query.filter_by(email=email).first() # check if the user actually exists # take the user-supplied password, hash it, and compare it to the hashed password in the database if not user … -
Fastest way to check for membership using Django ORM
Let's say I have the following two models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) And I have the following instances of these models: pub = Publication.objects.first() article = Article.objects.first() What's the FASTEST way to check membership of a Publication in an Article? I can think of a few ways: # Option 1 pub in article.publications.all() # True # Option 2 pub.pk in article.publications.values_list("pk", flat=True) # True # Option 3 article.publications.filter(pk=pub.pk).exists() # True I would guess Option 3 is fastest. Am I correct? Are there any other queries that would be faster? -
Why is only one of my nested object validated with Django Rest Framework?
I'm building an endpoint to which someone can send some nested data. One of the nested objects is validated, but others are not and I'm confused why this is. These are my models: class Publication(models.Model): type = models.CharField(max_length=255) reference = models.CharField(max_length=255) class Measurement(models.Model): publication = models.ForeignKey('Publication', on_delete=models.CASCADE) value = models.IntegerField() class Location(models.Model): measurement = models.ForeignKey('Measurement', on_delete=models.CASCADE) location_number = models.IntegerField() class TravelTime(models.Model): measurement = models.ForeignKey('Measurement', on_delete=models.CASCADE) type = models.CharField(max_length=255) estimation = models.CharField(max_length=255) The Viewset looks like this: class PublicationViewSet(viewsets.ModelViewSet): serializer_class = PublicationSerializer serializer_detail_class = PublicationSerializer def create(self, request, *args, **kwargs): publication_serializer = PublicationSerializer(data=restructure_data(request.data)) publication_serializer.is_valid(raise_exception=True) ## THIS LINE PRINTS dict_keys(['value', 'locations', 'travel_times']) print(publication_serializer.initial_data['site_measurements'][0].keys()) ## THIS LINE PRINTS odict_keys(['value', 'locations']) print(publication_serializer.validated_data['site_measurements'][0].keys()) publication_serializer.save() return Response("", status=status.HTTP_201_CREATED) In the create() method you see two prints with a comment saying what they print out. As you can see, the second one is missing the 'travel_times' item. How can it be that the locations key is still in the validated_data, but the travel_times has disappeared? -
How can I fix the issue: No module named 'multiselectfield'?
I installed django-multiselectfield successfully but it doesn't work. these steps I did to run the lib: pip3 install django-multiselectfield INSTALLED_APPS = [ #..., 'multiselectfield' ] also, I did create requirements.txt file but the error didn't go, How can I install this lib successfully models.py from multiselectfield import MultiSelectField class PlayerName(models.Model): match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='player_name') name = models.CharField(max_length=255) def __str__(self): return self.name PLAYERS = PlayerName.objects.values_list('name', 'name') class PlayerBox(models.Model): player_name = models.ForeignKey(PlayerName, on_delete=models.CASCADE, related_name='player_box') name = MultiSelectField(choices=PLAYERS) -
check start time without system time
I have a model with DateTime information . I want to allow posting data to an API only after the start time .This could be done by checking the time against timezone.now(). The problem is anyone can change the system time in their machine and proceed to the API . I want to block this hack .How can i check if it is start_time without considering the time set in their system? Also i want to display a timer on the client side. class Module(models.Model): start_time = models.DateTimeField(default=None, null=False, blank=False) -
Trying to Create Navigation Bar in Django, there might be some problem with bootstrap, but unable to figure out
'''' {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'books/style.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384- 9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'books:index' %}">The BookStore </a> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span>&nbsp; Books </a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>&nbsp; Add Book </a> </li> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span>&nbsp; Logout </a> </li> '''' When I try to execute this code, navigation bar is not displayed. Other Options such as "Books"/"Add Book"/"Logout" is also not displayed. I believe that there might be some problem when I tried to copy Bootstrap CDN. Although, I have tried all the option, the problem persists. -
how to get month and year (Jan, 2020) from queryset object of datetimefield in django python?
I have a table with field id, Img, UploadDate and many more fields. In views.py, I want to fetch id, Img and UploadDate but in UploadDate field(which is of type datetimefield) i want to get only month and year how can i get it . I have tried: collectMonthYear = ImgDetails.objects.filter(User_id=user.id,Valid=True).annotate(Date=('UploadDate').strftime("%m-%Y")).values('id','Img','Date') this raise error: 'str' object has no attribute 'strftime' can anyone help me with that. how can i fetch the data with 'UploadDate' field having month and year only. -
Django Rest Framework best practice for making object with generic relationship
I'm creating django models for blogging. Here's the thing I've made. class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField() images = GenericRelation(TaggedImage) class TaggedImage(models.Model): image = models.ImageField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=32) content_object = GenericForeignKey('content_type', 'object_id') I'm using django rest framework for building rest API server. I wanted to create Post with image so I created PostSerializer like this. class PostSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.email') image = serializers.ImageField(write_only=True) class Meta: model = Post fields = '__all__' def create(self, validated_data): image = validated_data.pop('image') instance = Post.objects.create(**validated_data) image_instance, created = TaggedImage.objects.create(image=image, content_object=Post) return instance I wonder if I followed best practice or there is better way to do so. Thanks! Here's the remainder of code just in case. class PostListCreate(generics.ListCreateAPIView): Post.objects.all() serializer_class = PostSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) -
please help AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64
I am trying to deploy a Django project and get error AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 I have gdal=3.0.4 and dockerfile please heck the issue FROM gcr.io/google-appengine/python RUN apt-get update && apt-get install -y \ binutils \ gdal-bin \ python-gdal # Create a virtualenv for dependencies. This isolates these packages from # system-level packages. RUN virtualenv /env -p python3.7 # Setting these environment variables are the same as running # source /env/bin/activate. ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH # Copy the application's requirements.txt and run pip to install all # dependencies into the virtualenv. ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt # Add the application source code. ADD . /app # Run a WSGI server to serve the application. gunicorn must be declared as # a dependency in requirements.txt. entrypoint gunicorn -b :$PORT tiwari.wsgi -
django change form field
I'm working on a function when the customer enters the scheduled date and updates the form the status of the form changes to Scheduled. However I'm unable to change it back to another status without deleting the scheduled date.I want my fucntion to be able to change the status without deleting scheduled_date views.py def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): order = form.save(commit=False) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None: order.status = 'Scheduled' order.save() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) class Order(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) = models.DateField(max_length=100, null=True) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Shipped','Shipped'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") -
Django Form not showing up on template; only the button
I've just about tried everything to get this form to show up. What I am trying to achieve is to have a comment box appear to submit comments to a post. I managed to get it working in a test environment but when I put it into my actual site the form fields does not appear; just the submit button. Model and admin side work fine, just seems to be the view/html side. I suspect it could be the views.py file with all the classes are affecting it. Any input would be greatly appreciated! views.py from django.shortcuts import render from django.contrib import messages # Create your views here. from django.contrib.auth.mixins import (LoginRequiredMixin,PermissionRequiredMixin) from django.urls import reverse from django.views import generic from django.shortcuts import get_object_or_404 from groups.models import Group, Comment from . import models from django.http import HttpResponseRedirect, HttpResponse from braces.views import SelectRelatedMixin from .forms import CommentForm from . import forms from django.views.generic import TemplateView def form_name_view(request): comment_form = CommentForm() if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment_form.save() return render(request, 'groups/group_detail.html', {'comment_form': comment_form}) class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('title','area','description') model = Group def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): … -
How do I use django allauth for a provider that is not supported?
I'm trying to use zoom Oauth in my web app, but as it's unsupported by allauth, I'm not sure how to proceed. -
How can I pass data into a modal using Bootstrap?
I imagine it's not too hard. I need data from outside the modal to use as an input in the modal. -
objects model manager not changing when assigned to a class from Manager.from_queryset
I've a weird issue going on, I've searched here and there're zero questions on this. This is my UserQuerySet class UserQuerySet(models.QuerySet): def create(self, **kwargs): with transaction.atomic(): password = kwargs.pop('password') kwargs['username'] = kwargs['username'].lower() user = self.model(**kwargs) user.set_password(password) Profile.objects.create(user=user, **user.related_profile_args) user.save(force_insert=True) del user.related_profile_args return user def subscribed(self): """ Return subscribed users """ and I'm building a Manager from this like class UserManager(BaseUserManager.from_queryset(UserQuerySet)): def get_by_natural_key(self, username): return self.get(**{ self.model.USERNAME_FIELD: username.lower() }) def create_superuser(self, **kwargs): if kwargs['password'] is None: raise TypeError('Superuser must have a password.') user = self.create(**kwargs, first_name='ADMIN', last_name='ACC', phone_number='XXXXXXXXX') user.is_superuser = True user.is_staff = True user.save() return user and this is my User class class User(AbstractBaseUser): ... objects = UserManager The problem is, the objects is still django.db.models.Manager, it didn't change when I printed it, this also shows an error when I create a superuser which is the manager lacks some attributes like get_by_natural_key which clearly makes sense because it's models.Manager as returned by User._meta.default_manager.__class__. I can solve this by moving everything that's in UserManager inside the UserQuerySet and changing objects to UserQuerySet.as_manager(). But I want to know why this doesn't work. I've read the source code of from_queryset and I got the idea that it just copies the methods from the … -
INVALID_CLIENT: Invalid redirect URI (django + spotipy)
Trying to use the spotipy python library and integrating it into my django application however am getting an INVALID_CLIENT: Invalid redirect URI error once the user has logged into their spotify account. structure of my project folder: project/ manage.py db.sqlite3 Songify/ __init__.py settings.py urls.py wsgi.py SongifyApp/ migrations/ __init__.py __init__.py admin.py templates/ after_sign_in.html home.html sign_in.html apps.py models.py tests.py urls.py views.py the urls.py file in the SongifyApp folder are as follows: from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('sign-in', views.sign_in, name='sign-in'), path('after-sign-in', views.after_sign_in, name='after_sign_in'), path('callback', views.callback,name='callback'), ] In my spotify dashboard where my application sits i have set the Redirect URIs to https://localhost:8000/callback and at the top of my views.py file have defined the SPOTIPY_REDIRECT_URI to the same thing So the following works, on the home page i click the sign in link which directs me to the authorize page at spotify and type in my credentials however then i get the INVALID_CLIENT: Invalid redirect URI error. I've searched for hours and tried all the possible fixes however none seem to fix it so my last resort is to ask here, I am new to django so sorry if i have made a stupid …