Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add extra context to a Django Flatpages template
The flatpage() view in Django's Flatpages app passes a single context item to templates, flatpage. I'd like to add more data to the context and the only way I can think of is to copy both the flatpage() and render_flatpage() functions from the original views.py into a new app. And then in my urls.py where I have this: from django.contrib.flatpages import views from django.urls import path urlpatterns = [ path("about/", views.flatpage, {"url": "/about/"}, name="about"), ] instead import from myapp import views to use my new custom view. Both of my copies of the functions would be exactly the same as originals, except render_flatpage() would add more context data. This seems over the top, copying so much code unchanged. But I don't have a better idea. I don't want to create a custom context_processor for this, because this context is specific to each Flatpage, and should not be used on on other pages. -
uWSGI always returns index.html if it can't find appropriate route in the app
I have and Django application deployed with uWSGI from which i'm also serving static files that contain index.html, javascript files built by Angular and bunch of other assets that are most images. When i did some light penetration testing, i observed some weird responses. Request like: GET /api/users/123/ returned success without any problem and i got the JSON with the specific user. Request like: GET /api/users/&document.vulnerable=true;/ returned 200 OK, and the result was just the index.html page. From my light inspecting by now, it seems if the values that are being inserted in the fuzzing process in the place /api/users/$fuzz_insert$/ contain any combinations of dots (.) or slashes (/), it cannot match it against any route in the application, and it just returns the index.html page. When i'm testing this exact same request with Django locally, i get the 404 error and page where it says that the specific url cannot be matched, even when dots and slashes are properly encoded. So i assume at first that Django has something against dots and slashes in the URL. But more confusing to me is that when deployed with uWSGI, it seems that if the 404 error in the same manner on … -
Django UpdateView FileField not dispalayed in form
model.py class Payments(models.Model): STATUS_CHOICES = ( ('', 'Нажмите на поле, чтобы выбрать статус оплаты'), ('true', 'да'), ('false', 'нет'), ) CHOICES_NAME_SERVICE = (('','Нажмите на поле, чтобы выбрать вид услуги'), ('Коммунальная услуга','Коммунальная услуга'), ('Капитальный ремонт','Капитальный ремонт'),) flats=models.ForeignKey(Flat,on_delete=models.PROTECT) name_flat=models.CharField(max_length=60, ) name_service=models.CharField(max_length=30,choices=CHOICES_NAME_SERVICE) slug=models.SlugField(max_length=60) amount_of_bill=models.DecimalField(max_digits=10,decimal_places=2) amount_of_real=models.DecimalField(max_digits=10,decimal_places=2) date_of_bill=models.DateField() date_of_payment=models.DateField(auto_now_add=True) status_payment=models.CharField(max_length=5,choices=STATUS_CHOICES,) comments=models.TextField(blank=True) bill_save_pdf=models.FileField(upload_to='Bill_pdf/%d/%m/%Y/') def __str__(self) -> str: return f'{self.name_flat}' class Meta: ordering=['name_flat'] def save(self, *args, **kwargs): self.slug = slugify(self.name_service) super().save(*args, **kwargs) def delete(self, *args, **kwargs): self.bill_save_pdf.delete() super().delete(*args, **kwargs) view.py class UpdatePayments(UpdateView): model=Payments form_class=PaymentsForm template_name='myflat/add_payment.html' context_object_name='name_flat' def get_success_url(self): print(self.object.pk) return reverse('HistoryPamentsByService' ,kwargs= {'slug':self.object.slug,'flats_id': self.object.flats_id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) payment=Payments.objects.get(pk=self.kwargs['pk']) context['form']=PaymentsForm(instance=payment) print(self.request.POST) return context forms.py class PaymentsForm(forms.ModelForm): class Meta: model=Payments fields=['name_service','amount_of_bill','amount_of_real', 'date_of_bill','status_payment', 'comments','bill_save_pdf'] labels = { 'name_service': ('Название услуги'), 'amount_of_bill': ('Сумма счета'), 'amount_of_real': ('Оплачено'), 'date_of_bill': ('Дата счета'), 'status_payment': ('Статус оплаты'), 'comments': ('Комментарий'), 'bill_save_pdf': ('Счет'), } widgets={ 'name_service':forms.Select(attrs={"class":"form-control"}), 'amount_of_bill':forms.NumberInput( attrs={"class":"form-control",'placeholder':'Сумма счета 0.00руб'}), 'amount_of_real':forms.NumberInput( attrs={"class":"form-control",'placeholder':'Оплачено 0.00руб'}), 'date_of_bill':forms.DateInput(format=('%Y-%m-%d'), attrs={"class":"form-control",'placeholder':'Дата счета','type':'date'}), 'status_payment':forms.Select(choices=(('','None'),), attrs={"class":"form-control"},), 'comments':forms.Textarea( attrs={"class":"form-control",'placeholder':'Комментарий...','rows':2}), 'bill_save_pdf':forms.FileInput( attrs={"class":"form-control",'placeholder':'Счет'}), } urls.py urlpatterns = [ path('',CreateNewFlat.as_view(),name='CreateFlat'), path('list_flats',ListCreatedFlats.as_view(),name='ListCreatedFlats'), path('add_payment/<int:pk>/',AddPayment.as_view(),name='AddPayment'), path('group_payments/',GroupPayments.as_view(),name='GroupPayments'), path('history_by_service/<slug:slug>/<int:flats_id>/', HistoryPamentsByService.as_view(),name='HistoryPamentsByService'), path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'), path('DelPayment/<int:pk>/',DelPayment.as_view(),name='DelPayment'), ] history_by_service.html {% extends "base.html" %} {% block title %} История платежей по видам услуг {% endblock title %} {% block sidebar %} <table class="table table-lg table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">Название квартиры</th> <th scope="col">Услуга</th> <th scope="col">Сумма по счету</th> <th … -
Is there a way to get a list of Factory Boy subfactory objects from with the correct Django object type?
I have a factory boy factory that uses Django. I need to access a list of the generated objects from a SubFactory. However, whenever I attempt to get that list, I receive TypeErrors that say that my generated objects are "SubFactory" instead of the type of the object I actually need. Any idea what I'm missing? # factories.py class PartNoRelationFactory(factory.django.DjangoModelFactory): class Meta: model = PartNoRelation id = factory.Sequence(lambda n: n + 1) parent_part_no = factory.SubFactory(PART_NO_FACTORY) child_part_no = factory.SubFactory(PART_NO_FACTORY) # test_factories.py def mock_child_part_nos(arg_1: PartNo) -> 'list[PartNo]': mock_part_no_relation_one = PartNoRelationFactory() mock_part_no_relation_two = PartNoRelationFactory() mock_part_no_relation_three = PartNoRelationFactory() return [ mock_part_no_relation_one.child_part_no, mock_part_no_relation_two.child_part_no, mock_part_no_relation_three.child_part_no ] # error: "Expression of type "list[SubFactory]" cannot be assigned to return type "list[PartNo]" -
H13 (Connection closed without response) errors on Heroku scale down
I am running Django app in Docker image with uWSGI, supervisor and nginx on Heroku. I am often getting H13 (Connection closed without response) errors when the app is scaling down: This problem generates following log events: 2022-10-12T09:35:13.231318+00:00 heroku web.3 - - State changed from up to down 2022-10-12T09:35:13.774228+00:00 heroku web.3 - - Stopping all processes with SIGTERM 2022-10-12T09:35:14.028602+00:00 heroku router - - at=error code=H13 desc="Connection closed without response" method=GET path="/comments/api/assets-uuidasset/xxxx-xxxx-xxxx-xxxx-xxxxx/count/?_=1665564563" I expect the problem lies in either the socket not closing on SIGTERM signal or nginx not closing with the right signal or something similar. The first case is described in this article regarding Puma and Ruby: https://www.schneems.com/2019/07/12/puma-4-hammering-out-h13sa-debugging-story/ The second case is described here: https://canonical.com/blog/avoiding-dropped-connections-in-nginx-containers-with-stopsignal-sigquit -
Error Deploy Django Project to Heroku "heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" "?
Error : 2022-10-12T15:20:31.186252+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15 2022-10-12T15:20:31.284067+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [INFO] Shutting down: Master 2022-10-12T15:20:31.284096+00:00 app[web.1]: [2022-10-12 15:20:31 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-10-12T15:20:31.457411+00:00 heroku[web.1]: Process exited with status 3 2022-10-12T15:20:31.847763+00:00 heroku[web.1]: State changed from up to crashed 2022-10-12T15:20:35.000000+00:00 app[api]: Build succeeded 2022-10-12T15:22:25.882709+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=bcbbfbfa-aae2-416d-bfbe-1c972b39dd77 fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https (venv) D:\project upload\dataimprovement>heroku logs --dyno router 2022-10-12T15:06:42.844541+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=e6128a90-7896-4662-b9fd-812b0304a02e fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https 2022-10-12T15:06:43.900566+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=dataimprovement.herokuapp.com request_id=4475ddaf-1fd0-4bb2-a744-b26e35ec130f fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https 2022-10-12T15:22:25.882709+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=dataimprovement.herokuapp.com request_id=bcbbfbfa-aae2-416d-bfbe-1c972b39dd77 fwd="180.252.117.170" dyno= connect= service= status=503 bytes= protocol=https This is my structure project: [enter image description here][1] 1. Then This is my app #layanan : [enter image description here][2] 2. Then this is my app #Items : [enter image description here][3] Can you guys tell me what wrong with my code when I deploy to heroku hosting ?, Because I was looking this error more than 2 days and I don't know how to … -
Python Integration the Payment System of Bank
I am trying to integrate the Bank's payment system on my Django-based website. As it said in documentation, I need to send parameters to their server (and then the new window should appear and the client should fill his card credentials there). Documentation (part 1): Documentation (part 2): Documentation (part 3): I am new in integration such services (payment) and need some help or broad explanation what to do, why do to that, and how. Additionally, I was pretty sure that the following code wouldn't work fine but why. import requests def send_request(): url = 'https://ecomm.pashabank.az:18443/ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.184.1.132&msg_type=SMS' response = requests.post(url) print(response) def main(): send_request() if __name__ == '__main__': main() causes raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='ecomm.pashabank.az', port=18443): Max retries exceeded with url: /ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.172.184.123&msg_type=SMS (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)'))) Overall, I need help of everything happening behind the scenes. Huge thanks in advance guys! Note: I have also received some certifications from bank (I assume to assure the connection safety). But how I use it and when? -
How to get integer ID of Django Factory Boy object?
I have a factory boy factory that uses Django that I need to access the ID of the generated objects. However, whenever I attempt to get that ID, I receive TypeErrors. Any idea what I am missing? # factories.py class PartNoFactory(factory.django.DjangoModelFactory): class Meta: model = PartNo id = factory.fuzzy.FuzzyInteger(1, 1000000, step=1) # have also tried id = factory.Sequence(lambda n: n + 1) # have also tried id = int(factory.Sequence(lambda n: n + 1)), which results in error "type Sequence cannot be assigned to paramater "_x" # test_factories.py def mock_child_part_nos(arg_1: PartNo) -> 'list[int]': mock_part_no_one = PartNoFactory() mock_part_no_two = PartNoFactory() mock_part_no_three = PartNoFactory() return [mock_part_no_one.id, mock_part_no_two.id, mock_part_no_three.id] # if using FuzzyInteger: "Expression of type "list[FuzzyInteger]" cannot be assigned to return type "list[int]" # if using Sequence: "Expression of type "list[Sequence]" cannot be assigned to return type "list[int]" -
ModuleNotFoundError: No module named 'aspose-words'
I have installed aspose.words using the following command pip install aspose-words But when I add this to my installed app it showing the following error INSTALLED_APPS = [ # Core Extensions 'aspose-words' ] ModuleNotFoundError: No module named 'aspose-words' -
poker five card draw with Django Rest Framework
I Have this code Written with Python. The logic of the Code is to shuffle a deck of Cards, deal one single hand to the player and after Evaluate the Highest rank of the Player's hand and return an appropriate message to the player like. (Ex: Your Hand : 5K 8H 2S 3D 9S Your Rank : Flush) I want to use Django framework to create an API that will return an HttpResponse to mimic this (Ex: Your Hand : 5K 8H 2S 3D 9S Your Rank : Flush) as a Json Object. I would like to know how would about writing API and which design consideration i should have in mind. Which part of the code should go into the view to return the appropriate endpoint exemple : the hand of the player the shuffling of the deck, and the rank of the user. from constants import Constant class Card(Constant): def __init__(self, suit, val): # initialize the card object self.suit = suit self.value = val # get the rank of the card by indexing the RANKS dictionary self.rank = self.RANKS[val] def get_rank(self): # return the rank of the card if self.rank: return self.rank else: raise Exception('No rank') def get_suit(self): … -
SQL request for a model
models.py class Country(models.Model): name = models.CharField(max_length=50, validators=[validate_name, ]) class Meta: managed = False db_table = 'countries' def __str__(self): return self.name 0001_initial.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, validators=[countries.validators.validate_name])), ], options={ 'db_table': 'countries', 'managed': False, }, ), ] sql (venv) michael@michael:~/Documents/PyCharmProjects/db/db$ python manage.py sqlmigrate countries 0001_initial BEGIN; -- -- Create model Country -- -- (no-op) COMMIT; Could you tell me whether this sql reflects the model or not? If not, how can it happen? And will it produce in the database? -
Django: Create a temporary custom user
I am currently working on a project with Django. I would like to allow a user to register only with his username. Additionally this user should be able to participate in chats with other users. After research I think that I need to create a SQL table for this. Should I rather create a custom user, which I then extend? Or should I create an independent model. Additionally, I am wondering how to design the authentication process. Should I store the PK and/or the password of the model in the user's session? In addition, I want to delete the user after some time. What is the best way to do this? Do I store the session key in the model and search the session database once a day for expired users? Also, if there is theoretically a way to solve the problem without making a database entry, I would be open to it. -
Hardcoded things in migrations
Could you tell me why Django hardcodes the business logic into migrations? We can formulate the question the other way. Let's have a look at valitadors and upload_to. These all is hardcoded into migrations. But if we show SQL that a migration produces, no validators or upload_to will be there. So, why are they hardcoded? Validators and upload_to are already mentioned in models. DRY principle is violated. Any change in the code ruins migrations. For example renaming of upload_to will result in the project's blowing up. Validators and upload_to are just examples. There are more things of the kind. Anyway, they don't influence the database. So, why do we need them in migrations? Could you comment? -
Django Crispy Form filter by is_staff
I have a form to upload article posts but how would I filter the author so it just shows users who have the is_staff role, I also need it to show authors as usernames rather than email adresses Here is my forms.py class ArticleForm(forms.ModelForm): tags = TagField(required=False, widget=LabelWidget) class Meta: model = Article fields = ('article_name', 'author', 'content', 'tags', 'status') Here is my views.py class ArticleCreateView(LoginRequiredMixin, CreateView): model = Article form_class = ArticleForm template_name = 'main_website/new_article.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): form.instance.author = self.request.user form.save() return super().form_valid(form) def get_context_data(self, **kwargs): articles = Article.objects.filter(status=1).order_by('-date_posted')[:2] context = super().get_context_data(**kwargs) context['articles'] = articles context['title'] = 'New Article' return context Here is my models.py class Article(models.Model): class Status(models.IntegerChoices): Draft = 0 Published = 1 article_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='news_updates') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() tags = TaggableManager() date_posted = models.DateTimeField(default=timezone.now) status = models.IntegerField(choices=Status.choices, default=Status.Draft, help_text=_('Decide whether you want to Publish the news article or save it as a Draft')) class Meta: ordering = ['-date_posted'] def __str__(self): return self.article_name def get_absolute_url(self): return reverse("main_website_article_detail", args=[str(self.slug)]) def save(self, *args, **kwargs): self.slug = slugify(self.article_name) super(Article, self).save(*args, **kwargs) -
Dockerized Django app and MySQL with docker-compose using .env
I would to run my Django project into a Docker container with its Database on another Docker container inside a Bebian When i run my docker container, I have some errors. Like : Lost connection to MySQL server during query ([Errno 104] Connection reset by peer). This command mysql > SET GLOBAL log_bin_trust_function_creators = 1 is very important because database's Django user create trigger. Morever, I use a .env file used same for create DB image to store DB user and password. This path is settings/.env. My code: docker-compose.yml: version: '3.3' services: db: image: mysql:8.0.29 container_name: db_mysql_container environment: MYSQL_DATABASE: $DB_NAME MYSQL_USER: $DB_USER MYSQL_PASSWORD: $DB_PASSWORD MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD command: ["--log_bin_trust_function_creators=1"] ports: - '3306:3306' expose: - '3306' api: build: . container_name: django_container command: bash -c "pip install -q -r requirements.txt && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - '8000:8000' depends_on: - db Dockerfile : # syntax=docker/dockerfile:1 FROM python:3.9.14-buster ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt ADD . /app/ How to start my Django project ? Is possible to start only the DB container ? What command i need execute and what changes i need to make, I'm novice with … -
Can we select which object to return from serializer[many=true] based on condition
Lets suppose i have a model Post with field such as Model Post - Name : TextField - Body : TextField - isPrivate : Boolean Now the query post_obj = Post.objects.all() return 10 objects which is passed to getPostDataSerializer() class getPostDataSerializer(serializers.ModelSerializer): class Meta: model = Galaxy fields = ("Name","Body") we have post_data = getPostDataSerializer(post_obj,many=True).data which returns name and body of all 10 objects but i want to receive data of only those posts whose isPrivate field is false Please help -
Staticfiles Folder not Being Created Elastic Beanstalk
I'm trying to deploy a django application to Elastic Beanstalk but am having some difficulty serving static files. I've added the following to my .ebextensions container_commands: --- 04_collect_static: command: "cd /var/app/current && source ../venv/staging-LQM1lest/bin/activate && python manage.py collectstatic --noinput" leader_only: true --- option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: "/static/": "myapp/static/" In the EB instance's logs, I can see 0 static files copied to '/var/app/current/myapp/static', 163 unmodified. which implies that the files have successfully been copied. However, when I ssh into my instance and navigate to that directory, no "static" folder exists and the files are not being successfully served to the client (404 error). -
Reverse for 'alunos_por_ano' with arguments '('',)' not found. 1 pattern(s) tried: ['escola/ano/(?P<ano_lectivo_id>\\d+)/$']
Sou novo e estou aprendendo Django. estou criando um projecto de gestao de mensalidades, e as views funcioanam perfeitamente, mas quando adiciono o link no templete (linha 56) da o seguinte erro: enter image description here views: enter image description here urls: enter image description here models: enter image description here espero que me ajudem. -
I need to convert string to byte string but am unable to do so, please assist me
def application(environ,start_response): status = '200 OK' html = '<html>\n' \ '<body>\n' \ '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \ 'mod wsgi Test Page\n' \ '</div>\n' \ '</body>\n' \ '</html>\n' response_header = [('Content-type','text/html')] start_response(status,response_header) return [html] This causes an error saying: TypeError: sequence of byte string values expected, value of type str found -
How to save newline (\n) or escape character using Django rest famework serializer
I'm following the tutorial(link) There are two methods to save data (1) direct save(without serializer) from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() (2) with serializer 'PUT' method def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204) With the first method, I can save newline character('\n') without any problem. But, with the second mehtod, I fail to save. I tested two cases. (1) one backslash { "title": "", "code": "foo = "bar"\n", "linenos": false, "language": "python", "style": "friendly" } (2) two backslashes { "title": "", "code": "foo = "bar"\\n", "linenos": false, "language": "python", "style": "friendly" } The results are: (1) no newline character { "id": 6, "title": "", "code": "foo = "bar"", "linenos": false, "language": "python", "style": "friendly" } (2) backslash character ('') before 'n' { "id": 6, "title": "", "code": "foo = "bar"\\n", "linenos": false, "language": "python", "style": "friendly" … -
AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri'
I got an AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri' when I am trying to update my code from python3.3 to 3.9 and django1.10 to 4.0.8. When I try to call update API I got this error -
django multilevel nested formsets
can't find any solution to my needs. django provide inline formset which allow to 3rd level of nesting, but I need much more complex nesting. It should be fully dynamic, so I can go one to one on each level, but it could be one to many on each level. So far I have this only, but could be expanded for additional sublevels. class Srts(models.Model): data = models.CharField(max_length=10, blank=True, null=True) class Volume(models.Model): srts = models.ForeignKey('Srts', on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True, null=True) class Qtree(models.Model): volume = models.ForeignKey('Volume', on_delete=models.CASCADE) name = models.CharField(max_length=120) class Server(models.Model): qtree = models.ForeignKey('Qtree', on_delete=models.CASCADE) hostname = models.CharField(max_length=120, blank=True, null=True) class CifsPermission(models.Model): qtree = models.ForeignKey('Qtree', on_delete=models.CASCADE) group = models.CharField(max_length=30, blank=True, null=True, default='None') permission = models.CharField(max_length=30, blank=True, null=True, default='None') I have been googling a lot last days, but there is not much. Some examples django-nested-inline-formsets-example -that basic only 3rd level Django-better forms -could handle mltiple forms on one submin, but not formsets django-nested-inline -only for admin page Soudl be the way to do not model related for , then do some separation and appropriate logic to save it in order to my models? -
Schedule a task with celery to run only once in Django
How can I schedule a task with celery to run only once in my Django app. Lets say I'm writing a reminder app where user can login to the system and say "Please remind me 10 minutes earlier that I have a meeting by 10:00am". Then the celery task will run by 9:50am and after that, it would never run again. Not a recurring task. -
Template used by multiple apps requires a specific variable
When one uses a template, used by various apps, that requires a specific variable <a href="{% url 'blog:blog-detail' user_blog %}">My blog</a> we want to ensure that the template will always be aware of the variable user_blog. Also, we don't want to hammer the logic in every view. In such cases, the question popping up is usually within the lines of "How to make a variable available to all templates?" and so we are redirected to Template context processors. Since what we want is dependent on a user instance, we wouldn't be able to use a context processor for something like this user_blog = self.request.user.blog return {'user_blog': user_blog} because, as noted by Willem Van Onsem A contextprocessor only passes extra variables to the template render engine, so it returns a dictionary, and does not take any parameters (except for the request). What do we then do in such cases? -
Str object has no attribute read with django
I have these two codes, i'm working with django, it's a request that asks for a specific project, and the python is supposed to give it back with the return function def project(request): request_body = json.loads(request.body.decode('utf-8')) queryID = request_body['queryID'] with open(os.path.join(BASE_DIR, 'projects//') + queryID + ".json", 'r') as f: response = json.load(f.read()) return response const url = "/project" let id_request = {"queryID":projectID} let data = fetch(url, { method: 'POST', mode: "same-origin", headers: { "Accept": "network/json", "Content-Type": "network/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify(id_request) } ) .then(response=>response.text()) .then(data=>{ console.log(data); }) But when reading the json file I want to return, it throws an error AttributeError: 'str' object has no attribute 'read'