Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass value to view from form
Good day. The challenge is: Create a form that will change the parameters of the model fields, based on user input. My logic is this. I tried to create a form for entering changes: class RefDataForm(forms.Form): NODE_ID_LIST=[('YE102_4G','YE102_4G'),('AG001_4G','AG001_4G')] ANRFUNC_PARAM_LIST=[('zzztemporary7','zzztemporary7'),('zzztemporary2','zzztemporary2')] change_id = forms.CharField(label='Node ID for Change', widget=forms.Select(choices=NODE_ID_LIST)) change_param_name = forms.CharField(label='Parameter name for Change', widget=forms.Select(choices=ANRFUNC_PARAM_LIST)) value = forms.CharField(label='Value') Next in view.py, I'm trying to create a .update command that should accept changes. def ref_test(request, template_name ='ref_test.html'): if request.method == 'POST': test=RefDataForm(request.POST) if test.is_valid(): change_id = request.POST['change_id'] change_param_name = request.POST['change_param_name'] change_value = request.POST['value'] update_form = Ran4GRfAnrfunction.objects.filter(pk__in=change_id).update(change_param_name=change_value) else: test=RefDataForm() return render(request, template_name, {'test':test}) My html is : <form method="post"> {% csrf_token %} {{ test.change_id }} {{ test.change_param_name }} {{ test.value }} <button type="submit">Search</button> </form> However, I get an error *Ran4GRfAnrfunction has no field named 'change_param_name' * How do I pass field_name through a form? In manage.py shell, I tried to do it - from dumper.models import * change_id = ['AG001_4G', 'AG002_4G'] change_value = ('Okay') change_param_name('zzztemporary2') Ran4GRfAnrfunction.objects.filter (pk__in = change_id) .update (zzztemporary2 = change_value) How do I pass the value of change_param to .update ? -
Writing a django migration manually with setting a variable on condition
I need to write a django migration which changes an attribute value depending on a condition. So I have is_admin and is_staff attributes, and now I am substituting the with the new attribute role. I need to set role = admin if the old is_admin was true. Similarly, I need to set role = staff if the old is_staff was true. How can I do that with django data migrations? I need something like if is_admin: role = "admin" if is_staff: role = "staff" -
French translation raises "ValueError('invalid token in plural form: %s' % value)"
I want to handle a french version of my website. I use Django 2.2 with i18n and I already set locale variables in settings.py. # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ('it', _('Italian')), ('es', _('Spanish')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True When I use ./manage.py makemessages -l fr, I correctly have a django.po french file but after ./manage.py compilemessages -l fr the server crashes with the following error (trimed) : File "/usr/lib/python3.7/gettext.py", line 93, in _tokenize raise ValueError('invalid token in plural form: %s' % value) ValueError: invalid token in plural form: EXPRESSION``` -
Uploaded Files get overwritten in Dropbox
I am trying to upload users files to DropBox in Django. When I use the built in 'open()' function, it throws the following exception: expected str, bytes or os.PathLike object, not TemporaryUploadedFile When I don't, the file gets uploaded successfully but is blank (write mode). UPLOAD HANDLER: def upload_handler(DOC, PATH): dbx = dropbox.Dropbox(settings.DROPBOX_APP_ACCESS_TOKEN) with open(DOC, 'rb') as f: dbx.files_upload(f.read(), PATH) dbx.sharing_create_shared_link_with_settings(PATH) How do I upload files or pass a mode to DropBox API without it being overwritten? -
How do I link JSON files within AJAX with Django?
I have a Django app and within it I'm using a template HTML page that utilizes a Javascript library called Cytoscape (allows you to create graphs with nodes and edges). I have everything set up with regards to templates and static files (the CSS and basic JS functions are working), however the one thing I'm having issues with is the Ajax functions within my main javascript file. These Ajax functions are responsible for displaying the graphs from JSON files (see code below as to how), and they work fine locally without Django. But as soon as I try to incorporate the server-side implementation, the functions can no longer read these files and I don't know how to fix this. I've attempted to copy over the JSON files into various directories (but I'm still running into a 404 not found error: "Not found filldata/undefined.json", (where filldata is my app) presumably because this URL has not been set up on the server-side. function onUpload() { var filename = $('input[type=file]').val().split('\\').pop(); var layoutPadding = 50; var aniDur = 500; var easing = 'linear'; var cy; if (upload_true) { var graphP = $.ajax({ url: filename, type: 'GET', dataType: 'json' }); var styleP = $.ajax({ url: … -
Migration references dynamic storage inconsistent
I want specific field in model to use either S3 storage (if settings has AWS_ACCESS_KEY_ID) or fallback to default_storage. I'm using django-storages. To implement this, in models.py: from django.db import models from django.conf import settings from .storage_backends import variativeStorage class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) photo = models.ImageField(upload_to='/public', default='dummy-img.png', storage=variativeStorage()) storage_backends.py: from storages.backends.s3boto3 import S3Boto3Storage from django.core.files.storage import default_storage from django.conf import settings def variativeStorage(): """Return S3Boto3Storage if access key is defined. Fallback to default storage. """ if hasattr(settings, 'AWS_ACCESS_KEY_ID') and settings.AWS_ACCESS_KEY_ID: return S3Boto3Storage() return default_storage It works great, but the problem is in migrations - it evaluates field storage on which django settings it currently has. So in case we don't have AWS_ACCESS_KEY_ID, makemigrations will do: operations = [ migrations.AlterField( model_name='profile', name='photo', field=models.ImageField(default='dummy-img.png', upload_to='/public'), ), ] and in case it has: operations = [ migrations.AlterField( model_name='profile', name='photo', field=models.ImageField(default='dummy-img.png', storage=storages.backends.s3boto3.S3Boto3Storage(), upload_to='/public'), ), ] So running server on production will trigger warning for missing migrations: remote: Running migrations: remote: No migrations to apply. remote: Your models have changes that are not yet reflected in a migration, and so won't be applied. remote: Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Is there a consistent … -
django how to make the fieldname a variable when using fieldname__contains?
query_dict = {'server_name': 'mysql', 'type': linux} class ServerInfo(db.models): server_name = models.CharField(max_length=255) type = models.CharField(max_length=20) from django.db.models import Q q = Q() for k, v in query_dict: q.add(Q(k__icontains=v), Q.AND) This can’t work,how could I replace the field name with a variable like the k above? My english is bad ,sorry about this. -
Multy queryset. Compare two queryset and find compared item
I have one not clearly for me task. I need to find one object which exist in two users. For example. Each user has AdditionalInfo, also i have the table AddInfoTeam where i have ManyToMany relationship: class AddInfoTeam(models.Model): add_info = models.ForeignKey(AdditionalInfo, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) Each user can exist in many teams. For example i have 2 users - user1 and user2. I need to find out which team are they together. This is my example code: # get additional info for user1 add_info_dealer = AdditionalInfo.objects.get(user=dealer) # get additional info for user2 add_info_grower = AdditionalInfo.objects.get(user=grower) # get all teams for user 1 dealer_teams = AddInfoTeam.objects.filter(add_info=add_info_dealer) # # get all teams for user 2 grower_teams = AddInfoTeam.objects.filter(add_info=add_info_grower) # this is bad code, i try to find someting better than this: for dealer_team in dealer_teams: for grower_team in grower_teams: if grower_team.id == dealer_team.id: return grower_team -
Django/ get ip of user and make default account to him
I'm working on a project (internet Voting) which user sign in using google, facebook and linkedin account I want to get the IP of the user to know that he the same person and ask him to have one default account to use it in voting and others accounts will be fake and when he votes by the fake accounts this vote will not count in final votes I just do not know how to do that and hope you help me -
How to perform UPDATE and DELETE operation in Django rest framework
I want to perform UPDATE and DELETE operation in Django rest framework, I did GET and POST operation. Please help me to do UPDATE and DELETE operation. views.py class SettingprofileViews(viewsets.ModelViewSet): queryset = Setting_profile.objects.all() serializer_class = SettingprofileSerializer models.py class Setting_profile(models.Model): name = models.CharField(max_length=255, blank=True, null=True) contact_number = models.CharField(max_length=12, blank=True, null=True) email = models.EmailField(max_length=100, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) serializers.py class SettingprofileSerializer(serializers.ModelSerializer): class Meta: model = Setting_profile fields = '__all__' urls.py router = routers.DefaultRouter() router.register('api/settingprofile', views.SettingprofileViews) urlpatterns = [ path('', include(router.urls)), ] -
Understanding many to many relationships: How can I choose the instances that belong to my Many to Many relationship field in django?ny
I have two models that I want to relate with a many to many relationship. BuildingGroup and Building My idea is that for example Building Group1 contains some Buildings and BuildingGroup2 contains other Buildings. I think I should have set it up correctly, but the way it works now is that every BuildingGroup contains ALL of my Buildings, always. I can't delete a Building and selectively decide which building belongs to which group. Here are my models: class Building(models.Model): name = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) buildings = models.ManyToManyField(Building, blank=True) Is that the right way to set it up? And if so, how can I change it, so I can group it correctly?? Any help is highly appreciated! -
cannot resolve keyword 'activate' into field
This is my error FieldError at /Slife/ Cannot resolve keyword 'activate' into field. Choices are: active, comment, created, details, featured, id, image, modified, name, option, slug, views Request Method: GET Request URL: http://localhost:8000/Slife/ Django Version: 2.2.1 Exception Type: FieldError Exception Value: Cannot resolve keyword 'activate' into field. Choices are: active, comment, created, details, featured, id, image, modified, name, option, slug, views Exception Location: C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\sql\query.py in names_to_path, line 1420 Python Executable: C:\Users\essum\Envs\Py1\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\essum\Envs\LIFE', 'C:\Users\essum\Envs\Py1\Scripts\python37.zip', 'C:\Users\essum\Envs\Py1\DLLs', 'C:\Users\essum\Envs\Py1\lib', 'C:\Users\essum\Envs\Py1\Scripts', 'c:\users\essum\appdata\local\programs\python\python37\Lib', 'c:\users\essum\appdata\local\programs\python\python37\DLLs', 'C:\Users\essum\Envs\Py1', 'C:\Users\essum\Envs\Py1\lib\site-packages'] Server time: Mon, 10 Jun 2019 09:56:18 +0000 Traceback Switch to copy-and-paste view C:\Users\essum\Envs\Py1\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\essum\Envs\LIFE\Slife\views.py in home categories = Category.objects.filter(activate=True,views__gte=3000).order_by('-views') … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\manager.py in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\query.py in filter return self._filter_or_exclude(False, *args, **kwargs) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\query.py in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\sql\query.py in add_q clause, _ = self._add_q(q_object, self.used_aliases) … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\sql\query.py in _add_q split_subq=split_subq, simple_col=simple_col, … ▶ Local vars C:\Users\essum\Envs\Py1\lib\site-packages\django\db\models\sql\query.py in build_filter lookups, parts, reffed_expression = … -
Why does my css not register with Django?
I am having trouble with CSS in Django. I have my static files linked, and for some reason when I make changes to the CSS file, it doesn't register. Say for example, I have a H2 that is red, but when I change it to H1 in the html and css, the css does not register. Also with an image, I have changed the file in the folder, even deleted the file, but the site is still showing the old image. Why is this happening? Also does this have anything to do with what I upload to git? -
IntegrityError, NOT NULL constraint failed
I want to add tags to posts in my Django app. I can add tags through the admin interface, but when I try to do it through the form I created, I get an IntegrityError. I couldn't find the solution in the existing topics with the same error. I ran makemigrations and migrate. From models.py: class Post(models.Model): title = models.CharField(null=False, blank=False) text = models.TextField() class Tag(models.Model): post = models.ForeignKey('my_app.Post', on_delete=models.CASCADE, related_name='tags') tag_text = models.CharField() The view: def post_add_tags(request, pk): post= get_object_or_404(Post, pk=pk) if request.method == "POST": form = TagForm(request.POST) if form.is_valid(): tag = form.save() tag.post= post tag.save() return redirect("single_post_view", pk=post.pk) else: form = TagForm() return render(request, "add_tags.html", {"form": form}) The form from forms.py: class TagForm(forms.ModelForm): class Meta: model = Tag fields = ["tag_text"] The template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Add tags</button> </form> The error: IntegrityError at /post/4/add_tags/ NOT NULL constraint failed: my_app_tag.post_id I'm using Django version 2.2, Python 3.6.8. -
Error : NoReverseMatch at /import/group_edit/1/ Reverse for 'confirm-delete' with arguments '('',)'
Error : Error : NoReverseMatch at /import/group_edit/1/ Reverse for 'confirm-delete' with arguments '('',)' not found. 1 pattern(s) tried: ['import\/confirm_delete\/(?P[0-9]+)\/$'] This error is from my confirm_delete.html when I want to go to group-edit.html scenario is: going to a list template of all groups (group_list.html). For each group, you have a href to edit it. When I click on this, Erro appears not on edit_group.html but on confirm_delete.html Hoping it is clear. Please see code...:-) changing views parameters but not working. It seems like parameter is not sent to the def confirm_delete. group_list.html: {% block page %} <div class="panel-body"> <table class="table table-bordered table-hover table-striped col-md-3"> <thead class="thead-dark"> <tr class="text-center"> <th>Group Name</th> <th>Parent Name</th> </tr> </thead> <tbody> {% for group in groups %} <tr> <td scope="row" class="col-md-3"><a href="{% url 'group-edit' group.group_id %}">{{ group.group_name|capfirst }}</a></td> <td class="col-md-3">{{ group.groupParent_id|capfirst }}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} group_edit.html: {% block page %} <form method="POST"> {% csrf_token %} <div class="col-lg-4 col-md-4 col-sm-4 content"> {% bootstrap_form form %} <button type="submit" class="btn btn-pink pull-right">Save</button> <button type="reset" class="btn btn-warning pull-left"><a href="{% url 'confirm-delete' form.group_id %}"></a>Delete</button> </div> <a href="{% url 'group-list' %}">Back to list</a> </form> {% endblock %} confirm_delete.html: {% block page %} <form method="post">{% csrf_token %} … -
queryset fails to print or give any result
The Code hangs up after the execution of queryset3 Strange thing is that if the date range is large, it works. But not for short durations My Summation code is: queryset3 = models.Ageperformancereport.objects.filter(account_id__exact=account_id, status__exact=0, date__gte=start_Date, date__lte=end_Date,is_brand=is_brand).values('account_id','account_name','age_range','is_brand','date').annotate(spend=Sum('cost')) Serializer is: class CostForAgeSerializer(serializers.ModelSerializer): spend = serializers.SerializerMethodField() class Meta: model = models.Ageperformancereport fields = ('account_id','account_name','age_range','is_brand','spend','date') def get_spend(self, obj): return obj['spend'] -
Annotation in Django Admin
I have a model as below: ....... user=models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True) visited = models.CharField(max_length=15) ...... I want to see in Django admin, each user with visited count. As of now I get name of each user multiple times and count is 1. This is my admin.py. class modelnameadmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(modelnameadmin, self).get_queryset(request) return qs.annotate(visit_count=Count('visited',distinct=True)).order_by('visit_count') def visit_count(self, inst): return inst.visit_count list_display = ['user','visit_count'] I am getting below results in admin template. user visit_count 1 1 1 1 2 1 2 1 But I should get result as below. user visit_count 1 2 2 2 -
(missing_code) Missing code parameter in response
Hi I am gluing a Django web app together. I need to authenticate my App with an API service that claims to use OAuth2. From the Providers developer portal I have followed the manual process and sent my https://provider.com/thirdpartylogin?client_id=clientid&redirect_uri=redirect-uri and as advertised I got back the https://your-redirect-url?authCode=temp-auth-code then exchanged the "temp-auth-code" for a real access_token. everything is fine with the manual process In my web app I am using https://github.com/requests/requests-oauthlib which works great. I cloned this project https://docs.microsoft.com/en-us/graph/tutorials/python and was able to get everything working. I thought it would be simple to swap out the tutorial parameters with my provider URLs and parameters, I can get so far and in the beginning the URLs look fine, but nothing is working after I am returned to the callback url and I get the error "code_missing". Can it be that my providers URL naming convention is wrong? note the authCode "https://your-redirect-url?authCode=temp-auth-code" I see from OAuth docs "code" is this is the standard naming not authCode. I am new to both Python and Django but if someone can confirm that this is the tripping point I would appreciate it. -
Automatically login user when using subdomains
I have two subdomains: a.domain.com b.domain.com on each domain, I have the same application but database schema is different so users are in totally different tables. Is there any way to automatically login user when I click "switch to b.domain.com" from a.domain.com if there is a user with the same email address? -
My Sidebar jumps when i click on tags. All other pages are shown correctly
I made a central css file, and now my sidebar jumps when i click on tags. I inspected the whole website, but i can´t figure out why. On the frontpage, and on all other pages it´s correct. Just when i click on tags, it jumps. I will also add some pictures, so you can see what i mean. Can´t figure out why this is happening, the tag function uses also the index.html as the frontpage. So there is no logical answer for me. This is my sidebar code. I use bootstrap for styling the page. <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Sidebar Widgets Column --> <div class="col-md-4 col-mt-3 float-right "> <div class="card my-4"> <h5 class="card-header">Über diesen Blog</h5> <div class="card-body"> <p class="card-text"> Hi, ich heiße Uroš und habe diesen Blog als Gedächtnisstütze für Problemlösungen innerhalb der Programmierung, Linux und Windows erstellt!</p> <a href="{% url 'about' %}" class="btn btn-danger">Mehr erfahren !</a> </div> </div> <div class="card my-4"> <h5 class="card-header">Links</h5> <div class="card-body"> <p> Ich bin Mitglied bei folgenden Portalen: <ul style="list-style-type:none;padding-left: 10px;"> <li><i class="fa fa-stack-overflow"><a class="mycardtext" href="https://stackoverflow.com/">&nbsp; Stack Overflow</a></i></li> <li><i class="fa fa-linkedin"><a class="mycardtext" href="https://www.linkedin.com/in/uros-dobricic-23489151/">&nbsp; LinkedIn</a></i></li> <li><i class="fa fa-xing"><a class="mycardtext" href="https://www.xing.com/profile/UROS_DOBRICIC/cv?sc_o=mxb_p">&nbsp; Xing</a></i></li> </ul> </p> </div> </div> <div class="card … -
Parsing nested JSON "id: value" inside "value" - inception of GET response and how to parse this
There are few similar topics BUT all of them guides how to parse nested JSON if you know the number and names of ids. What i need to do is generic code. I am creating WEB-application that uses multiple DIFFERENT GET/POST/DELETE requests. Now i focus parsing GET requests. What i have now is generic template that parse not nested JSON response. my generic json.html [...] {% if response %} {% for id, value in response.items %} <p>{{ id }}: {{ value }}</p> {% endfor %} {% else %} <p>No IDs are available.</p> {% endif %} [...] and its perfectly generic, works fine for all of responses i get if are not nested (id: value) for examle: version: 3.4 level: system: unix server_time: 1560252637000 server_utc: 2 but when i get nested json response, this generic template is not so good. response looks like this: transfers: [{'direct': 'SEND', 'type': 'MESSAGE', 'compatstate': 'T', 'ack': '', 'state': 'T', 'phase': 'X', 'phasestep': 'X', 'idf': 'NOW', 'idt': 'F1112091', 'frec': '', 'msg': 'test'}] numberOfSelectedRecords: 2 numberOfUsedRecords: 2 numberOfRecords: 10000 offset: 0 adding view, maybe itll be helpful: def transfers(request, host_id): hostname = Host.objects.get(pk=(host_id)) response = requests.get( 'https://{}:1769/v1/transfers?fields=aa%bb'.format(hostname), verify='/cert/cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxx'}, ).json() context = {'response': … -
Python/Django MultipleChoiceField with OptGroup Options
I am having a little bit of trouble figuring out how to configure optgroup tags in my Django Form using MutlipleChoiceField select options. Basically I have created an interface that uses Ajax to allow the allowance or removal of permissions for my project and I use a form to prepopulate the granted and not granted permissions in 2 MutlipleChoiceField select boxes. There are currently about 190 permissions for the project so the select box looks quite overwhelming at the moment, what I want is to group these options using an optgroup html tag. I understand how it works if I am statically typing the choices for the form, but at the moment with my current code, I cannot see a way to easily group them by app_label to add the correct optgroup. Can somebody help me out? Here is my code: from django import forms from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from django.db.models import Q class GroupForm(forms.ModelForm): class Meta: model = Group fields = ['permissions'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'instance' in kwargs: instance = kwargs['instance'] granted_permissions = list() not_granted_permissions = list() all_permissions = Permission.objects.all().order_by('id', 'content_type__app_label') for permission in all_permissions: if permission in instance.permissions.all().order_by('id', 'content_type__app_label'): … -
Problem with changing the header background with page scroll
I am implementing a fixed transparent header which turns black when the page is scrolled more than 100 pixels. Currently, in main.js I have a function: // Header scroll class $(window).scroll(function() { if ($(this).scrollTop() > 100) { $('.header').addClass('header-scrolled'); } else { $('.header').removeClass('header-scrolled'); } }); in main.css I have: /*------- # Header ---------*/ #header { padding: 3px 0; position: fixed; left: 0; top: 0; right: 0; transition: all 0.5s; z-index: 997; background-color: transparent; } .header-scrolled { background-color: black; } and the html page is formatted as follows: <header id="header" id="home"> <div class="container"> <li class="row align-items-center justify-content-between d-flex"> <div id="logo"> <a href="home.html"><img width="160" height="160" src="{% static 'img/my_logo.png' %}" alt="" title="" /></a> </div> <nav id="nav-menu-container"> <ul class="nav-menu"> <li class="menu-active"><a href="#home">{% trans "Home" %}</a> </li> <li class="menu-active"><a href="#contacts">{% trans "Contacts" %}</a></li> </ul> </nav> </div> </header> Currently, the header is fixed and transparent. Yet, when I scroll down, it doesn't turn black (although in the inspector it seems that the header-scrolled is being added). I cannot seem to find any solution to the problem (none of the provided other suggestion of similar questions work)... Perhaps I am missing something? -
How to overwrite get_queryset method to only display the objects that are contained within a many-to-many field in django?
I have an API that has two models. Buildings and BuildingGroup. Every building is within a building group. I want to overwrite the get_queryset method to display only buildings that are within a Building group. My models: class Building(models.Model): name = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, buildings = models.ManyToManyField('Building') My view so far: def get_queryset(self): qs = Building.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(project__icontains=query) return qs this shows me a list of all Buildings. Now I want to change that method, but I couldn't manage so far. I tried: qs = BuildingGroup.objects.buildings.all() qs = BuildingGroup.buildings.all() qs = BuildingGroup.buildings_set.all() and I tried looping through the BuildingGroup... Has anyone an idea? Help is of course very much appreciated. Thanks in advance -
How to query in Django with best efficiency?
I recently found that too much SQL query optimization issue. django-debug-tool reported hundreds of similar and duplicate queries. So, I'm trying to figure out the best efficiency of Django ORM to avoid unnecessary Queryset evaluation. As you see the below Store model, a Store model has many Foreign key and ManyToManyFields. Due to that structure, there are many code snippets doing the blow on HTML template files such as store.image_set.all or store.top_keywords.all. Everything starts with store. In each store detail page, I simply pass a cached store object with prefetch_related or select_related. Is this a bad approach? Should I cache and prefetch_related or select_related each Foreign key or ManyToManyField separately on views.py? HTML templates {% for img in store.image_set.all %} {{ img }} {% endfor %} {% for top_keyword in store.top_keywords.all %} {{ top_keyword }} {% endfor %} {% for sub_keyword in store.sub_keywords.all %} {{ sub_keyword }} {% endfor %} views.py class StoreDetailView(View): def get(self, request, *args, **kwargs): cache_name_store = 'store-{0}'.format(store_domainKey) store = cache.get(cache_name_store, None) if not store: # query = get_object_or_404(Store, domainKey=store_domainKey) query = Store.objects.all().prefetch_related('image_set').get(domainKey=store_domainKey) cache.set(cache_name_store, query) store = cache.get(cache_name_store) context = { 'store': store, } return render(request, template, context) models.py class Store(TimeStampedModel): categories = models.ManyToManyField(Category, blank=True) price_range = …