Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid "a lot of {%include%} gives a lot of <footer>"?
When I need to use a lot of {%include%} (content) in html templates - do unnecessary extensions appear for each content inclusion? Effects are also applied to each subsequent inclusion of content... When I can add content inclusion to the first html template expander, everything is fine. But when I use "pagination" I need to send "page=posts" to paginator.html. I can't find a way to send this variable to blog.html from layout.html... And I think that in the future I will have the same problems, and therefore it should be solved. layout.html <div class="container body-content"> <div id="content"> {% block content %} {% endblock %} </div> </div> <div class="container body-content"> <footer> <hr/> <p>&copy; {{ year }}. Сайт</p> </footer> </div> blog.html {% extends "app/layout.html" %} <!--♕--> {% block content %} <h2>{{ title }}</h2><br> {% for post in posts %} <hr> <div class=""> <h2> {{post.title}} </h2> <p> {{post.posted}} </p> </div> <p> <a href="{% url 'blogpost' parametr=post.id %}">{{ post.description }}</a> </p> {% endfor %} {% include "app/pagination.html" with page=posts %} {% endblock %} pagination.html {% extends "app/blog.html" %} <!--♕--> {% block content %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Предыдущая</a> {% endif %} <span class="current"> Страница {{ page.number }} … -
How to open db.sqlite3 in Visual studio for django project
I want to use the db.sql 3 but when I open it is not reading the file. Moreover, I also downloaded SQLite extension but when I again click on db.SQLite 3 is nothing showing there. So please help me regarding this. -
Filter query on first many-to-many item
I would like the first! artist for the song to come from NL or BE. At the moment I'm querying all artists for a song. This is my query. Song.objects.filter(artists__country__code__in=['NL', 'BE']) and these are my models: class Song(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) artists = models.ManyToManyField(Artist) ... class Artist(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) country = CountryField(blank=True, null=True) ... I know that I can access the first item of the many-to-many field like this: song.artists.first() But I don't know how to do this in the query filter. Any ideas? Thanks in advance. -
Problem with a select that filters the other
I did all the filtering correctly from the frontend point of view, but in the backend I cannot save the data. This is the error: select a valid choise. That choice is not one of the available choices. I can't understand where the error is, I think in the fact that 'group_single' is passed in post from my view and therefore is not seen by the form. if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = … -
Not able to install tensorflow in Mac M1
I am trying to install tensorflow on my Mac M1 and I am getting the following error: ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow I have python3- 3.9.7, pip- 21.3.1 -
how to migrate just specific table in django?
I tried multiple databases in django. So, I set databases like that # settings.py DATABASE_ROUTERS = [ 'stage1.routers.MultiDBRouter', ] DATABASE_APPS_MAPPING = { 'stage1': 'stage1', } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'stage1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'stage1', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': '######', 'PORT': 3306, 'CHARSET': 'utf8mb4', }, } # stage1.routers.py class MultiDBRouter(object): def __init__(self): self.model_list = ['stage1'] def db_for_read(self, model, **hints): if model._meta.app_label in self.model_list: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label == 'stage1': return 'stage1' return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label in self.model_list or obj2._meta.app_label in self.model_list): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'stage1': return db == 'stage1' return None # stage1.models.py from django.db import models class Room(models.Model): name = models.CharField(max_length=100) sort = models.CharField(max_length=100) class Meta: app_label = "stage1" I did manage.py migrate --database=stage1 and it worked. But there are something wrong I didn't intend. I just wanted stage1 database has only one table room. But it has all tables that are basically set like auth_group, django_session ... How can I do to make only one table room in stage1 database? Please help me. -
Swedish BankID QR code Server/Client Interaction in Django
This post is related to my last post BankID has the ability to offer animated QR code generation for authorization. It generates a new QR every second and you scan with a mobile app and then their server returns a success once the user enters their code or scans their fingerprint. You can just skip the QR code and have bankID ping the user to enter their code to auth, but I want to have the QR code functionality for my app. Now my question is this. When the POST request is sent Views gets a qr_start_token, and qr_start_secret returned from the bankID server. Views is waiting for a status change from the BankID server to do something, but that leaves me at a lost on how I can render the changing QR code on the client. How can I do this without rendering a new page, passing the secret through context and using javascript to replicate this process? Here is the relevant code: if request.META['HTTP_USER_AGENT']: ua_string = request.META['HTTP_USER_AGENT'] user_agent = parse(ua_string) if user_agent.is_pc: status=client.collect(order_ref=auth["orderRef"])["status"] order_time = time.time() while status == "pending": qr_start_token = auth["qrStartToken"] qr_start_secret = auth["qrStartSecret"] print(qr_start_secret) qr_time = str(int(time.time() - order_time)) qr_auth_code = hmac.new(qr_start_secret.encode(), qr_time.encode(), hashlib.sha256).hexdigest() qr_data … -
Django admin on many-to-many relation: Variant-category relationship with this Variant and Category already exists
In Django admin if i select new field in inline of category which is many to many relation with variant, if i select the same category it raise error Variant-category relationship with this Variant and Category already exists. How would i select new inline field with same category for many to many field. Here's my code Admin.py class VariantInline(admin.TabularInline): model = Variant.category_id.through extra = 0 @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): ... inlines = [VariantInline] Models.py class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) ... class Variant(models.Model): ... variant_id = models.AutoField(primary_key=True) category_id = models.ManyToManyField(Category) -
"'Request' object has no attribute 'learner'": Django Restframework
There is an error in my code "'Request' object has no attribute 'learner'". Here, My requirement is "request.learner" is empty then call "CDetailsSerializer" otherwise call "CourseDetailsSerializer". def list(self, request, **kwargs): try: queryset = self.get_queryset() queryset = self.filter_queryset(queryset) if not request.learner: serializer = CDetailsSerializer(queryset, many=True) else: serializer = CourseDetailsSerializer(queryset, many=True) print('s', serializer.data) response_data = {'course': serializer.data} return self.jp_response(s_code='HTTP_200_OK', data=response_data) except Exception as e: print(e) return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) Here always calling (else part) CourseDetailsSerializer, but in some situations, I also want to call (if part) CDetailsSerializer.Give me a solution to fix this. -
django factory using a factory gives "Database access not allowed"
I want to create a user_profile from a factory called UserProfileFactory which uses a User object from UserFactory. the error is: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. here are the relivant classes. from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] class UserProfileFactory(DjangoModelFactory): user = UserFactory.create() #### the problem line ### country = Faker("country") # which laws apply birth_date = Faker("date_of_birth") # in the US you can't collect data from <13yo's class Meta: model = UserProfile and in the tests/test.py class TestUserProfileDetailView(): def test_create_userprofile(self): """creates an APIRequest and uses an instance of UserProfile to test a view user_detail_view""" factory = APIRequestFactory() request = factory.get('/api/userprofile/') request.user = UserProfileFactory.create() # problem starts here # response = user_detail_view(request) self.assertEqual(response.status_code, 200) -
Empty lines in form-select django template
i have a choice form, the user has to select a country from a dropdownlist. my html code: <div class="mb-3"> <label for="{{ profile_form.country.id_for_label }}" id="country_label" class="form-label">Country</label> <select class="form-select" name="{{ profile_form.country.html_name }}" id="{{ profile_form.country.id_for_label }}"> {% for country in profile_form.counry %}<option>{{ country }}</option>{% endfor %} </select> </div> But in html i get a dropdown with a empty line between every country: -Usa -emptyline -Germany -emptyline How can i get rid of those empty lines ? -
Can the APIRequestFactory create a request with data and user attributes
I'm trying to make a unit test for a function that takes a django Request object as a parameter; the Request object being one of the params from a Django class based view method. From the request object param, it's assumed there is a data and user attribute. My problem is that I can't replicate the request object using DRF's APIRequestFactory. When I'm using the python requests package and I do something like headers = { 'Authorization': "Token {}".format(settings.AUTH_TOKEN), 'Accept': 'application/json', 'Content-Type': 'application/json', } data['foo'] = foo_id response = requests.post( '{}/api/foo/{}/action/'.format(settings.ROOT_URL, foo_id), headers=headers, json=data) Then the user and data attribute exist in the request object of the class based views. If, however, I use DRF's APIRequestFactory and do data = {"foo_id": 1234} factory = APIRequestFactory() request = factory.post('/api/foo/1/action/', data, format="json") ...then I have to explicitly add request.user = user request.data = data Only the body attribute as data, and thats as a bytestream e.g. body: b'{"foo_id":"1234"}' Is what I'm trying to do possible? As an aside, it could also be that I'm violating the law of demeter and that my function being tested should be taking a dict and a user object as params instead of an entire request object, … -
Getting "Requested runtime is not available for this stack (heroku-20)." error with correct versions of Python
The main issue that I could not find anywhere else is that the bracket contains all the other lines of runtime.txt. which makes me believe something else is wrong but I can't find any solution online. Buildlog attached for reference. -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt ! Requested runtime (asgiref==3.4.1 colorama==0.4.4 comtypes==1.1.10 cycler==0.10.0 dj-database-url==0.5.0 Django==3.2.6 docx2pdf==0.1.7 gunicorn==20.1.0 joblib==1.0.1 kiwisolver==1.3.2 lxml==4.6.3 matplotlib==3.4.3 mysql-connector-python==8.0.26 numpy==1.21.2 Pillow==8.3.2 psycopg2==2.9.1 pyparsing==2.4.7 python-dateutil==2.8.2 python-docx==0.8.11 pytz==2021.1 pywin32==227 scikit-learn==0.24.2 scipy==1.7.1 six==1.16.0 sklearn==0.0 sqlparse==0.4.1 threadpoolctl==2.2.0 tqdm==4.62.3 whitenoise==5.3.0 python-3.9.7) is not available for this stack (heroku-20). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Are there any difference between these two?
I am little lost, from my understanding there should be no difference between these two code lines. As I am creating tuple list in both cases. But I feel like I am wrong, could you point where I am wrong and why. class Meta: ordering = tuple(('-pub_date',)) And class Meta: ordering = ('-pub_date') -
Convert raw query to django orm
I written this query in MySQL and I'm confused of conversion of this query to django orm SELECT * FROM student.student_data where created_by in (select user_id from user_profile where user_location in(7, 8)); -
I've installed packages in python but its still showing module error
I've done few python projects in the past and the modules have worked fine.From few days im getting Error that "no module found" even though ive installed the packages I reinstalled python updated pip tried in Virtual env but I can't find a solution -
While installing Open-Edx we are facing ValueError: Unable to configure handler 'logfile'
I understand it is because python is not able to find the log file so that it logs the exceptions. My question is why it is not able to configure. is it because of improper installation of python or other programs or any other possible reason. -
Problem with performing a groupby count using an annotated field
Context I have a table/model called Article. Within this model, I have several fields such as expiry date, visibility, and status. These fields determine if the Article should be displayed or not. Essentially, the desired logic is like so: display = True if status == 'Private'; display = False if visibility == False; display = False ... For the sake of simplicity, in this post, I'm just going to be using one field: status. The status field is a CharField with choices being 'Private' or 'Public'. In order to work out the display logic, I use annotation. This is relatively simple: all_articles = Article.objects.annotate( display=Case(When(status='Private', then=Value(False)), default=Value(True), output_field=models.BooleanField()) ) displayed_articles = all_articles.filter(display=True) notdisplayed_articles = all_articles.filter(display=False) Goal With this setup, I would like to use Django ORM to perform a count with group by to determine how many articles are being displayed, and how many are not. The outcome would like like this in SQL tabular format: display count True 500 False 2000 Problem This is the natural way to achieve my goal: queryset = Article.objects.annotate( display=Case( When(status='Private', then=Value(False)), default=Value(True), output_field=models.BooleanField() ) ).values('display').annotate(count=Count('id')).order_by() print(queryset) Expectation I'm expecting something like this: <QuerySet [{'display': True, 'count': 500}, {'display': False, 'count': 2000}]> Error However, … -
Canvas: Remove scrollbar functionality and grey border box/outline?
I'm working on a project in Django whereby I have one canvas element superimposed over another with functionality that allows me to mouseover the top canvas to reveal an image loaded into the canvas underneath it. The functionality works great however it seems to be wreaking havoc in other ways, namely: The window width and height are larger than the canvases causing unnecessary scrolling. I want to get rid of this. There is a light grey border around my canvas elements and I can't get rid of it. Tried setting outline and border to none but no dice. I'm also having issues centering the canvases in the window. My gut is telling me these problems have something to do with the fact that my canvas stack is set to absolute position while its parent div is set to relative (this is the functionality that allows me to stack canvases) but this is just a hunch. I've looked at a variety of other similar SO questions, but none of their solutions worked for my code. Any help would be greatly appreciated. Thanks. window.onload = function() { //Create Bottom canvas & context var canvas = document.getElementById('canvas'); var ctxB = canvas.getContext('2d'); //Create Top … -
How to use token generated by knox in api view function
I am using knox and not rest_framework.authtoken. I am also able to generate tokens right now but I am having issue in using it. According to the documentation (https://www.django-rest-framework.org/api-guide/authentication/), an api function view requires @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) I replace Session and Basic to TokenAuthentication but I am getting the error of NameError: name 'authentication_classes' is not defined In my views according to the documentation, i have imported the following: from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated -
Django traceback / cannot import name 'TypeVarTuple' from 'typing_extensions'
Hi all I'm new to django & python. I keep getting this traceback while using django when I tried runserver or migrate. ImportError: cannot import name 'TypeVarTuple' from 'typing_extensions' I already tried 1/ upgrading django with pip 2/ upgrading typing extensions with pip and both didn't work for me... Does anyone faced the same problem and solved? Thank you! -
Django Python ICalendar
I want to upload a file with the extension ICS, after uploading that file only keep the events with code "10059707" and output the download file. This is my code : views.py def calendar_list(request): calendars = CalendarModel.objects.all() return render(request, 'upload_app/calendar_list.html',{ "calendars" : calendars }) def upload_calendar(request): if request.method == "POST": form = CalendarForm(request.POST, request.FILES) g = request.FILES['calendarfile'] gcal = Calendar.from_ical(g.read()) cal2 = Calendar() for component in gcal.walk(): if component.name == "VEVENT": ATTENDEE = component.get('ATTENDEE') SUMMARY = component.get('SUMMARY') if ATTENDEE is not None and '10059707' in ATTENDEE: print("1:{}\n 2:{}\n".format(ATTENDEE,SUMMARY)) event2 = Event() event2.add('attendee',vCalAddress(ATTENDEE)) event2.add('summary', "作業予定あり") cal2.add_component(event2) ***** What can I do in here?******** cal2.to_ical() if form.is_valid(): form.save() return redirect('calendar_list') else: form = CalendarForm() return render(request, 'upload_app/upload_calendar.html',{ "form" :form }) ..... I don't know how I can handle that request in Django to parse ics file. models.py # Create your models here. class CalendarModel(models.Model): calendartitle = models.CharField("ファイル名",max_length=100) calendarfile = models.FileField("ファイル追加",upload_to="icsfile") cover = models.ImageField("ファイルイメージ",upload_to="cover_img", null=True,blank=True) ... -
how can we store Django forms user data to database
I am a newbie to MVC architecture. I just wanted to know, how can we store Django forms data into Database(admin) as we do with models in Django? -
How to display cleaned email data in django import-export
I have this widget: class EmailWidget(CharWidget): def clean(self, value, row=None, *args, **kwargs): if value: email_field = EmailField() if email_field.clean(value): return value return None which I use here: some_email= fields.Field(attribute='some_email', widget=EmailWidget(), column_name='some_email') cleaning is fine but it does not specify the data to be cleaned on the table view in errors. [![enter image description here][1]][1] what I was expecting was something like this: [![enter image description here][2]][2] I only need to specify it and display it among the list of errors in the second row and second column. [1]: https://i.stack.imgur.com/NHc2E.png [2]: https://i.stack.imgur.com/fMar4.png -
I want to scape play store apps categories and subcategories in my django app. When use give a input in app and display on website
I want to scape play store apps categories and subcategories for specific app name that user gives as input. And then store that app categories and subcategories to database as well as display to website instantly. Is their is any way to do this?