Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit .py File runtime
I have a simple error. I need to edit a .py file durring runtime and use that after the edit. Now i can edit and add my new lines to it. After running the script it comes to the exact position and runs it and creats the file the correct way but! I will get a 500 Error and the rest of the code will not be compiled. Following code i am running. with open("D:/django/alpha/alpha/settings_inspectdb2.txt", "a") as file: file.write("\t\t},") file.write("\n\t\t'" + projectname + "': {") file.write("\n\t\t\t\t'ENGINE': engine,") file.write("\n\t\t\t\t'NAME': " + projectname + ",") file.write("\n\t\t\t\t'USER': user,") file.write("\n\t\t\t\t'PASSWORD': pwd,") file.write("\n\t\t\t\t'HOST': host,") file.write("\n\t\t\t\t'PORT': port,") file.write("\n\t\t}") file.write("\n}") with open("D:/django/alpha/alpha/settings_inspectdb2.txt", 'r') as f1: lines = f1.readlines() with open("D:/django/alpha/api_manager/settings_inspectdbF.py", 'w+') as f2: for line in lines: f2.write(line) Does anyone know how to solve that error? -
why does site matching query not exist.?
I'm trying to do jwt authentication. I'm using some code from django-rest-auth package for registration and I have this problem for both registration endpoint and admin area. I know that a lot of people asked this question before me, but god knows why the solution isn`t working in my case. I`ve tried this in shell: >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'answerly.com' >>> site.name = 'answerly.com' >>> site.save() My settings: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # local apps 'pages', 'accounts', # third party packages 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', ] ... REST_USE_JWT = True ... Urls: from django.contrib import admin from django.urls import path, include from rest_auth.registration.views import RegisterView # from rest_auth.views import LoginView, LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.api.urls')), path('accounts/registration/', RegisterView.as_view(), name='register'), # path('rest-auth/registration/', include('rest_auth.registration.urls')) ] I have this for the common solution: raceback (most recent call last): File "/home/valentyn/Dev/Answerly/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/valentyn/Dev/Answerly/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: django_site.domain The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> … -
CSS attributes in HTML page show blank (style="") when they are not | NGINX + Django
All static files in the project are being loaded (how do I know this? Bootstrap, and Fontawesome, which I have locally, work fine), everything seems to be in order, but, for some reason, all the CSS attributes in the HTML pages are rendered blank when in the source code this is not the case. I haven't been able to find an answer online, and since I don't really know what files to include from my code or settings, I think a simple code sample of the problem should suffice. html source: <div style="width:100px;"></div> html live: <div style=""></div> I would give more information if I knew what would be useful. I don't know where the problem resides. I've never had this happen. -
AttributeError: 'module' object has no attribute 'compare_digest'
I configured user authorization via GoogleOauth2.0 (social-auth-app-django). Entries in the social_django / usersocialauth / application are not created. Locally everything works, but an error occurs on the server. After selecting an account to log in via Google, it redirects to the page complete/google-oauth2/ + GET paramteres In Traceback, I get the following: Traceback ERROR 2019-07-31 19:25:29,351 base 4745 139713585624832 Internal Server Error: /complete/google-oauth2/ Traceback (most recent call last): File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_django/views.py", line 33, in complete *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/actions.py", line 43, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/utils.py", line 251, in wrapper return func(*args, **kwargs) File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/oauth.py", line 388, in auth_complete state = self.validate_state() File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/backends/oauth.py", line 91, in validate_state elif not constant_time_compare(request_state, state): File "/home/deploy/.virtualenvs/finbee/lib/python2.7/site-packages/social_core/utils.py", line 227, in constant_time_compare return hmac.compare_digest(val1, val2) AttributeError: 'module' object has no attribute 'compare_digest' settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) TEMPLATES … -
How to disallow creation of object if related foreign key doesn't exists?
Here is the setup class A(Model): pass class B(Model): a = ForeignKey(A, on_delete=CASCADE) assert A.objects.all().count() == 0 try: B(a_id=1) except IntegrityError: print('error') # ... another logic to deal with situation DB is PostgreSQL. There are no A objects yet (at least with id=1). I try to create object B using the id of some hypothetical object A fetched from the 3rd party. Expectation If there is no object A -> IntegrityError is thrown -> deal with it (eg create object A with id=1 and rerun). Reality Object B is created anyway despite having a foreign key constraint, IntegrityError is thrown but is not fetched by try/except. Everything is messed up. I don't what to get_or_create object A beforehand because I will end up with 2 queries every time I want to create B (and I need to create it many times while most of the time needed object A is already in DB) -
Django contact form doesnt submit
I am trying to set up a contact form. I have implemented the Django-crispy-forms and now my form is not submitted (I don't have any errors). I've added action="" to my form in my template without any success. forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=100, help_text='Enter your name or username') email = forms.EmailField() message = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'cols': 40}), help_text='Example: I forgot my password!') views.py def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "From {0}:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('PLM_Tool contact', message, sender_email, ['myadress@gmail.com']) return redirect('home:index') else: form = ContactForm() return render(request, 'accounts/contact.html', {'form': form}) urls.py app_name = 'accounts' urlpatterns = [path('contact/', views.contact_us, name='contact'),] contact.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block main %} <form method="post" action=""> {% csrf_token %} <div class="row"> <div class="col-6"> {{ form.name|as_crispy_field }} </div> <div class="col-6"> {{ form.email|as_crispy_field }} </div> <div class="col-6"> {{ form.message|as_crispy_field }} </div> </div> </form> <button type="submit" class="btn btn-success">Send</button> <a href="{% url 'home:index' %}" class="btn btn-danger">Cancel</a> <br><br> {% endblock %} -
How to parse XML into Django model?
I have Playlist and Track models. Playlist has XML-file field, Track has Playlist as a foreign key. From where I shoud run python parser script to parse XML into Track instances as soon as I add new Playlist instance? -
How to control color theme using configurations in Django admin?
Basically I have Django project (using Docker) installed on many sites with different logos, content, etc. Problem seems to be that also theme colors should be configurable for each site. Optimal solution would be to have some color codes (primary, secondary, etc) configurable, which would eventually change CSS content. Project uses Bootstrap 4, which uses SASS (SCSS) that compiles as CSS, so now my GIT contains single SCSS file and compiled final CSS should be different on each site. All solutions I have figured out seem to be hacks, so I wonder is there any "clean solutions" for this? Solution don't have to be necessarily "real time", like configurations in Django Admin UI, but that would definitely be plus. Anyway, something that works even if I make changes to common code base and update that to all sites. -
Why Yoko Ono shouldn't have blog?
According to Django documentation: if self.name == "Yoko Ono's blog": return # Yoko shall never have her own blog! else: super().save(*args, **kwargs) # Call the "real" save() method. Why Yoko Ono shouldn't ever have her own Blog? ;) -
Django using generic views, "POST /''/ HTTP/1.1" 405 0, Method Not Allowed (POST)
Trying to define Create, Edit and list page for each model I have, after using the Generic view in Django UpdateView and CreateView. after save when forwarding to the listview an HTTP ERROR 405 appears without saving any data. I am using Django UpdateView for update form, CreateView for add and SingleTableView for the list. Models.py class PartnerOrganization(TimeStampedModel): name = models.CharField( max_length=100, unique=True, verbose_name=_('Name')) coordinator = models.ForeignKey( Coordinator, blank=False, null=True, related_name='+', verbose_name=_('Coordinator') ) land_phone_number = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner land phone number') ) fax_number = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner fax number') ) email = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner email') ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=False, null=True, related_name='+', verbose_name=_('Created by') ) class Meta: ordering = ['name'] def __unicode__(self): return self.name def get_absolute_url(self): return reverse("learningcenters:teacher_list") In Views.py class ListingPartnerView(LoginRequiredMixin, GroupRequiredMixin, FilterView, ExportMixin, SingleTableView, RequestConfig): table_class = PartnerTable model = PartnerOrganization template_name = 'learningcenters/partner/list.html' table = BootstrapTable(PartnerOrganization.objects.all(), order_by='id') # filterset_class = TeacherFilter group_required = [u"UNICEF"] def get_queryset(self): force_default_language(self.request) if self.request.user.groups.filter(name__in=['UNICEF']).exists(): return PartnerOrganization.objects.all() class AddPartnerView(LoginRequiredMixin, GroupRequiredMixin, CreateView): template_name = 'bootstrap4/common_form.html' form_class = PartnerForm queryset = PartnerOrganization.objects.all() # success_url = '/learningcenters/teacher/list/' group_required = [u"UNICEF"] def get_absolute_url(self): # return reverse("learningcenters:teacher_update", kwargs={"pk": self.id}) return reverse("learningcenters:partner_list") def form_valid(self, form): print(form.cleaned_data) form.save(self.request) return super(AddPartnerView, self).form_valid(form) class … -
Django JsonField Array data query
I have a jsonfield in Postgres db and data like below: income_info = [ { "id": "1", "name": "A", "min_income": 22000 }, { "id": "2", "name": "B", "min_income": 40000 }, { "id": "3", "name": "C", "min_income": 22000 } ] Now want to use gte and lte over the django orm queryset. Already tried Employee.objects.filter(income_info__min_income__lte = 4000000) but did not work at all. -
Receive Radio button value in React and Django
I have two types of users in my app i.e. supplier and teacher and a signup form in my react which contains Radio buttons to select either of them but I am unable to save the value of the radio buttons in my django ORM Here's the Code: SignUpForm.js import React from 'react'; import PropTypes from 'prop-types'; class SignupForm extends React.Component { state = { username: '', password: '', type: '', }; handle_change = e => { const name = e.target.name; const value = e.target.value; this.setState(prevstate => { const newState = { ...prevstate }; newState[name] = value; console.log(newState); return newState; }); }; render() { return ( <form onSubmit={e => this.props.handle_signup(e, this.state)}> <h4>Sign Up</h4> <label htmlFor="username">Username</label> <input type="text" name="username" value={this.state.username} onChange={this.handle_change} /> <label htmlFor="password">Password</label> <input type="password" name="password" value={this.state.password} onChange={this.handle_change} /> <label htmlFor="type">User type</label> <input type="radio" name="type" value="1" checked={this.state.type == "1"} onChange={this.handle_change} />Shipper <input type="radio" name="type" value="0" checked={this.state.type == "0"} onChange={this.handle_change} />Supplier <input type="submit" /> </form> ); } } export default SignupForm; SignupForm.propTypes = { handle_signup: PropTypes.func.isRequired }; Serializers.py from rest_framework import serializers from .models import Quiz from rest_framework import serializers from rest_framework_jwt.settings import api_settings from .models import User class TodoSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields = ('id', 'origin', 'destination', 'scheduled_date') … -
How do fix "Installed 0 object(s) (of 4) from 1 fixture(s)"?
I am trying to install a fixture. Django finds the fixture file but does not install the file. My model is this: class TipoCondominio(models.Model): descricao = models.CharField(max_length=30) criado = models.DateTimeField(auto_now_add=True) alterado = models.DateTimeField(auto_now=True) class Meta: db_table = 'tipo_condominio' def __str__(self): return self.descricao I set in the settings.py file the path: FIXTURE_DIRS = ( os.path.join(BASE_DIR, "fixtures",), ) My fixtures file is this: [ { "model" : "tipos.TipoCondominio", "pk" : 1, "fields" : { "descricao" : "Residencial" } }, { "model" : "tipos.TipoCondominio", "pk" : 2, "fields" : { "descricao" : "Comercial" } }, { "model" : "tipos.TipoCondominio", "pk" : 3, "fields" : { "descricao" : "Ambos" } }, { "model" : "tipos.TipoCondominio", "pk" : 4, "fields" : { "descricao" : "Outro" } } ] When I run the command: python manage.py loaddata tipo_condominio.json I recive: Installed 0 object(s) (of 4) from 1 fixture(s) And... The fixtures don't install in database. I would like the fixtures to be installed. Can anyone help? -
How can I solve the following problem?:UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list
Good morning, I present the following warning and I have not been able to solve it, it adds ordering properties and nothing: C: \ Users \ P05016 \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ rest_framework \ pagination.py: 198: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: QuerySet. paginator = self.django_paginator_class (queryset, page_size) class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination ordering = ['id_interface'] filterset_class=InterfacesFilter -
Create pagination for django elastic search result and send response?
I have implemented Django-elastic-search-dsl into my project and it works fine, but now i want my result to be paginated. I have tries basic django pagination and it did not work, so any ideas will be helpful. This is my views.py for search def search(request): if request.method == 'GET': q = request.GET.get('q') if q: p = Q("multi_match", query=q, fields=['title', 'description', 'status', 'media_source'], type='phrase_prefix') s = PostDocument.search().query(p) response = s.execute() else: response = '' response_list = [] for items in response: response_list.append({"title": items.title, "preview_path": items.preview_path, "description": items.description, "start_date": items.start_date, "end_date": items.end_date, "status": items.status, "media_source": items.media_source, "thumbnail_path": items.thumbnail_path, "published_date": items.published_date}) return HttpResponse( json.dumps(response_list, indent=4, sort_keys=True, default=str), status=200, content_type="application/json" ) Expected results : To send response data with pagination Actual results : Only search query result data. -
CSS attributes in HTML page show blank (style=""), when they are not | NGINX + Django [on hold]
All static files in the project are being loaded (how do I know this? Bootstrap, and Fontawesome, which I have locally, work fine), everything seems to be in order, but, for some reason, all the CSS attributes in the HTML pages are rendered blank when in the source code this is not the case. I haven't been able to find an answer online, and since I don't really know what files to include from my settings, I think a simple code sample of the problem should suffice. html source: <div style="width:100px;"></div> html live: <div style=""></div> -
How to add Id_card_number input field in django admin page whenever I add new user in admin?
I have a problem which I am searching for so many days but not finding an answer. I want new field to be appeared by the name of Id_card_number whenever I click add user in django admin page. Remember that Id_card_number is appearing in registration page but it not appearing in django admin page. Please help. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id_card_number = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id_card_number'] register.html <form method="POST"> {%csrf_token%} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-size: 50px">Join Today</legend><br> {{form|crispy}}<br> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> -
ModuleNotFoundError: No module named 'app_name'
I created a new app using python manage.py startapp associations I added it to installed apps but when I try to call the models inside management commands -fill_brands_table, I'm getting these error: from associations.models import Brand ModuleNotFoundError: No module named 'associations' settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'associations', ] management command -fill_brands_table: from django.core.management import BaseCommand from associations.models import Brand #failed here directory structure: associations/ management/ commands/ fill_brands_table.py __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py -
How can I import background from background_tasks in django. method gives error
I want to use django background-task but from background_task import background gives error How can I remove this error from my code. So far I have followed the documentation and have implemented this. views.py from background_task import background @background(schedule=60) def main(request): # First we have to create our client client =RestApiClient(version='9.0') settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'offense', 'background_task', ] Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\kiran.tanweer\appdata\local\programs\python\python37-32\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\kiran.tanweer\appdata\local\programs\python\python37-32\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\kiran.tanweer\Envs\dash\lib\importlib\__init__.py", line 127, in … -
Django WeasyPrint - Export filtered list
So I've created a pdf file from a ListView called "OrderListView". Now I would like to pass a queryset to the pdf file. I rewrote my listview as a function view for more clarity. I need to find a way to pass the queryset to the pdf view. I'm using django-filter to create the filtered view. I have the following; filters.py class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = { 'start_date': ['gte'], 'end_date': ['lte'], } views.py from .filters import * # View to show a filtered list using django-filter def order_list(request): order_list = Order.objects.all() order_filter = OrderFilter(request.GET, queryset=order_list) return render(request, 'orders/order_list.html', { 'filter': order_filter, }) # View to create a pdf file from the filtered view using WeasyPrint def order_list_pdf(request): order_list = Order.objects.all() order_filter = OrderFilter(request.GET, queryset=order_list) response = HttpResponse(content_type="application/pdf") response['Content-Inline'] = 'attachment; filename=filtered_list.pdf'.format() html = render_to_string('pdf/pdf_booking_list_arrivals.html', { 'filtered_list': order_list, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response So I have tried using query = request.GET.get('q','') And pass the query with the url <a class="btn" href="{% url 'order_list_pdf'?q={{ query }} %}">Create PDF</a> This does create the query in the url but does not filter the list. The generated pdf is working, I just need to find a way to … -
How can I use two variables in the urls.py with Django?
Hello I have this line in my urls.py using Django : re_path(r'exporting/(?P<var1>)/(?P<var2>.+)', views.myfunction, name='myfunction') And actually in my js file the url looks like something like this : window.location = Url + 'pdf/myfunction/' + var1 + '/' + var2 + ''; But it does not work when I try to see the page... Could you help me please ? Thank you very much ! -
django - how to display list objects from model in 'base.html' and extends it to all other templates
I have a navbar in "base.html" and i want to list objects from model on it, so this list be visible on all other template that extends 'base.html' 'base.html' <nav> {% for category in categories %} <a href="#">{{ category.category_name }}</a> {% endfor %} </nav> models.py class Categories(models.Model): category_name = models.CharField(max_length=100, null=True) views.py class NavbarView(ListView): model = Categories template_name = 'base.html' context_object_name = 'categories' urls.py path('nav/', views.NavbarView.as_view(), name='nav') this makes categories list visible only on 'nav/' urls but not in all templates that extends 'base.html how can i do this ? thanks -
'Save html form data in database' django
I'm trying to save name and email from HTML from using django in postgres database, in action tag, function name is mentiond but insted of using that function, django is passing that data to a new page of same function name HTML <form class="newsletter_form d-flex flex-md-row flex-column align-items-start justify-content-between" action="subscribe" method="post"> {%csrf_token%} <div class="d-flex flex-md-row flex-column align-items-start justify-content-between"> <div> <input name="subname" type="text" class="newsletter_input newsletter_input_name" id="newsletter_input_name" placeholder="Name" required="required"> <div class="input_border"></div> </div> <div> <input name="subemail" type="email" class="newsletter_input newsletter_input_email" id="newsletter_input_email" placeholder="Your e-mail" required="required"> <div class="input_border"></div> </div> </div> <div><button type="submit" class="newsletter_button">subscribe</button></div> </form> views.py def subscribe(request): if request.method == 'POST': subname = request.POST['subname'] subemail = request.POST['subemail'] sub = User.objects.create_user(subname=subname, subemail=subemail) sub.save(); return redirect('/') else: return redirect('/') url.py from django.urls import path from . import views urlpatterns = [ path("register", views.register, name='register'), path("login", views.login, name='login'), path("logout", views.logout, name='logout'), path("subscribe", views.subscribe, name='subscribe') ] this is error "image" [1]: https://imgur.com/a/8kh1Qbe "tooltip" -
How to split one form fields into multiple fields of a model in django?
This question is similar to Using multiple input fields for one model's attribute with django and How to render two form fields as one field in Django forms? What I need is basically the opposite of MultiValueField where I can save data from one form field - Name into two model fields - Firstname, Lastname. I'm unable to find any such thing like the opposite of MultiValueField. Can someone please suggest me what is the better way to do it. -
Value error on Image field when trying to comvert model to dict
I have 2 models, 1st is Garage class Garage(models.Model): name = models.CharField(verbose_name=_('Garage'), max_length=200) @property def cars(self) -> list: from django.forms.models import model_to_dict cars = [] for i in Car.objects.filter(garage=self.id): cars.append(model_to_dict(i)) return cars def __str__(self): return self.name class Meta: verbose_name = _('Garage') My 2nd model is Car, class Car(models.Model): name = models.CharField(verbose_name=_('Car Name'), max_length=200) garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2) image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None) def __str__(self): return self.name class Meta: verbose_name = _("Car") verbose_name_plural = _("Cars") Now, when I try to run, the property 'cars' in the Garage model throws ValueError. ValueError: The 'image' attribute has no file associated with it. The complete error log is: Traceback (most recent call last): File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 107, in render allow_nan=not self.strict, separators=separators File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/json.py", line 28, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.7/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File …