Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to pass a list to determine fields in a django form?
I have a list determined by an admin for which fields the user should be able to fill out. I have tried passing a subset of my fields into the fields variable in my forms.py but all the fields are still rendered in the template. forms.py class myForm(forms.ModelForm): myList = ['field1'] field1 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) field2 = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = myModel fields = myList Im just rendering my form with {{ form }} in my html. I dont get any errors but my app renders all the fields instead of just the ones in my list -
How to add a custom permission to a group in Django?
I think I have coded a custom permission in a model: class Foo(models.Model): class Meta: permissions = [('admin_foo', 'Can administrate foo'),] ... I ran the commands to store the permission: python manage.py makemigrations python manage.py migrate Then I have a decorator on my protected view: @permission_required('app.admin_foo') def myFooView(request): ... But when I go into the admin site the permission is not listed under "Available permissions". I was hoping to add the permission to the group "bar". How do I add this permission to the group "bar" programmatically? -
UnboundLocalError at /tweets local variable 'searchtext' referenced before assignment
@cache_control(no_cache=True, must_revalidate=True, no_store=True) @login_required(login_url='login') def tweetsPageView(request): twitter_client = TwitterClient() tweet_analyzer = TweetAnalyzer() if request.method == 'POST': searchform = Searchform(request.POST) if searchform.is_valid(): searchtext ='%s' %(searchform.cleaned_data['search']) searchform.save() api = twitter_client.get_twitter_client_api() tweets =api.user_timeline(screen_name =searchtext, count = 50 ) df = tweet_analyzer.tweet_to_data_frame(tweets) html_file =df.to_html() -
Can not connect to mysql database using Django
I'm trying to connect my Django app with MySQL and I have Successfully installed MySQL-connector-python-2.0.4 also. But after that whenever I run server same error message is showing. Here are my cmd ... Here is the full message showing -
'User' object is not iterable error django when using manytomanyfield
I created a Team model containing a manytomany field for the members. Now while trying to show the names of the teams the user is present in, I am getting a TypeError at /dashboard/ 'User' object is not iterable error. The codes are below: models.py class Team(models.Model): name = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(User, through='Member') def __str__(self): return f"Team: {self.name} created on {self.created_at}\nMember(s): {self.members.all()}" class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) def __str__(self): return f"User: {self.user} belongs to {self.team}" views.py @login_required(login_url="/login/") def dashboard(request): teams = Member.objects.filter(user__in=request.user) context = {} context = {"teams": teams return render(request, "users/dashboard.html", context) dashboard.html <p>Your teams:</p> <ul> {% for team in teams %} <li>{{ team.name }}</li> {% endfor %} </ul> {% endblock %} Can anyone please help me fix the error and understand what is causing it? -
Is a django annotate call lazy?
Django QuerySets are lazy and not evaluated until they are needed. Is this true for annotate as well? -
Can Django querysets filter both children and parents
In a Django REST framework application, I have the following models: class Experiment(models.Model): person = models.CharField(max_length=255, default=None, blank=True, null=True) class Level(models.Model): chamber = models.CharField(max_length=255, default=None, blank=True, null=True) experiment = models.ForeignKey(Experiment, related_name='levels', on_delete=models.CASCADE) class Run(models.Model): film = models.CharField(max_length=255) level = models.ForeignKey(Level, related_name='runs', on_delete=models.CASCADE) The user can request data by passing filters to the view. @api_view(['POST']) def get_filtered_data(request): if (request.method == 'POST'): query = Q() if request.data['people'] is not None and len(request.data['people']) > 0: query = query & Q(person__in=request.data['people']) if request.data['chambers'] is not None and len(request.data['chambers']) > 0: query = query & Q(levels__chamber__in=request.data['chambers']) if request.data['films'] is not None and len(request.data['films']) > 0: query = query & Q(levels__runs__film__in=request.data['films']) exp_qs = Experiment.objects.filter(query).distinct() serializer = ExperimentSerializer(exp_qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else : return Response('Not a valid API call', status=status.HTTP_400_BAD_REQUEST) I want to get all experiments that match a specific chamber and film, but I want the resulting Experiments to include only the filtered chambers and films. Right now it returns all of them Current Behavior With request: {"chambers":["2B"], "people":[], "films": ["Film1"]} Returns [ { "person": "me", "levels": [ { "chamber": "1A", runs: [ { "film": "Film1" }, { "film": "Film2" } ] }, { "chamber": "2B", runs: [ { "film": "Film1" }, { "film": "Film2" … -
Django-tenant-schemas how to Separate users
So I am new to multi-tenancy and am using django-tenant-schemas to be able to separate my tenants. thing is I want to be able to create users on a SHARED-APP that will be able to log in to every other tenant, and have users created within the TENANT_APP isolated to that schema. So goal is to have an admin panel that I can add users two that will be apart of every tenant and then have users who are created within the tenant only have access to said tenant. Right now my custom user model along with my tenant model and all models really resides in my core app. the other apps just hold serializer and views etc. what's the best method do go about getting what I want to be done. Thank you in advance for any help you can provide. settings.py SHARED_APPS = ( # Note here that auth and admin are in BOTH SHARED_APPS AND TENANT_APPS # Note that this right here will be your public schema <---- 'tenant_schemas', # mandatory, should always be before any django app 'core', # must list the app where your tenant model resides in 'django.contrib.contenttypes', # everything below here is optional … -
Django Redis Error unknown command 'BZPOPMIN'
I've installed Redis 3.0.54. Django is updated. I'm learning channels from the tutorial page https://channels.readthedocs.io/en/latest/tutorial/part_2.html This is my terminal window for redis-cli and redis server Image of Terminal System check identified no issues (0 silenced). August 06, 2020 - 16:04:58 Django version 3.1, using settings 'mysite.settings' Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. HTTP GET /chat/lobby/ 200 [0.02, 127.0.0.1:60841] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:60843] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:60843] Exception inside application: ERR unknown command 'BZPOPMIN' Traceback (most recent call last): File "C:\Users\\Envs\py2\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\\Envs\py2\lib\site-packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\\Envs\py2\lib\site-packages\channels\consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "C:\Users\\Envs\py2\lib\site-packages\channels\utils.py", line 58, in await_many_dispatch await task File "C:\Users\\Envs\py2\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch result = task.result() File "C:\Users\\Envs\py2\lib\site-packages\channels_redis\core.py", line 453, in receive real_channel File "C:\Users\\Envs\py2\lib\site-packages\channels_redis\core.py", line 508, in receive_single index, channel_key, timeout=self.brpop_timeout File "C:\Users\\Envs\py2\lib\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' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:60843] -
Cannot display a username within a Django project
I've been suffering to display a username on users' profile pages in my personal project. The following image is the view that I'd like to give. It has username at the top, and has a bio followed by the posts from the specific user. The view that I wanna give However the actual view that I get is this: The view that I get How can I add the username and bio to the user-posts page? Here are some files that are probably related to this issue: user_posts.html: <h1>{{ view.kwargs.username }}'s Profile</h1> <p>{{ user.bio }}</p> <h2 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'situmon:user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.published_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'situmon:post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} urls.py: from django.urls import path from . import views app_name = 'situmon' urlpatterns = [ path('user/<str:username>', views.UserPostListView.as_view(), name='user-posts'), ] views.py: from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from users.models import CustomUser from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post def … -
Elastic search condition
Hello i am confuse in condition in elastic search. Code works fine if parameter is not empty if parameter is not given to method how can i handle this bool query. def elastic_search(category=None): client = Elasticsearch(host="localhost", port=9200) query_all = { 'size': 10000, 'query': { "bool": { "filter": [ { "match": { "category": category } }] }, } } resp = client.search( index="my-index", body=query_all ) return resp -
Create an iterative counter in DJango template
I've checked a lot of other questions and I haven't seen my particular scenario really addressed and I've tried a lot of things out without success. What I have is a DJango for loop in my HTML code, and within the for loop is an if statement checking if each element from the list that is being looped through equals a certain value. If that is true, then an entry is created on the page. I need to dynamically print the element number (eg. entry 1 would display as 1. and entry 2 would display as 2.) The two best attempts I have made are: 1. <!-- this approach prints out 1 for each entry --> {% with counter=0 %} {% for q in questionnaire.questions %} {% if q.answer %} <div class="row"><h3> {{ counter|add:1 }}. {{ q.name }} </h3></div> <!-- some other code--> {% endif %} {% endfor %} {% endwith %} {% for q in questionnaire.questions %} {% if q.answer %} <div class="row"><h3> <span id="displayCount">0</span>. {{ q.name }} </h3></div> <!-- some other code--> {% endif %} {% endfor %} <script type="text/javascript"> var count = 0; var display = document.getElementById("displayCount"); count++; display.innerHTML = count; </script> Any help would be appreciated -
Can zoom API be used with django to transcribe meetings in real-time?
I would like to integrate the zoom API in a django web-app to transcribe meetings in real-time. I have tried running a Node server, but pythonanywhere does not support two servers at the same time. Will it be necessary to change the work model (django) or is there a way to do it? If is not possible, what should be the appropriate way to achieve it? -
heroku django Server Error (500) in only pages the reset is working
i am getting Server Error (500) on my heroku app , but the weird thing is i only get this error in a certain 3 pages here is my setteings.py DEBUG = False ALLOWED_HOSTS = ['scout-it.herokuapp.com','127.0.0.1'] #am using whitenoise for staticfiles MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] #database still working with sqlite3 STATIC_ROOT = os.path.join(BASE_DIR , 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR , 'static/images') the url for the 3 pages that are not working path('entreprise/', indexEntreprise ,name='indexEntreprise'), path('scout/<int:my_id>/', scout, name='scout'), path('candidat/', indexCandidat,name='indexCandidat'), my views (the other 2 are pretty much the same) def indexCandidat(request): return render(request,'Candidat/startCandidat.html') -
What is the diffrence between celery and celery beat in django
I want to know how to use celery beat in asynchronous mode so that there is high speed navigation of data using asynchronous mode in celery beat. -
Making different registration forms in Django?
I'm trying to create two different types of users in Django using AbstractUser. I've created two models that inherit from my AbstractUser model. How do I update the UserCreationForm so that it has a field for user type? -
Django relationship with User default auth model and another Model
I’m developing a web application where users can subscribe to different series of texts, that would be seen inside the system. I want to create a relationship between the User and the SeriesText, so I can grab the current logged user in the VIEW, and just return all of his subscriptions at the dashboard template. An user would be able to subscribe to as many series as he wants. I’m using the default User model from django.contrib.auth.models, and I’m not sure how to create this relationship. I read a lot and I think the correct usage here would be Many-to-many (is that correct?), so I tried this, using a pivot table/model called Subscriptions: from django.contrib.auth.models import User as BaseUserClass class User(BaseUserClass): subscriptions = models.ManyToManyField(SeriesText, through="Subscription") class SeriesText(models.Model): series_name = models.CharField(max_length=255) series_text = models.CharField(max_length=255) subbed_users = models.ManyToManyField(User, through="Subscription") class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) series = models.ForeignKey(SeriesText, on_delete=models.CASCADE) def subscribe(self, user_id, series_id): self.user = user_id self.series = series_id self.save() But that didn’t seem to work, I got errors even trying to use a User.objects.get(pk=1), don’t really know why. I’m really confused if I need to put the relationship both ways, like created models.ManyToMany on SeriesText model, and on an extended User … -
Django JSONField nested greater than operation
Here's the structure of the JSONField - data I have. data : { "animals" : [ "animal_id" : 2321, "legs" : [ { "name" : "front", "measured_at" : 1596740795.453353 }, { "name" : "back", "measured_at": 1596740795.453353 } ] ] } I need to find all records that match the following condition legs-name = "front" OR measured_at is greater than 6 hrs from now. I have tried the following six_hrs_ago = (datetime.utcnow() - timedelta(hours = 6)).timestamp() obj = Model.objects.filter(data__has_key='animals'). filter(Q(data__animals__legs__name="front") | Q(data__animals__legs__measured_at__gt = six_hrs_ago)))) This doesn't work, and it fetches no record. I also tried to just filter the records with legs - name - front, that doesn't work either obj = Model.objects.filter(data__animals__contains=[{'legs': [{"name": "front"}]}]) Any ideas are appreciated. -
Optimal model design for historical data tracking
How to construct relationships between these two models? Company stores data about a company: class Company(models.Model): """Company related data""" name = models.CharField(max_length=120) abbrev = models.CharField(max_length=5) founded = models.IntegerField(null=False) country = models.CharField(max_length=60) Meanwhile StockQuote tracks history of shares' prices: class StockQuote(models.Model): """Price history""" fetch_date = models.DateField(default=timezone.now()) business_day_date = models.DateField(default=timezone.now()) price = models.CharField(max_length=8, default='0.00') Considering that each of StockQuote records can be assigned just one Company, how should these models be connected with relationships so that it would be straightforward to display all prices listed, querying just the Company model (API endpoint)? -
DRF Custom Password Serializer `create()` must be implemented
When try to Update password it required create() How to add it in the right way? Serializer My serilizer class UserPasswordChangeSerializer(serializers.Serializer): old_password = serializers.CharField() password = serializers.CharField() class Meta: model = User fields = ('old_password', 'password') def validate(self, data): if not self.context['request'].user.check_password( data.get('old_password')): raise serializers.ValidationError( {'old_password': 'Wrong password.'}) return data def update(self, instance, validated_data): instance.set_password(validated_data['password']) return super().update(instance) View My action view @action(methods=['post'], detail=True) def change_password(self, request, *args, **kwargs): user = self.get_object() user.serializer = UserPasswordChangeSerializer(data=request.data, context={'request': request}) user.serializer.is_valid(raise_exception=True) user.serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) -
django: OperationalError at /handle_contact
I have used forms for my contact page. When I fill the form and click on submit option in my contact page I get error which says Operational Error at /handle_contact no such table: app_contact -
How to implement session timeout - Angular - Django app integration with Azure AD
Overview - I am working on a solution having UI built in angular and backend in django. I want to implement authentication and authorization using Azure AD. At UI, I have made use of @azure/msal-angular, which acquires access tokens directly from azure each time a backend enpoint is hit. Problem 1 - Access tokens are acquired in the background and never expire unless user logs out. Is there a way to log user out after certain period of time/inactivity? Problem 2 - @azure/msal-angular uses implicit grant flow which receives user tokens in url fragments, which seems not secure. Is auth code a better way to go about it? -
Django query- annotating with one of two fields (depending on what exists)
I have the following models, that describe employees on a job: class Job(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) # Several other Job related fields class CrewAssignment(models.Model): job = models.ForeignKey(Job, on_delete=models.PROTECT, related_name='crew_assignments') user = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField() # Several other crew related fields class SubAssignment(models.Model): job = models.ForeignKey(Job, on_delete=models.PROTECT, related_name='crew_assignments') user = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField() # Several other sub related fields Given a User u, and a Date d, I am trying to assemble a query that will return all Job entities that u was either a CrewAssignment or SubAssignment on with a date on or after d, annotated with the date. For example, if d is 2020-08-06, and the user has the following assignments: CrewAssignment | Job id 1 | 2020-08-06 SubAssignment | Job id 2 | 2020-08-06 CrewAssignment | Job id 1 | 2020-08-07 CrewAssignment | Job id 3 | 2020-08-07 SubAssignment | Job id 3 | 2020-08-07 Things to note- the user was on Job 1 on multiple days (so there should be an entry for each day), and the user was a CrewAssignment and a SubAssignment for Job 3 on the same day, which should only create one entry. I would like … -
'Request' object has no attribute 'get' error while getting the api url
In this when I got to the validat_phone URL and I post the phone_number in URL, it returns the error 'Request' object has no attribute 'get', I don't know how to fix the error. Is there is a way to fix the error? Here is my view.py class ValidatePhoneSendOTP(APIView): def post(self, request, *args, **kwargs): phone_number = request.data.get('phone', False) if phone_number: phone = str(phone_number) user = User.objects.filter(phone__iexact = phone) if user.exists(): return Response({ 'status' : False, 'status' : 'Phone number is already exists.' }) else: key = send_otp(phone) if key: PhoneOTP.objects.create( phone = phone, otp = key, ) link = f'My--api-url - {phone}+ {key}' test = request.get(link) return test; return Response({ 'status' : True, 'detail' : 'OTP sent successfully.' }) else: return Response({ 'status' : False, 'detail' : 'Sending otp error.' }) else: return Response({ 'status' : False, 'detail' : 'Phone number is not given in post request.' }) def send_otp(phone): if phone: key = random.randint(999,9999) print(key) return key else: return False -
How can I use django to display data on a website without reloading the whole page
i use django to render a page. If a user now requests information, I would like to load it from the database and display it on the website. It's actually quite simple. I get the information in Django and I find the data in the database. BUT how do I get them back to the user. I don't want to re-render the whole page (it could) I just want to re-render part of the website without having to reload the whole page. Is there a trick? I might have thought of sending the data back via AJAX and adjusting the page using js, but isn't there a more elegant option from django and is AJAX still up to date? had heard that this should no longer be used ...