Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist
Hi I'm trying to get the newest/latest number in a query set: I use this codeline for that: CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True).get(pk=-1) This is how the queryset looks like: <bound method QuerySet.last of <QuerySet [4, 4, 4, 2, 4, 4, 5, 6, 5, 14, 10, 12]>> # need last number(12) I tried the code above but I get an Error message: store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist. This is my models: class CartQuantity(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) cquantity = models.IntegerField(default=0, null=True, blank=True) Does anyone know how to fix the error or another way of getting the newest number(in this case number 12 in the query set)? -
AWS Elastic Beanstalk Python Django S3 Access Denied cannot upload / read file
I have deployed Python Django server on AWS Elastic Beanstalk. This is how my settings.py file looks like: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'hello_django.storage_backends.PublicMediaStorage' # s3 private media settings PRIVATE_MEDIA_LOCATION = 'private' PRIVATE_FILE_STORAGE = 'hello_django.storage_backends.PrivateMediaStorage' In AWS I created IAM user with AmazonS3FullAccess permission, and I use his AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in settings. The problem is that when I try to read media file from the file link I always get "Access denied" error, even if I specify PublicMediaStorage and give all public access on S3 bucket. Also, when I upload file, the folder (e.g 'media') in bucket does not get created. Do you have idea what could the problem ? -
Django: How to get an object with a file name
Let's say I have a model with a FileField: class Foo(models.Model): file = models.FileField( upload_to='files' ) What would be the best approach for getting an object from the model with the name of the file? Something like: try: foo = Foo.objects.get( file__name='bar.csv', ) except Foo.MultipleObjectsReturned: return something() except Foo.DoesNotExist: return something_else() process(foo) I guess I could add a file_name field into the model, but that seems cumbersome..? -
Error while running server in django after connecting djangorestframework
This error happens after adding rest_framework (pip install djangorestframework) to project but i dont know the reason in this framework or not. Error log, i think, is not enough informative for me. If need to share any file just let me know. Note: I am new in django web api so any your advice would be valuable. Thank you in advance. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' Traceback (most recent call last): File "manage.py", line 22, in … -
Am using drf-spectacular for my Django rest api documentation, how to override our own endpoint
In below code am not able to generate schema for 2 endpoints admin/ and payslip/ urlpatterns = [ # YOUR PATTERNS path('admin/', admin.site.urls),, path('payslip/',include('payslip.urls')) path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), ] -
Django-filter, multiple fields search overriding other parameters! (django-filter)
I am having a spot of trouble making a search box that looks through both the title, and the description of the model, without it over riding everything. I took my example from this: Django-filter, how to make multiple fields search? (with django-filter!) so my current filter looks something like: class QuestionSetFilter(django_filters.FilterSet): search = CharFilter(method='my_custom_filter', label='search') o = OrderingFilter( fields = ( ('date_posted', 'date_posted') ), choices = [ ('date_posted', 'Old first'), ('-date_posted', 'New first'), ] ) class Meta: model = QuestionSet exclude = ['image', 'user', 'date_posted', 'question_set_description', 'question_set_title'] def my_custom_filter(self, queryset, name, value): return QuestionSet.objects.filter( Q(question_set_title__icontains=value) | Q(question_set_description__icontains=value) ) How can I change my custom filter to still chain with the other parameters I want to search with? -
Django urls "overlapping"
Ok. Hi guys. I googled this problem and didn't find anything that would help. Ok so this is my project structure: -myproject -controlpanel -urls.py -views.py -templates -controlpanel -index.html -include -navbar.html -main -urls.py -views.py -templates -main -index.html -partials -navbar.html -myproject -urls.py This is my controlpanel urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('servers', views.servers, name='servers'), ] This is my main urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('join', views.join, name='join'), path('rules', views.rules, name='rules'), path('services', views.services, name='services'), path('stats', views.stats, name='stats'), path('gdpr', views.gdpr, name='gdpr'), path('login', views.login, name='login'), ] This is myproject urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('main.urls')), path('controlpanel/', include('controlpanel.urls')), path('admin/', admin.site.urls), ] Now when user doesn't specify any subdirectory he should be redirected to index.html in app main. The problem is that some {% url 'urlname' %} return urls from other projects. For instance when i used {% url 'index' %} in main apps navbar it used url controlpanel/index which it isn't supposed to do. This also happened to me when i was creating navbar for controlpanel and imported css but i solved it by renaming … -
How can i sort event by current user in Django calendar
I have a problem with sorting events in the Django calendar, namely, I would like to filter them not only by date but also by the user who created the event so that only his events are displayed on the calendar and not other users this is my utils.py file class Calendar(LocaleHTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) print() return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True,): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month,) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal My problem is that I do not know how to apply filtering with the current user in the object … -
Django - How can I implement and ignore case-sensitivity within my model to make the fields unique by character only?
How can I implement a function or method for my username and email fields to ignore case-sensitivity. By current Django standard, both the name John and john are unique by default. I want the mentioned fields to be unique by characters only, ignoring any aspect of captial cases. Is there any simple way of doing this? I want to do this at the database level, so I don't have to constantly repeat hacky code whenever I want to implement. I found this thread: Case insensitive unique model fields in Django? The first answer, creating an SQL index option has me worried because indexes need to be maintained and an index is not always used for a query. Then there's another method that uses citext , the docs mention that this is only possible during first create table migration, that seems like the most simple option, but it requires the most maintaince if you already have a live db. The next option for ease would probably be this method referenced: class MyModelManager(models.Manager): def get_by_username(self, username): return self.get(username__iexact=username) class MyModel(models.Model): ... objects = MyModelManager() I would like to try and replicate that using my model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), … -
Displaying fields not intended to be edited in ModelAdmin
I have a custom contact form for which I create a sent_time field using auto_now_add to save the time when the user had sent the message. I am able to list all the information on the listing view of the admin panel however when I try to enter a specific message I hit the following error: 'sent_time' cannot be specified for GeneralContact model form as it is a non-editable field My attempt to make the fields readonly in the ModelAdmin results in the same error class GeneralContactAdmin(ModelAdmin): """ Admin model for general correspondence via the main contact form on the information page """ model = GeneralContact list_display = GeneralContact.__all__ search_fields = GeneralContact.__all__ readonly_fields = GeneralContact.__all__ ordering = ('-sent_time',) list_filter = ('sent_time', 'has_response') Surely it is possible to be displayed only, perhaps I've done something incorrectly in my models? Here is the base model I use for the contact model class ContactFormBase(models.Model): __all__ = ( 'sent_time', 'sender_name', 'sender_email', 'sender_message', 'has_response', 'responded_on' ) sent_time = models.DateTimeField(auto_now_add=True) sender_name = models.CharField() sender_email = models.EmailField() sender_message = models.TextField() has_response = models.BooleanField( default=False, help_text='Select whether this message has been replied to by an admin.', ) responded_on = models.DateTimeField(blank=True, null=True) panels = [ FieldRowPanel([ FieldPanel('sender_name'), FieldPanel('sender_email'), ]), … -
Logging not working within WebSocketConsumer sub-classes
I have an issue where logging statements are not working in subclasses of WebsocketConsumer. Logger works in the entry point to the daphne application and even above the class declaration but not within the consumer. logger = logging.getLogger(name) logger.info("This log shows up") class TrackNotifyConsumer(WebsocketConsumer): """API Tracking Notifications Consumer""" def connect(self): logger.info("This log DOES NOT show up") async_to_sync(self.channel_layer.group_add)("track", self.channel_name) self.accept() Your OS and runtime environment, and browser if applicable Ubuntu 18.04.4 LTS A pip freeze output: freeze.txt This is deployed via Daphne, nginx -
Celery beat stuck on starting with Django and Redis
In my Django project I have two tasks in two different apps that I want to run periodically with Celery. The worker seems to collect the tasks and the beat seems to collect the schedular. However, the beat stuck on starting (it didn't synchronize the schedules) and never deliver the tasks to the worker. The celery --app=bozonaro worker --loglevel=debug --beat (bozonaro is my django project's name) command prompts the following to me: [2021-02-04 18:23:48,080: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2021-02-04 18:23:48,103: DEBUG/MainProcess] | Worker: Building graph... [2021-02-04 18:23:48,104: DEBUG/MainProcess] | Worker: New boot order: {Timer, Hub, Pool, Autoscaler, StateDB, Beat, Consumer} [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Building graph... [2021-02-04 18:23:48,413: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Heart, Agent, Mingle, Gossip, Tasks, Control, event loop} -------------- celery@LAPTOP-E5L3SQ6N v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 2021-02-04 18:23:48 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: bozonaro:0x7fc00b16d4c0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- … -
Django DecimalField Formatting and Filtering Non-Responsive
The DecimalField output on my template is appearing like this; Total Cost: {'Cost__sum': Decimal('739.900000000000')} when it should appear like this Total Cost: 739.90. Despite my model only having 2 decimal places and trying the DecimalField filters the formatting does not change, it also includes my context variable 'Cost__Sum'. This has not happened in previous apps despite using the same code. Greatly appreciate if someone could point out what is going wrong here. Model.py class ComicInput(models.Model): Cost = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') Value = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') SoldAmt = models.DecimalField(max_digits=10, decimal_places=2, default='0.00') Views.py def home(self): """Renders the home page.""" #excludelist = ('Sold','Wish') if self.user.is_authenticated: DisplaySumCost=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Cost')) DisplaySumValue=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Value')) DisplaySumSoldAmt=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('SoldAmt')) assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Kollector', 'year':datetime.now().year, 'DisplaySumValue': DisplaySumValue, 'DisplaySumCost': DisplaySumCost, 'DisplaySumSoldAmt': DisplaySumSoldAmt, } ) else: assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Collector', 'year':datetime.now().year, } ) Template {% extends "app/layout.html" %} {% load humanize %} {% load l10n %} {% block content %} {% if request.user.is_authenticated %} <section style="border:1px solid black;background-color:lightyellow"> <h3 style="text-align:center"> Collection Summary for {{user.username}} </h3> <div class="row"> <div class="col-md-4"> <b>Total Cost: {{DisplaySumCost|localize}} </b> <b>Total Value: {{DisplaySumValue}} </b> <b>Total Sales: {{DisplaySumSoldAmt}} </b> </div> </div> </section> {% endif %} {% endblock %} -
Django and xhtml2pdf: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte
I have a Django web application and I would like it to product an html pdf. I was sent HTML templates to work with, and out of the three I received, two work and one doesn't. Everytime I acsess this view, it gives me UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte. Here is the full error: UnicodeDecodeError at /documents/973/generate/preliminary 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte The string that could not be encoded/decoded was: ��{% Here is my code: views.py def generatePreliminary(request, fileNumber): claim = ClaimMaster.objects.get(fileNumber=fileNumber) documents = [] for claimz in ClaimSub.objects.filter(claim=claim): docu = Document.objects.filter(claim=claimz) for doc in docu: documents.append(doc) data = { 'claim': claim, 'documents': documents, 'insurers': InsurerLink.objects.filter(claim=claim), 'insured': InsuredLink.objects.filter(claim=claim), } template = get_template('documentApplication/preliminaryreport.html') data_p = template.render(data) response = BytesIO() pdfPage = pisa.pisaDocument(BytesIO(data_p.encode("UTF-8")), response) if not pdfPage.err: return HttpResponse(response.getvalue(), content_type="application/pdf") else: return HttpResponse("Error") preliminary.html template: {% load static %} <html> <head> <style> <!-- /* Font Definitions */ @font-face { font-family: Wingdings; panose-1: 5 0 0 0 0 0 0 0 0 0; } @font-face { font-family: "Cambria Math"; panose-1: 2 4 5 3 5 4 6 3 2 4; } @font-face { font-family: Tahoma; panose-1: 2 11 … -
Get cleaned_data from queryset
Hi How can I get cleaned data from a queryset? And can I use .split() on an queryset? Ex. CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True) The code above prints this: <bound method QuerySet.last of <QuerySet [4, 4, 4, 2, 4, 4, 5, 6, 5, 14, 10, 12]>> # need last number (12) But I only need the number 12 (the newest/latest number added to the model) I tried using .cleaned_data to only get the numbers (without <QuerySet etc.) and .split. I need the number 12 for a while loop. -
CS50W Project 1 WIKI - django paths capitalization problem in some entries
I have an issue with the implementation of Wiki I can't simply understand what's happening. My code so far for urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entries, name="entries"), path("search/", views.search, name="search") ] and for views.py: from django.shortcuts import render from django.http import HttpResponse from django.urls import reverse from django.http import HttpResponseRedirect from markdown2 import Markdown from django import forms from . import util # render wiki's index def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) # take path, remove capitalization and query for a matching entry def entries(request, title): nocase_title = title.lower() entry = util.get_entry(nocase_title) if entry: # convert markdown to html and render the entry route translator = Markdown() html = translator.convert(entry) return render(request, "encyclopedia/entry.html", {"entry":html, "title":nocase_title.upper()}) else: return render(request, "encyclopedia/not_found.html") def search(request): return render(request, "encyclopedia/search.html") My problem is this: In the url, I can't type a pass to wiki/python or wiki/css all in lowercase. Everytime I try it, I get 404 problem returned to me. I don't have issue with the other entries, I can type wiki/django, wiki/git or wiki/html.... But the most strange part is that I can type urls including those words in all caps … -
Django RF. how to get a Django Model with nested relationship
While testing my features in a Django Rest framework App, I need to get an object, let's call it Foo and this object has some nested relationships. I can get it by my making a request with the APIClient as such : class FooTest(TestCase): def setUp(self): self.client = APIClient() def test_foo_feature(self): foo_id = generator.generateFoo().id foo = self.client.get(reverse('foo-detail', args=[foo_id])).data I was wondering if I could call directly my FooSerializer in a certain way to get my Foo object with the nested relationships, instead of passing by the view with the help of the APIClient because simply calling Foo.objects.get(id=foo_id) doesn't return the nested relationships. -
Loading data faster from GraphQL endpoint for React
I have an e-commerce Django App that uses Graphene GraphQL to store some data at the backend. I use React at the frontend to load the data from the GraphQL endpoint. I have a requirement where I need to load all of the products (estimated to be about 100-170 products) in one go. This load is taking a long time at the moment (~7-10 seconds). Is there a way I can use caching to help the data load faster. I have read about this: https://docs.graphene-python.org/en/latest/execution/dataloader/ which seems like an option. Is there a better of doing this? Any help is appreciated -
Add a permission to Django admin panel without a model
I would like to create a custom user permission that is not related to a model that I can assign to users through the django admin panel. I have already tried something like class CustomPermissions(Permission): class Meta: proxy = True verbose_name = "MIDB Has write permission" permissions = ( ('can_write_to_midb', 'Can write to midb') ) admin.site.register(CustomPermissions) And variations on that. Is it possible to have just a user permission without a model that can be assigned through the admin panel? Thank you -
How do I match the model to the parent model, in html?
I have 2 pages, on the first page I create questions in the form, on the second page I want to display these questions and match the questions created on the first page, but I have to manually select the query result (I have 2 questions created). How do I do it dynamically? The question to fit its corresponding Answer model this is my code -> models.py from django.db import models from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100, null=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): print("Test validation only") print(request.POST) return render(request, "question/ans.html", {"form":form, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form … -
clearing browser cache in django
I have a website that I developed using Django. Sometimes I have to change some small css styles or add some new things to the website but every time I need to clear the browser cache by pressing ctrl+f5. obviously, I cant tell everyone else to clear their browser cache every time they want to use the website. what should I do to make the app forcingly clear the cache for everyone? thanks for your responses -
Passing variables from a from to a view in Django
Working on a site where Managers can view database entries made by Reps. I want Managers to be able to specify search dates for the reports I'm building, but for the life of me I can't figure out how to pass the values from a simple Django form with two DateFields to my view that would then use those variable to query the database. models.py class ReportRequestForm(forms.Form): start_date = forms.DateField() end_date = forms.DateField() views.py def weekly_rep_report(request, start_date=datetime.today(), end_date=datetime.today()): weekly_visit_objects = Store.objects.filter(visit_filed__range=(start_date, end_date)) My view/html works fine with the default values provided in the arguments, but I'm lost as to how to have the ReportRequestForm submit data to the weekly_report_view as most of my forms are adding/editing items in the database. -
name 'HTML' is not defined
I am working with the Django project and trying to render a pdf with WeasyPrint. my views.py: def WeasyPDF(request): paragraphs = ['first paragraph', 'second paragraph', 'third paragraph'] html_string = render_to_string('app/pdf_report.html', {'paragraphs': paragraphs}) html = HTML(string=html_string) html.write_pdf( target='/tmp/mypdf.pdf', stylesheets=[ # Change this to suit your css path settings.BASE_DIR + 'css/bootstrap.min.css', settings.BASE_DIR + 'css/main.css', ], ); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response return response But it says the following error: name 'HTML' is not defined I was following this tutorial: link. How can I fix it? -
How to use updateview without createview in django python?
I'm creating shop profile by create function so i'm not using createview for that but now I wanted to update that default shop profile with updateview , right now i'm getting following here : Exception Value: ShopProfileDetailView is missing a QuerySet. Define ShopProfileDetailView.model, ShopProfileDetailView.queryset, or override ShopProfileDetailView.get_queryset(). models.py class ShopProfile(models.Model): shop_owner = models.OneToOneField(User, related_name='shop_profile', on_delete=models.CASCADE) shop_address = models.CharField(_("shop address"), max_length=255) title = models.CharField(("shop"), max_length=50) slug = models.SlugField(blank =True,unique = True) create_date = models.DateTimeField(("create date"), default=timezone.now) shop_bg =models.ImageField(_("Shop background image"), upload_to="shop_back_grounds",default="shop_default.jpeg" ,height_field=None, width_field=None, max_length=None) customers = models.ManyToManyField(User, related_name="customers", verbose_name=_("coutomers")) customers_favorite = models.ManyToManyField(User,related_name="customers_favorite", verbose_name=_("customers favorite")) views.py class ShopProfileDetailView(DetailView): Shop = ShopProfile template_name='shops/shop_profile.html' class ShopProfileUpdateView(UpdateView): model = ShopProfile form_class = ShopProfileForm template_name = 'shops/shop_profile_update.html' def get_object(self, *args, **kwargs): return self.request.user.shop_profile def get_form_kwargs(self, *args, **kwargs): form_kwargs = super().get_form_kwargs(*args, **kwargs) form_kwargs['request'] = self.request return form_kwargs def get_context_data(self, *args, **kwargs): context = super(ShopProfileUpdateView, self).get_context_data(*args, **kwargs) update_form = ShopProfileForm(instance = self.request.user.shop_profile) context['form']=update_form return context def form_valid(self, form): if self.request == 'POST': form.save() return super().form_valid(form) urls.py app_name = 'shops' urlpatterns = [ path('profile/<str:slug>/',views.ShopProfileDetailView.as_view(),name='shop_profile'), path('profile/update/<str:slug>/',views.ShopProfileUpdateView.as_view(),name='shop_profile_update') ] If more code if require then tell me in a comment section. traceback here you will get complete traceback.. -
How to reload page while keeping FormGroup content alive
I have got a filter function in a sidenav in my application which filters the list of profiles. However when I submit the filter function in the HTML I call this onFilterButtonSubmit function (see below) which should give my profile-list.component.ts the parameters while also reloading the page. onFilterButtonSubmit(minA, maxA, gen): void { this.profileService.minAge = minA; this.profileService.maxAge = maxA; this.profileService.gender = gen; this.router.navigate(['/home']); } The site is not being reloaded though. Only when I am on another page (f.e. profile-page), parsing the filter criteria and clicking on Filter, it correctly reroutes me to /home and displays the results I filtered for. I also tried using window.location.reload(); which reloads the page successfully but does not save the FormField content. I am kinda lost here, any help is appreciated. Not sure which other code parts are relevant but let me know and I will add it to the question. I am using Angular and Django for the backend. app.component.ts export class AppComponent implements OnInit { title = 'frontend'; isLoggedIn = false; filteredFormControl: any = new FormControl(''); filteredProfilesFormGroup: FormGroup; profiles: Profile[]; public isFiltered: boolean; constructor(public userService: UserService, public profileService: ProfileService, private router: Router) { } ngOnInit(): void { this.filteredProfilesFormGroup = new FormGroup({ minAge: new …