Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to place a django form in a nav bar so that it appears on every page?
I have a form whose queryset depends on request.user, and whose initial value depends on a session key. The primary models are User (slight modification of default User model) and Account, with a many-to-many relationship between them. The form allows a User to change the Account that he/she is viewing, and that choice must persist as the User navigates the site. The form works fine when created in a single view and passed to a single template, but I want the form to appear in the top navigation bar so that the User can change Accounts from anywhere. Here is the form: class ChangeAccountContextForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.current_account_id = kwargs.pop('account_id') super(ChangeAccountContextForm, self).__init__(*args, **kwargs) self.fields['account_choices'].queryset = self.user.accounts.all() try: self.fields['account_choices'].initial = Account.objects.get(id=self.current_account_id) except(Account.DoesNotExist): self.fields['account_choices'].initial = None #queryset and initial are set to None, because they are assigned dynamically in the constructor (see above) account_choices = forms.ModelChoiceField(queryset=None, initial=None, label='Account:', widget=forms.Select(attrs={'onChange':'this.form.submit()', 'class': 'custom-select mr-sm-2 ml-2'}), required=True ) class Meta: model = User fields = ['account_choices'] And here is the existing view where the form is used: @login_required def welcome_view(request): user = request.user context = {} accounts = user.accounts.all().order_by('account_name') context['accounts'] = accounts context['num_accounts'] = len(accounts) try: account_id = request.session['current_account_id'] except (KeyError): … -
Show a DRF user token in a django template view
I have a very simple template view to allow user to view their drf token from django.views.generic.base import TemplateView from rest_framework.authtoken.models import Token class AuthTokenView(TemplateView): template_name = 'view_auth_token.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['username'] = self.request.user.username context['token'] = Token.objects.get(user=self.request.user) return self.render_to_response(context) I keep getting this even though I know Token is a model. Any ideas? context['token'] = Token.objects.get(user=self.request.user) AttributeError: type object 'Token' has no attribute 'objects' [12/Mar/2020 14:56:16] "GET /get_auth_token/ HTTP/1.1" 500 107751 -
Django 3 and SQL Anywhere
How do I connect a Django 3 (Python 3.6) new app to a SAP SQL Anywhere 16? I have tried to use sqlanydb, pyodbc and django_sqlany without success. -
Django: can't trigger AJAX call and send values back to my form
I need to run an AJAX call to perform a quick calculation in my django view and return the result in my html page, inside a tag. I'm very new to Javascript so I don't understand why my AJAX call hasn't been triggered. This is my html and JS code: <input type="text" name="SHm2" maxlength="10" type="number" value="50"> <input type="text" name="STm2" maxlength="10" type="number" value="50"> <button id="estimation" name= "estimation" onclick="calculate()">Estimation</button> <span>{{estimation}}</span> <script type="text/javascript"> function calculate () { $.ajax({ url: '/myApp/templates/homepage/', type: 'POST', data: { SHm2: $('#SHm2').val(), STm2: $('#STm2').val() }, success: function(estimation) { alert(estimation); document.getElementById("estimation").innerHTML = estimation; } }); } </script> And this is my views.py: def homepage(request): if request.method == 'POST' and request.is_ajax and 'estimation' in request.POST: SHm2 = request.POST.get('SHm2') STm2 = request.POST.get('STm2') estimation = float(SHm2) + float(STm2) estimation = json.dumps(estimation) return HttpResponse(estimation, content_type='application/json') The problem is that the AJAX code isn't triggered since I don't receive the alert. Nevertheless, the code in my django view is running anyway (which is strange, since I specified to run if 'request.is_ajax', which doesn't seem to be recognized on the other hand). It loads a new page where it correctly displays the result. But it's not what I want since I need the result to be … -
Is there any way to show a field on a listing page in Wagtail admin?
I know that I can register my model as a Django model and add an image there but I need to save a pages' tree and identify my pages by an image on a listing page. To make a long story short, I need to show images on a listing page in admin. -
Trouble with RFC 5545 Recurrence by day
I'm seeing erroneous behavior with a by-day (e.g. every Tuesday and Thursday) recurrence pattern. Suppose I have an event starting on Thursday 3/12 at 9p (2100h) Pacific time and recurring every Tuesday and Thursday. Pacific time is UTC-0700, so the event has a UTC start date of 0400h on 3/13--4am the following day. When my recurrences are generated they take the start time of the original event, but not the date. So my recurrences are generated on Tuesdays and Thursdays at 0400h, which translates to 9p PT on Mondays and Wednesdays. I've tried creating the events in local (Pacific) time and specifying a TZ-ID, but it doesn't seem to help. Is there a way to account for this? I don't want to try to infer whether there will be an issue and rewrite the recurrence pattern on the fly, as that A) seems very error prone, and B) will make the interface for editing the recurrence pattern very challenging as well. -
Django ORM raw query how manage quotes
In my Django project i have to implement a complex RAW query for extract data, for doing this i use the raw django function. The original query is: SELECT FT."Riferimento1", FT."Riferimento2", "CodProdotto", "QuantitaFatturata", "PrezzoUnit", "DataFattura", "NumeroFattura", "CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192'; if i run directly in pgadmin SQL all was done In django i implement in this fashion: >>> from idocuments.models import as_fatturetestata as asf >>> a = asf.objects.raw("SELECT FT."Riferimento1",FT."Riferimento2","CodProdotto","QuantitaFatturata","PrezzoUnit","DataFattura","NumeroFattura","CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192'") but i get: SyntaxError: invalid syntax maybe the problem is how to manage quotes but i don't understand how transport the sql query into raw directive. Someone can help me please? so many thanks in advance -
Partially rending page, if click the button (image O)
enter image description here I want to make faster website. so I try rendering less in one time. If the button is clicked, the page is partially rendering like picture. I linked example of what i want to made. https://na.op.gg/summoner/userName=shernf click the arrow button, rendering new page -
Cannot login to deployed app. Nginix configuration issue on EC2
I've tried to get my api working on ec2 to working with my django/drf backend and my nuxt frontend app. When I deploy the app my frontend is rendered and my backend admin works but I cannot login or access render any data from backend. For Example, when I try to request url ec2-64-644-225-61.eu-west-1.compute.amazonaws.com/api Nothing happens. I'm trying to find documentation on this online but I'm not getting far. On the DRF official docs or nginx official docs I don't see any documentation that show's how to configure api on ec2. My app runs locally fine but on ec2 doesn't serve my frontend for backend data communications. Should these settings work or am I missing something? config for nginx upstream django { ip_hash; server 127.0.0.1:8000; } upstream nuxt { ip_hash; server 127.0.0.1:3000; } server { location ~ /(api|admin|static)/ { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location / { proxy_pass http://nuxt; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } listen 80; server_name localhost; } docker_compose version: '3.4' services: db: restart: always image: postgres volumes: - pgdata:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 redis: restart: always image: redis volumes: - redisdata:/data django: build: context: ./backend … -
DRF custom permission is not working for function view (get request)
I have Angular frontend sending request using firebase id_token. In the backend (backend.py) authenticates every request based on the id_token in the header. Using Firebase Admin SDK I added users to 'standard' or 'premium' group and also have local copy of users in the database. In permissions.py I check if the user belongs to either standard or premium. For QuestionCorrAPiView(APIView) it works as expected (if not logged in or if user is not in standard group, cant access). However, for the function view, I couldn't figure out why the permission class is not called. Even though _has_persmission returns False, it still allows access to exams view. I know I have made stupid mistake somewhere but don't know where. Any help is appreciated. ''' #All other imports from coc_api.permission import IsStandard @ /api_vie(['GET']) @/permission_classes([IsStandard]) def exams(request): exams = models.Exam.objects.all() serializer = coc_serializers.ExamSerializer(exams) return Response(serializer.data) class QuestionCorrAPIView(APIView): permission_classes = [IsAuthenticated,IsStandard] # IMPLEMENTATION HERE #permissions.py def _is_in_group(user, group_name): """ Takes a user and a group name, and returns `True` if the user is in that group. """ try: return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() except Group.DoesNotExist: return None def _has_group_permission(user, required_groups): return any([_is_in_group(user, group_name) for group_name in required_groups]) class IsStandard(permissions.BasePermission): # group_name for stadnard users required_groups = … -
Creating copy for blog post has no argument and return all pots and comments and updating date and return new id
class Blog_Post(models.Model): '''create copy in this class``` title = models.CharField(max_length=250) body = models.TextField() date_created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Author',on_delete=models.CASCADE) class Author(models.Model): name = models.CharField(max_length=50) class Comment(models.Model): blog_post = models.ForeignKey(Blog_Post,on_delete=models.CASCADE) text = models.CharField(max_length=500) -
Django: Error rendering views with CSRF token
There are lots of posts on the web regarding the error TypeError: 'module' object is not callable, when trying to use contexts, but I am stuck on this for almost 24h... I've read the documentation more than once and I still had no success. TL,DR: I don't know what I am doing and I need someone to explain me, how to use a {% csrf_token %} on a html page. Because my views.py are not rendering properly, if at all. If I don't use csrf_tokens/post methods, everything works fine! I'm new to Django. Using 3.0.4 Brief explanation of what I am trying to do and symptoms: My base.html as a sign-in button, which opens a modal, where the user can insert : and this triggers a post direct within the domain. Because of this reason, I need to use {% csrf_token %}. Which I do. Once I had the token, I get an error saying I need to setup the context on my views, which I did. I tried multiple ways and right now my views looks like this: from django.http import HttpResponse from django.template import Template, RequestContext def gallery_categories_view(request): template = Template('gallery-categories.html') context = RequestContext(request) html = template.render(context) return … -
django DB2 inspectdb failure :'NoneType' object is not subscriptable
my dev environment is in python 3.6 and virtualenv(virtualenv 15.1.0) and with dependencies below: django 2.2 ibm-db 3.0.1 ibm-db-django 1.2.0.0 as i used "(env_django2) λ python manage.py check", it return "System check identified no issues (0 silenced)." that is no problom. however, when i used "python manage.py inspectdb --database db2 DEMO.DEMOUSER", it return like these below: (env_django2) λ python manage.py inspectdb --database db2 DEMO.DEMOUSER # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'DEMO.DEMOUSER' # The error was: 'NoneType' object is not subscriptable this is my db2 setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db2':{ 'ENGINE': 'ibm_db_django', 'NAME': 'test', 'USER': 'db2inst1', 'PASSWORD': 'XXXXXX', 'HOST': 'XX.XXX.XXX.XXX', 'PORT': 'XXXXX', 'PCONNECT':True, } } and … -
how do i create bridge table in djnago model
i have created two table's in djnago models. i have created foreign-key for both models like a 'cross-product' but while i applies python3 manage.py makemigrations cmd and then python3 manage.py migrate i get error django.db.utils.IntegrityError: The row in table 'subscription_registration' with primary key '1' has an invalid foreign key: subscription_registration.ProfileImages_id contains a value '1' that does not have a corresponding value in subscription_profileimages.id. models.py table-1 class Registration(models.Model): YourName = models.CharField(max_length=30) ProfileImages = models.ForeignKey('ProfileImages', on_delete=models.CASCADE, verbose_name="profile image key(as FK)", null=True, blank=True) Email = models.EmailField(max_length=254,null=True) password = models.CharField(max_length=254,null=True) table-2 class ProfileImages(models.Model): MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE, null=True, blank=True) profile_image = models.ImageField(upload_to='profile_image',default="some",null=True) note: the registration form have allready data as id 1 now i want to add profile image for that user. and i think i can create a bridge table between them so if please help me what i can do before creating bridget table i need to assign fk for both table am right? -
Extend wagtail page visibility and add subscription plans
I'm creating a website with wagtail where users can decide to buy a subscription plan. Each subscription should allow access to a page on the site. For example, "only users in the premium plan can read the news." The subscription must have an "expiry date". At the moment the visibility can be blocked to users in a specific group (which can be managed as a subscription) but I don't know how to manage the expiration date and it doesn't seem to be a particularly elegant solution for my problem. I haven't found anything to create a custom model user_group with an expiry_date field. I would like to know how a situation like this should usually be handled and if it is possible to add another entry in the visibility section, for example: "private, accessible to users in specific subscriptions". -
How to Query model filed elements in the same URL
I am writing a single model application in DRF. My model looks like this: class Superhero(models.Model): squad_name = models.CharField(max_length=100) hometown = models.CharField(max_length=30) formed = models.DateField() active = models.BooleanField() members = JSONField() My viewset looks like this: class SuperheroViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving superheros. """ serializer_class = SuperheroSerializer def list(self, request): """list superhero object""" queryset = Superhero.objects.filter() serializer = SuperheroSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Superhero.objects.filter() superhero = get_object_or_404(queryset, pk=pk) serializer = SuperheroSerializer(superhero) return Response(serializer.data) and finally, my router is: router = DefaultRouter() router.register(r'superhero', SuperheroViewSet, basename='superhero') urlpatterns = router.urls Now how do I set a URL,so I would query the members field like: //superhero/{id}/members to get specific id members. I tried drf nested URL but didn't work. The url I have works for superhero/ and superhero/{id}. -
Error 'File doesn't exist' when running Django migrations, migrate and runserver
Whenever I run Django 'python manage.py makemigrations', runserver or migrate I get the following error : (env) mark@mysite$ python manage.py migrate File doesn't exist This is a very unhelpful error, are there any logs I can look in to find out which file is missing? I have tried re-installing Django, and deleting and recreating the site migrations and database but the error persists. The site otherwise runs fine so I have no clue as to what is going on. Any suggestions in how I can fault find this would be really appreciated. I am also using Wagtail but I don't think the error is related to that. -
channels_redis raises "Name or service not known" in docker-compose network mode bridge
I've a django app which uses channels, channels_redis and graphene_subscriptions. graphene_subscriptions is used to publish a message via channels when a database model instance is saved (DATABASE_MODEL_INSTANCE.save()). The Django app and redis (as well as the other parts of the fullstack app of course) is run separate docker containers using docker-compose. When I run the setup with docker-compose in network mode host on Linux everything is just fine. However if reconfigure the setup for network mode bridge with custom networks (one for the backend, one for the frontend) and run the setup with docker-compose I get the following error: c_backend | File "./APP_SPECIFIC_PATH/FILE.py", line X, in FUNCTION c_backend | DATABASE_MODEL_INSTANCE.save() c_backend | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save c_backend | force_update=force_update, update_fields=update_fields) c_backend | File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base c_backend | update_fields=update_fields, raw=raw, using=using, c_backend | File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send c_backend | for receiver in self._live_receivers(sender) c_backend | File "/usr/local/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> c_backend | for receiver in self._live_receivers(sender) c_backend | File "/usr/local/lib/python3.7/site-packages/graphene_subscriptions/signals.py", line 15, in post_save_subscription c_backend | event.send() c_backend | File "/usr/local/lib/python3.7/site-packages/graphene_subscriptions/events.py", line 20, in send c_backend | "subscriptions", {"type": "signal.fired", "event": self.to_dict()} c_backend | File "/usr/local/lib/python3.7/site-packages/asgiref/sync.py", line 116, in __call__ c_backend | return … -
In Django, form submit is working but not able to parse user input
User can able to submit the form without any issue, however user input data does not parse into database. Only predefined default data is parsing. In my opinion, my model has an issue however I could not able to find because first time I am creating an object with ForeignKey and my knowledge on 'instance' part of the model is limited. Or I am too tired... My models.py class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='ticketer') status = models.CharField(max_length=6, choices=STATUS_CHOICES, default='open', blank=True) subject = models.CharField(max_length=60, default='Ticket', blank=False) body = models.TextField(blank=False) priority = models.CharField(max_length=6, choices=PRIORITY_LEVEL, default='low', blank=False) display = models.BooleanField(default=True, blank=True) created_at = models.DateTimeField(auto_now=True, blank=True) closed_at = models.DateTimeField(blank=True, null=True) handler = models.CharField(max_length=14, default='MT', blank=True) response = models.TextField(blank=True, default='We are working on your ticket!') def save(self, *args, **kwargs): super(Ticket, self).save(*args, **kwargs) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_or_update_ticket(sender, instance, created, **kwargs): Ticket.objects.create(user=instance) My views.py @login_required @transaction.atomic def add_ticket_view(request, username): if request.method == 'POST': add_ticket_form = AddTicketForm(request.POST, instance=request.user) if add_ticket_form.is_valid(): add_ticket_form.save() messages.success(request, ('Your ticket was successfully submitted!')) return redirect('..') else: messages.error(request, ('Please correct the error below.')) else: add_ticket_form = AddTicketForm(instance=request.user) context = { 'add_ticket_form': add_ticket_form, } return render(request, 'pages/user-ticket-add.html', { 'add_ticket_form': add_ticket_form }) My forms.py class AddTicketForm(forms.ModelForm): class Meta: model = Ticket fields … -
Does too many empty fields in each row effect search performance in PostgreSQL?
I am using PostgreSQL as my database along with Django Given below is my model for database class Users(model.Model): email = model.CharField(max_length=50, default="") password = model.CharField(max_length=40, default="") source = model.CharField(default='unknown', max_length=150) domain = model.CharField(max_length=50, default="") before_at = model.CharField(max_length=255, default="") username = model.CharField(max_length=150, default="") hash = model.CharField(max_length=255, default="") ipaddress = model.CharField(max_length=50, default="") phonenumber = model.CharField(max_length=100, default="") class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'password', 'source'], name='uniqueness constraints') ] def __str__(self): return self.email The thing is most of the rows will have email, password, domain field but the rest will remain empty. Similarly, some will have username,password, source while others are empty. What i want to do is that everyone can search from users table based on different fields such as email, password, domain, username, hash, ipaddress. There are going to be Billions of data in this one table. So what is the best practice is it ok even if rows have a lot of empty fields or does it effect the performance. For instance there are one billion records in total but in which half a billion have empty/null ipaddress field and half billion record have data in ipaddress field then if if i gona search in the table based on ipaddress … -
why zlib error when i want to use virtualenv with python3.6?
when i run virtual environment for create environment with python3.6 in Ubuntu 16.4,i got error: **virtualenv -p python3.6 .venv** Traceback (most recent call last): File "/usr/lib/python3/dist-packages/virtualenv.py", line 22, in <module> import zlib ModuleNotFoundError: No module named 'zlib' -
Is there any way to import JavaScript function to React component outside from src folder
I have a two function at my javascript utils.js at my django static files. I want to use this file common with react. So i want to import to react this file with functions and i want to use it at react component. Function example function convertMsToDatetime(s) { let ms = s % 1000; s = (s - ms) / 1000; let secs = s % 60; s = (s - secs) / 60; let mins = s % 60; s = (s - mins) / 60; let hours = s % 24 let day = (s - hours) / 24 var ret = []; if (day !== 0) { ret.push(day + "d") } if (hours !== 0) { ret.push(hours + "h") } if (mins !== 0) { ret.push(mins + "m") } if (secs !== 0) { ret.push(secs + "s") } return ret.join(" ") } -
Django select indirectly related with a condition
In my project, I have Users and they can have a certain role. However, the roles are limited by date ranges, that is a user can have an admin role from 01.01.2020 to 02.02.2020, and an unprivileged user role from 02.02.2020 to 03.03.2020. I need to be able to return the list of users with their current roles and I want to be able to make just one query to the database. However, I can't figure out how to do that. Here are my models: class User(models.Model): ... class Role(models.Model): name = models.CharField(...) class UserRoleQuerySet(models.QuerySet): def current(): return self.filter(period__contains=date.today()) class UserRoles(models.Model): user = models.ForeignKey(User, related_name='roles') role = models.ForeignKey(Role) period = DateTimeRangeField() objects = UserRoleQuerySet.as_manager() I need a queryset with either a prefetch_related, select_related or annotate method called on it so that when I then do something like code below, I don't get additional database trips: users = User.objects.(some_magic_here).all() for user in users: print(user.profession) -
return Pandas csv as FileResponse
I have a super simple pandas table to return as csv in django: class PandasExport(View): def get(self, request, *args, **kwargs): f = tempfile.NamedTemporaryFile(mode='wt') table = pd.DataFrame(list(MyModel.objects.all().values())) report = table.to_csv(f, index=False, header=True) return FileResponse(report, 'r') Although report is fine, the view returns an error: 'NoneType' object is not iterable What am I doing wrong? -
ImageFiled not working on update in django
I have a custom form to update record in Django. everything working fine except the image. updated = Brand.objects.filter(brand_id = brand_id).update(brand_name = brand_name, brand_slug = brand_slug, brand_logo_alt_text = brand_logo_alt_text, brand_title = brand_title, category_id = brand_category, country_id = brand_country,brand_info = brand_info, brand_description = brand_desc, brand_logo = brand_logo) Media setup was perfect and everything working correct on creating new records but when I update this image not shown in media directory but in database image URL properly stored. What's exactly the problem is? and please provide a suitable solution for the same.