Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i have misconception about this loop in python
i have a list of items and based on it, i would like to print some pieces of information so,a for loop over two items for example, if one on these two items found in somewhere i would like to share them the same print statement, else this, i would like to print a shared statement also, see example please: book = 'long text' a = ['im eating', 'im drinking'] for item in a: if item in book: print('something once')#just one item found to Be satisfied then break the code break else: print('the opposite somthing once')#if the two-items not found print one sentence exprime this once help plz -
How to programically redirect calls to files in my Static folder?
I have rating stars images in my Static folder: static MyApp 1.0-stars.svg 1.5-stars.svg 2.0-stars.svg 2.5-stars.svg ... I will prepend the rating pulled from the model before the image file when calling the image. But some ratings may be 1.6 or 1.7, which I would want to redirect to the appropriate rounded-to-0.5 star rating image (1.5-stars.svg in the former case of 1.6 and 1.7 stars). Is there a way to do this programmatically in Django, if so where exactly (in urls.py, in views.py, in models.py)? Or should I use JS to do the math before calling the correct image file? -
Permissions to GET and POST
I'm new to Django, so maybe the issue is easy to solve. I have App News and APP users. As I have to allow GET for everyone, however POST is only for the token. -
Pass QuerySet in Django url
I'm looking to pass a list as the queryset parameter to a Django ListView. I know you can do this by overwriting the get_queryset method but ideally I would like to avoid this. The reason is, I am referring from another view and already have the queryset I need so I don't want to run the same query twice. Currently I am linking to my view as follows: <a href="{url 'lab_work:project_list_ongoing' %}?projects={{active}}">{{active|length}</a> active is the prepopulated list I want to use as the queryset. My view looks as follows: class ProjectListOngoing(ListView): template_name = "<name of my template>" model = Project context_object_name = "projects" paginate_by def dispatch(self, request, *args, **kwargs): self.projects = request.GET.get('projects', []) return super().dispatch(request, *args, **kwargs) def get_queryset(self): return self.projects This does seem to populate the correct queryset however the primary keys are blank for some reason. I have the following in my template: {% for project in projects %} <li><a href="{% url 'lab_work:project_detail' pk=project.pk %}"></a></li> {% endfor %} And I get the following error: Reverse for 'project_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['project/(?P<pk>\\d+)/$'] -
ERROR Invalid option specification - AWS Elasticbeanstalk - Django
I am trying to set up my Django project using the AWS CLI service but I get the following error ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting. I work on Windows and follow these instructions: https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/. This is from 2017 and I have already made some adjustments, as the AWS services is constantly being updated But now something seems to be wrong in the python.config file. Maybe the name of the command has been changed. I couldn't find much about that anyway. This is what my python.config file looks like: container_commands: 01_migrate: command: "python manage.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "Whisky.settings" PYTHONPATH: "$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "Whisky/wsgi.py" StaticFiles: "/static/=www/static/" packages: yum: postgresql95-devel: [] I hope you can help me -
Removing one-to-many related models using Django
I have the below models defined in Django and am looking for a way to delete all the cookies associated with a site. models.py class Site(models.Model): created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT) class Cookie(models.Model): name = models.TextField() value = models.TextField(blank=True, null=True) host = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='cookies') I tried the following but got an error: site_object.cookies.delete() AttributeError: 'RelatedManager' object has no attribute 'delete' -
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)?