Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vue.js/JavaScript Errors When Running Vue/Django App on OpenShift but not Locally
I have a vue django app that runs and works fine locally. It does not work once I deploy it to my OpenShift pod, however. These are the specific errors I get when I navigate to the pod URL: Uncaught ReferenceError: jQuery is not defined at select2.min.js:2:241 at select2.min.js:2:249 vue.js:9330 You are running Vue in development mode. Make sure to turn on production mode when deploying for production. See more tips at https://vuejs.org/guide/deployment.html vue.js:5108 [Vue warn]: Property or method "titleInvalid" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. (found in <Root>) warn$2 @ vue.js:5108 vue.js:5108 [Vue warn]: Error in render: "TypeError: titleInvalid is not a function" (found in <Root>) warn$2 @ vue.js:5108 vue.js:3732 TypeError: titleInvalid is not a function at Proxy.eval (eval at createFunction (vue.js:11632:18), <anonymous>:3:883) at Vue._render (vue.js:2509:30) at Vue.updateComponent (vue.js:2948:29) at Watcher.get (vue.js:4178:35) at new Watcher (vue.js:4168:53) at mountComponent (vue.js:2965:7) at Vue.$mount (vue.js:9311:14) at Vue.$mount (vue.js:11870:20) at Vue._init (vue.js:4724:18) Are there any specific settings I need to check for in my django project settings or in my OpenShift pod (or project) settings? I wasn't … -
How to properly contenarize a django-react multicontainer app using docker for production and deployment ? (Nginx, Gunicorn)
I built a small blog to learn to use docker and docker-compose. I am new to programming and web development. I built the frontend with react and next. the backend with django and a postgresql database. I managed to setup a development environment with bind mounts, volumes, Dockerfiles and docker-compose.yml that worked fine and i learned a lot. here was my base docker-compose.yml file: 1 version: "3.8" 1 2 services: 3 db: 4 image: postgres:12.0-alpine 5 restart: unless-stopped 6 volumes: 7 - postgres_data:/var/lib/postgresql/data/ 8 env_file: 9 - ./api/.env.dev 10 11 blog-dev: 12 image: "blog:dev" 13 build: 14 target: development_build 15 context: ./api 16 cache_from: 17 - "blog:dev" 18 args: 19 DJANGO_ENV: development 20 command: python -Wd myblog/manage.py runserver 0.0.0.0:8000 21 ports: 22 - 8000:8000 23 env_file: 24 - ./api/.env.dev 25 depends_on: 26 - db 27 28 front-dev: 29 image: "front:dev" 30 build: 31 target: development_front 32 context: ./frontend 33 command: npm -Wd start 34 ports: 35 - 3000:3000 36 volumes: 37 - ./frontend:/front 38 - /front/node_modules 39 40 volumes: 41 postgres_data: now i want to deploy it on AWS with ECR and elastic beanstalk. I read quite a bit about Dockerrun.aws.json files and config files, etc. to that end, my … -
Django_filters - ModelChoiceFilter - How to filter based on the page_ID the user is visiting
I would like the user to be able to filter based on categories. I am using django_filters. Two important things: These categories are not hard coded in the model, but provided by the a user type ( in my case a Venue, not an actual user therefore request.user does not work. Or at least I dont know how to use it in my situation). I only want to show the categories relevant to the Venue ID page. I am probably lacking a bit of "vocabulary" to express this in a way django understand. It's a recurring problem I have, and somehow always manage to go around it. I think this time I am definitely going to need to do something about it. Would be useful to find out! model class Catalogue(models.Model): product = models.ManyToManyField('Product', blank=True) type = models.TextField('type', blank=True, null=True) url path('show_venue/<venue_id>', views.show_venue,name="show-venue"), views def show_venue(request, venue_id): if request.method == "POST" and 'btnreview_form' in request.POST: form = CatalogueReviewForm(request.POST) if form.is_valid(): data = form.save(commit=False) data.product_id = venue_id # links to product ID in Catalogue Model and return product name data.venue_id = request.POST.get('venue_id') # prints venue ID in form data.user_id = request.user.id data.save() ven_id = request.POST.get('venue_id') print(data) form.save() return HttpResponseRedirect(ven_id) else: venue … -
Render a blank response (Django Template Language)
i want print the name of a given post list but it render an blank response.. Below is the code of views.py from django.shortcuts import render post = [ { 'name':'Abc, 'dob':'01/01/1998' }, { 'name':'Xyz', 'dob':'24/01/1993' } ] def home(requests): return render(requests,'app1/home.html',dict(post)) Content of home.html {% for item in post %} <p>name is {{ item.name }}</p> {% endfor %} here it display the blank response instead of printing the name..So how can i fix this issue ? What i tried is created another variable and pass it to the home.html views.py def home(requests): context = { 'posts':post } return render(requests,'app1/home.html',context) home.html {% for item in posts %} <p>name is {{ item.name }}</p> {% endfor %} Above code gives the expected result.. -
Error with Wagtail URLs for media files: subclasses of Storage must provide a url() method
I am using Wagtail in a project and have a problem with both wagtailimages.Image and wagtaildocs.Document fields. When using DRF to access the URL data I get a "subclasses of Storage must provide a url() method" error. My configuration is that I have to use Bunny.net for storing media files. In order to do that, I use a library called django-bunny-storage (https://pypi.org/project/django-bunny-storage/) that works well with non Wagtail projects. This is my simplified model in which I removed all other fields: class Content(models.Model): illustration = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) uuid = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False) document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) panels = [ ImageChooserPanel('illustration'), DocumentChooserPanel('document'), ] As per django-bunny-storage I also had to modify the template context_processors array TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] I created a small modelserializer for Content that always returns this same error when I try to access the url of the Document or the Image field. from wagtail.images.models import Image, AbstractImage, AbstractRendition from wagtail.documents.models import Document class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = (('file'),) class DocumentSerializer(serializers.ModelSerializer): class Meta: model … -
django unittest error when have two test method in one class
I have question table in my model and each question can have some options : Models.py : class Question(BaseModel): class DifficultyLevel(models.IntegerChoices): EASY = 1 MEDIUM = 2 HARD = 3 question_text = models.TextField() level = models.IntegerField(default=1, choices=DifficultyLevel.choices) def __str__(self): return truncatewords(self.question_text, 7) class Option(BaseModel): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') title = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) def __str__(self): return self.title for updating questions I have : Views.py : class QuestionByIDAPIView(BadRequestSerializerMixin, APIView): def patch(self, request, question_id, company_code): serializer = InputQuestionSerializer(question_obj, data=request.data, partial=True) if not serializer.is_valid(): return self.serializer_error_response(serializer) serializer.save() return success_response(serializer.data, status_code=status.HTTP_200_OK) serializers.py : def update(self, instance, validated_data): options = validated_data.pop('options', None) instance.question_text = validated_data.get('question_text', instance.question_text) instance.level = validated_data.get('level', instance.level) instance.save() options_with_same_question_instance = Option.objects.filter(question=instance.pk).values_list('id', flat=True) options_id_pool = [] if options: for option in options: if "id" in option.keys(): if Option.objects.filter(id=option['id']).exists(): option_instance = Option.objects.get(id=option['id']) option_instance.title = option.get('title', option_instance.title) option_instance.is_correct = option.get('is_correct', option_instance.is_correct) option_instance.save() options_id_pool.append(option_instance.id) else: continue else: options_instance = Option.objects.create(question=instance, **option) options_id_pool.append(options_instance.id) for option_id in options_with_same_question_instance: if option_id not in options_id_pool: Option.objects.filter(pk=option_id).delete() return instance Tests.py : def create_single_answer_question(company=None): question = Question.objects.create( question_text='some test', level=Question.DifficultyLevel.EASY, company=company, ) for i in range(4): question.options.create( title=faker.name(), ) # mark one option as correct option = Option.objects.filter(question=question).first() option.is_correct = True option.save() return question class TestQuestionByIDAPIView(QuestionBaseTestCase): def setUp(self): super().setUp() self.create_company_group_for_handle_permission(company=self.company, … -
"daemon" directive is duplicate in /etc/nginx/nginx.conf:33 nginx-proxy "daemon" directive is duplicate in /etc/nginx/nginx.conf:33
I am working with nginx-proxy and lets-encrypt I am following this guide https://testdriven.io/blog/django-lets-encrypt/#nginx-proxy-service Other than that I am running another nginx service for my uswgi and written a "run.sh" command the content of my file is #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf exec nginx -g 'daemon on;' Content of my default.conf is server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } I know the error clearly indicates that there are 2 daemons running, but I cannot figure out how to fix this issue. I want to run both of them My dockerfile is FROM jwilder/nginx-proxy:0.9 LABEL Carte Blanche LLC COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ chmod +x /run.sh VOLUME /vol/static CMD ["/run.sh"] The folder structure is below -
How to make a view and nested urls correctly in Django for quiz app so that every question was on a new page?
I'm making a quiz app and can't figure out this problem. I understand how a ListView works on one page, but I need to make every question of the quiz with answers to apper on a new page (I mean, one question with possible answers and "next" button), and after that to show the results. I'm trying to make a nested urls, but it doesn't work. Maybe there are a better ways to do it? My models: class Quiz(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True, upload_to='images/quiz/') class Meta: verbose_name_plural = 'Quizzes' def __str__(self): return self.name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') question = models.CharField(max_length=255) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=255) is_correct = models.BooleanField() def __str__(self): return self.answer I tryed this view: class QuestionView(DetailView): model = Question template_name = 'question.html' def get_object(self, queryset=None): queryset = Question.objects.filter(quiz=self.kwargs['question_pk']) return queryset def get_context_data(self, **kwargs): context = super(QuestionView, self).get_context_data(**kwargs) context['quiz'] = Quiz.objects.get(pk=self.kwargs['quiz_pk']) return context And this url: urlpatterns = [ re_path(r'^quiz/(?P<quiz_pk>[0-1000])/(?P<question_pk>[0-1000])/$', QuestionView.as_view(), name='question'), ] I don't even know where to start so any advice is highly appreciated. Thank you. I'm trying to use nested urls, but I'm not sure it's the right way -
Updating the value of a model variable remotely
I want to update the value of inventory in 'Item' whenever I create a 'PurchaseItem' object. model.py(1): class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) Here, quantity represents no. of items purchased so when I create this object; I want inventory value to be updated here: model.py(2): class Item(models.Model): title = models.CharField(max_length=100) model = models.CharField(max_length=100) sku = models.CharField(max_length=100) ean = models.CharField(max_length=100) price = models.FloatField() inventory = models.IntegerField() -
Django and pylintt: inconsistent module reference?
Possibly because of my noobness, I can't get pylint and django management commands to agree about how to import files in my project. Setup # venv cd $(mktemp -d) virtualenv venv venv/bin/pip install django pylint pylint-django # django venv/bin/django-admin startproject foo touch foo/__init__.py touch foo/foo/models.py # management command mkdir -p foo/foo/management/commands touch foo/foo/management/__init__.py touch foo/foo/management/commands/__init__.py echo -e "import foo.models\nclass Command:\n def run_from_argv(self, options):\n pass" > foo/foo/management/commands/pa.py # install perl -pe 's/(INSTALLED_APPS = \[)$/\1 "foo",\n/' -i foo/foo/settings.py # testing venv/bin/python foo/manage.py pa venv/bin/pylint --load-plugins pylint_django --django-settings-module=foo.foo.settings --errors-only foo Result You'll note that manage.py is happy with import foo.models, but pylint isn't: ************* Module foo.foo.management.commands.pa foo/foo/management/commands/pa.py:1:0: E0401: Unable to import 'foo.models' (import-error) foo/foo/management/commands/pa.py:1:0: E0611: No name 'models' in module 'foo' (no-name-in-module) If I change it to import foo.foo.models, pylint passes but manage.py breaks: ... File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/tmp/tmp.YnQCNTrkbX/foo/foo/management/commands/pa.py", line 1, in <module> import foo.foo.models ModuleNotFoundError: No module named 'foo.foo' What am I missing? -
How to make forigen key relationship in django
Hi I have two table in my django database which have one to many relation. In one table I have some data and I want to copy all that data to the next one code is below. forms.py: I want the exec_summary value from NewProductForm to NewReportForm. class NewProductForm(forms.ModelForm): exec_summary = forms.BooleanField(required=False) scope = forms.BooleanField(required=False) isms = forms.BooleanField(required=False) methodology = forms.BooleanField(required=False) recommendation = forms.BooleanField(required=False) class Meta: model = DB_Product fields = ('name', 'description', 'exec_summary', 'scope','isms','methodology','recommendation') widgets = { 'name': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required", 'placeholder': "Product Name"}), 'exec_summary' : forms.BooleanField(), 'scope' : forms.BooleanField(), 'isms' : forms.BooleanField(), 'methodology' : forms.BooleanField(), 'recommendation' : forms.BooleanField(), } class ProductModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class NewReportForm(forms.ModelForm): product = ProductModelChoiceField(queryset=DB_Product.objects.all(), empty_label="(Select a product)", widget=forms.Select(attrs={'class': 'form-control'})) P_executive_summary = forms.BooleanField(required=False) class Meta: today = datetime.date.today().strftime('%Y-%m-%d') nowformat = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') model = DB_Report fields = ('product', 'report_id', 'title', 'executive_summary', 'scope', 'outofscope', 'P_executive_summary', 'methodology', 'recommendation', 'report_date' ) widgets = { 'report_id': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required"}), 'title': TextInput(attrs={'class': 'form-control', 'type': "text", 'required': "required"}), 'report_date': DateInput(attrs={'class': 'form-control', 'type': "text", 'data-inputmask': "'alias': 'yyyy-mm-dd'", 'data-mask':'', 'required': "required"}), 'P_executive_summary' : forms.BooleanField(), } models.py: exec_summary from DB_Product --> P_executive_summary in DB_Report class DB_Product(models.Model): name = models.CharField(max_length=255, blank=False) description = MartorField() … -
How to add an autocomplete field in an existing form?
Given a form class SettingsForm(Form): first_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'First name'}), label='', ) last_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Last name'}), label='', ) I'm trying to add an autocomplete field languages that suggests languages using the model below class Language(models.Model): name = models.CharField(max_length=255, unique=True) code = models.CharField(max_length=7, unique=True, null=True) def __str__(self): return self.name Based on django-autocomplete-light, I tried the below: languages = djhacker.formfield( Profile.languages, forms.ChoiceField, widget=autocomplete.ModelSelect2(url='language-autocomplete'), ) but it looks like formfield is not returning anything bootstrap5.exceptions.BootstrapError: Parameter "field" should contain a valid Django BoundField. [29/Dec/2022 13:58:56] "GET /settings/ HTTP/1.1" 500 182091 by checking further, the error above occurs because languages is None. If so, then how should I be adding languages as a field of the settings form? -
Django: Scheduled executeion of tasks
I'm building a Django system that needs to daily fetch data from another source (e.g. a daily dump of JSON files from a government site). The Django site is supposed to run in Docker, currently as a single server but optionally scaling later. I'd like to run the scheduled task internally inside Django (not using crontab or SystemD), but unsure how to do that. The schedule isn't dynamic (I'm happy setting the cadence in the Python code), and I don't want to have to run an external command aside from runserver. All of the solutions I found seem to necessitate running another component / command / process, and I wonder if there's a more elegant solution. -
How to write {% url ' ' %} for 2 and more multiple slugs?
im beginner in Django I try write url for go to next url if i use {% url tuman_url 'iib:mahalla' i.slug %} i get error: Reverse for 'mahalla' with arguments '(<Tuman: Sharof Rashidov Tumani>, 'ulugbek')' not found. 1 pattern(s) tried: ['(?P<tuman_slug>[-a-zA-Z0-9_]+)/mahalla/(?P<mahalla_slug>[-a-zA-Z0-9_]+)\Z'] my urls.py path('statistika/<slug:tuman_slug>/', show_one_stata, name='tuman_stata'), path('<slug:tuman_slug>/mahalla/<slug:mahalla_slug>', show_one_mahalla, name='mahalla'), my views.py def show_one_stata (request,tuman_slug:str): tuman_url = get_object_or_404(Tuman, slug=tuman_slug) tuman = Tuman.objects.all() citizen = Citizen.objects.all() category = Category.objects.all() mahalla = Mahalla.objects. context = { 'citizen' : citizen, 'category' : category, 'mahalla' : mahalla, 'tuman' : tuman, 'tuman_url' : tuman_url, return render(request, 'main/one_stata.html',context) def show_one_mahalla(request, mahalla_slug:str,tuman_slug:str) : citizen = Citizen.objects.all() nizo = Category.objects.all() mahalla_for = get_object_or_404(Mahalla, slug=mahalla_slug) tuman_url = get_object_or_404(Tuman, slug=mahalla_slug) context = { 'citizen':citizen, 'nizo':nizo, 'mahalla_for':mahalla_for, 'tuman_url':tuman_url, } return render(request, 'main/one_mahalla.html',context) my html {% for i in mahalla %} {% if i.tum == tuman_url %} <tr> <td style="font-weight: bold;"><a href="{% url tuman_url 'iib:mahalla' i.slug %}" style="text-decoration:none; color:black;">{{ i.name }}</a></td> <tr> {% endif %} {% endfor %} my models.py class Tuman(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Tuman") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name def get_absolute_url(self): return reverse('iib:tuman', kwargs={'tuman_slug': self.pk}) class Meta: verbose_name = 'Tumanlar' verbose_name_plural = 'Tumanlar' class Mahalla(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name="Mahallaning nomi") slug = models.SlugField(max_length=255, unique=True, … -
Websocket messages are lost with Django + websocket
I'm using Django to build a service which receives data from Binance crypto exchange in real time via websocket. I run several websocket connections, each of them in the separate thread. There is the function which starts all threads with websockets: def start_threads(self): query = self._socket_type.get_pairs_symbols(self.get_symbol_function(), provider=self._provider) for i in range(0, len(query), self._provider.limit_socket_pair_per_thread): socket = self._socket_type() thread = BaseThreadSocketWorker(socket, query[i: i + self._provider.limit_socket_pair_per_thread]) thread.start() Here I try to subscribe to all available pairs on Binance. I wasn't able to subscribe to all of them at once, websocket simple were stuck, that is why i split it to several connections. self._provider.limit_socket_pair_per_thread - number of pairs to subscribe in the websocket _socket_type.get_pairs_symbols - just formats and returns query which is accepted by Binance websocket. self._socket_type - my custom class to handle websocket messages and process received data BaseThreadSocketWorker - class inherited from threading.Thread python class. Overrides run method in which websocket is started. Here is a method implementation, where self._socket_handler is the same class as described for self._socket_type earlier. def run(self): self._socket_app = self._socket_handler.subscribe_to_prices_ws(self._observed_pairs) self._socket_app.run_forever() subscribe_to_prices_ws does the following. Creates a WebSocketApp instance, which subscribes to Binance weboscket (in my case it's wss://stream.binance.com:9443/ws), which suppose to send a messages any time prices … -
cannot acces http://server_domain_or_IP:8000
I am using an AzureVM to host my development API server written in django. There, I cloned my codebase and did all the requirements.txt installation. Before executing the manage.py runserver 0.0.0.0:8000 command, I changed the firewall permission rule: sudo ufw allow 8000. The sudo ufw status commads shows the following result: Status: active To Action From -- ------ ---- Nginx HTTP ALLOW Anywhere 8000 ALLOW Anywhere OpenSSH ALLOW Anywhere Nginx HTTP (v6) ALLOW Anywhere (v6) 8000 (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) and then I run python3 manage.py runserver 0.0.0.0:8000. I should be able to see the default django page @ http://SERVER_IP_OR_DOMAIN:8000 But nothing shows. whereas if I hit http://SERVER_IP_OR_DOMAIN, I can see the NGINX landing page. I am following this blog from digital ocean. Here is my VM network rules: How can I fix this? -
How to filter with encrypted column in django?
Here I am encrypting some column in the db by making custom django model field. All were working fine but I am not able to filter with the encrypted column. from cryptography.fernet import Fernet from django.conf import settings from django.db import models class CustomTextField(models.TextField): key = settings.FERNET_KEY.encode() f = Fernet(key) def get_prep_value(self, value): return self.f.encrypt(value.encode()).decode() def from_db_value(self, value, expression, connection): return self.f.decrypt(value).decode() class MyModel(models.Model): text = CustomTextField(null=True) MyModel.objects.create(text="sometext") # saves text as 'gAAAAABjrZU-AiwR0EaQQ3lkYYd6GJnyNF0tNE1lYHmuUAKgydAA0nl2mYd4IuPoREatQSlwYMwWBYbvrYqPiryLwaL9OraeJA==' MyModel.objects.values("text") # returns "sometext" But the issue is while filtering For eg. MyModel.objects.filter(text="sometext") # return empty queryset -
PAGE NOT FOUND- ERROR(404);GET request; django-python
Lately I have been trying to use the GET request in django-python. However I run into a 404 error when I do so. I want the program to print the parameter given to it. URL PATTERN : path('add<int:hello>/',views.add,name = 'Add') VIEWS.PY: def add(request,num1): val1 = request.GET["num1"] return HttpResponse(request,"Hello") WHAT I AM SEARCHING ON BROWSER: http://127.0.0.1:8000/add?1 -
specific sending of a data to another user in django
I code a plateform project in django, a user can create an announce and a another user can reserv this announce.I would like that when User-A books on an announce of user-b, User-B receives the notification on the site, on a page notification, but I don't know how to do that. I tried something. My views.py : @login_required def view_annonce(request, annonce_id): message = "" annonce = get_object_or_404(models.Offre, id=annonce_id) if request.GET.get('contact') == 'contact': print('user clicked summary') if request.user.point_number < 10: message = "You can't reserv this announce" else : request.user.point_number = request.user.point_number -10 request.user.save() return redirect("home") context={ "annonce": annonce, } return render(request, 'blog/view_annonce.html', context=context) @login_required def notif_page(request): return render(request, 'blog/notifications.html') urls.py : path('offre/<int:annonce_id>', blog.views.view_annonce, name="view_offre"), path("offre/<int:annonce_id>/edit", blog.views.edit_annonce, name='edit_offre'), path("notif/", blog.views.notif_page, name="notif"), my models.py : class User(AbstractUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=30, null=True) profile_photo = models.ImageField(verbose_name='Photo de profile') point_number = models.IntegerField(default=20) ville = models.CharField(max_length=50) -
django query: groupby and keep rows that are the most recent
I am struggling on a query that is supposed to group by a model attribute and return for each unique value of that model attribute, the row that has the most recent date. I can't manage to get the output that I am looking for in a way that will be digestible for my template. here is the model I am trying to query: class Building(models.Model): building_id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) project = models.CharField(max_length=200,blank=True, null=True) and here are my attempt #1: get the unique projects and use a for loop: projects = list(Building.objects.all().values_list('project', flat=True).distinct()) context = {} for project in projects: proj = Building.objects.filter(project=project).latest("created_at") context[project] = proj this is ok but it does not allow me to access the queryset as {% for i in projects %} in template => causing pk problems for links my other attempt tries to get rows, to keep everything in a queryset: projects = Building.objects.all().values_list('project', flat=True).distinct() proj = Building.objects.filter(project__in=list(projects)).latest("created_at") that only returns the latest entered row regardless of the project name. This is close to what I am looking for, but not quite since I try to output the latest entered row for each unique project value. what is the proper way … -
Create the form with given requirements in Python
please Solve this. in python. file link :- https://drive.google.com/file/d/1Io5Ec-hZLIy3iA2vuS-WmEeoO3WiA8oU/view?usp=share_link Solve the full problem -
Is it possible to show message in DjangoAdmin on open?
I need to display a message right after I open model admin page, is there a way? I know how to show it after save, but didn't find a way to show it on open. -
How to restrict users from accessing product after it has expired?
I'm developing an e-learning app in which users can purchase courses that have an expiry date of up to two months from the time they purchase the course. I'm aware of how to limit their access by comparing dates, but I was hoping you could advise me on how to easily restrict the users without manually going through every view and calling a function that returns Permission Denied if their course has expired. I attempted to create a decorator that checks this but was unsuccessful. Should I use middleware to accomplish this? Could you point me in the right direction so I don't have to go through every view manually? -
Django api showing an import error upon running the server after using django-rest-auth
I was trying to build a Django API for a blog site. Up to this point, everything was working fine, but as soon as I tried to implement user authentication using Django-rest-auth and updated the urls.py files of both the app and the project accordingly, I have been getting this error that's apparently been telling me that the program can't locate 'URL' from Django.configs.urls. Here's the code of the urls.py file of the 'posts' app in the project:- from django.urls import path from .views import PostList,PostDetail urlpatterns = [ path('<int:pk>/',PostDetail.as_view()), path('',PostList.as_view()), ] Here's the code of the project level urls.py file:- from django.contrib import admin from django.urls import path,include #new urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/',include('posts.urls')), #new path('api-auth/', include('rest_framework.urls')), #new path('api/v1/rest-auth/',include('rest_auth.urls')), #new ] Here's the settings.py file of the project:- '''' from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&u!b8$eururpem!f_0klrw2g28(xu14%i8h4g&k(i$@_tmmm$7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
How to write webhooks for telegram bot with aiogram and django
How do I write webhooks using aiogram and django. How do I send data to the bot received via webhooks ? Bot code from aiogram.utils.executor import start_webhook from aiogram.dispatcher.webhook import SendMessage from config import * @dp.message_handler() async def echo(message: types.Message): return SendMessage(message.chat.id, message.text) async def on_startup(dispatcher): await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True) async def on_shutdown(dispatcher): await bot.delete_webhook() if __name__ == '__main__': start_webhook( dispatcher=dp, webhook_path=WEBHOOK_PATH, skip_updates=True, on_startup=on_startup, on_shutdown=on_shutdown, host=WEBAPP_HOST, port=WEBAPP_PORT, ) Django code class Webhook(mixins.CreateModelMixin, viewsets.GenericViewSet): def get_message(self, request, *args, **kwargs): data = self.request.data # in this message for bot ... And how I can reply to bot this message ?