Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send QuerySet from HTML template to views via urldispatcher in django
I am trying to send QuerySet from index.html to views through urldispatcher. I searched through documentations but mostly have information on int:id, path:kjf, etc. There is some information on keyword args but i don't know much about them. I am beginner to Django and this is my first project, also my deadline for this project is near, so any help will be appreciable. index.html listing only necessary code... {% if datadict and datadict != "Sorry no data found" %} {% for item in datadict %} <tr> <th width="5%" scope="row"><a href="{% url 'index' datadict %}" class="btn btn-secondary">Generate</a></th> <td>{{ item.title }}<td> </tr> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.index, name='index'), path('<datadict>', views.index, name='index') ] views.py def index(request, datadict=None): if (datadict): b = datadict[0] ### this is just testing to see if i am receiving the data in QuerySet from or not return render(request, 'dapp/index.html', {'b': b}) datadict have this data:- <QuerySet [{'id': 1002, 'year': '2000', 'sector': 'test', 'topic': 'test1', 'insight': 'dont no', 'url': 'localhost', 'start': '2000', 'impact': 'impaca', 'added': 'January 08 2001', 'published': 'August 03 2001', 'relevance': '4', 'pest': 'test2', 'source': 'CBSE', 'title': 'Adding test data', 'like': '5'}]> -
How to autofill user and slug fields in django form
I need two of the three form fields to be filled in automatically before submitting to the database. Slug is supposed to be filled based on test_name, and user have to be filled based on data about the current user. Now I can submit the form, but the database entry will not be created. models.py class Test(models.Model): test_name = models.CharField(max_length=100, db_index=True, verbose_name='Test name') slug = models.SlugField(max_length=100, unique=True, verbose_name='URL') author = models.ForeignKey(User, db_column="user", on_delete=models.PROTECT) forms.py class AddTestForm(forms.ModelForm): class Meta: model = Test fields = ['test_name', 'slug', 'author'] views.py def ask_test_name(request): form = AddTestForm(request.POST) if form.is_valid(): test = form.save(False) test.slug = slugify(test.test_name) test.author = request.user test.save() return render(request, 'app/ask_test_name.html', {'form': form}) ask_test_name.html <form action="{% url 'ask_test_name' %}" method="post"> {% csrf_token %} <p><input type="text" name="test_name" required></p> <p><input type="hidden" name="slug"></p> <p><input type="hidden" name="author"></p> <p><button type="submit">Create</button></p> </form> -
Django Show var as Label name
I'am learning Django and looking for a wat te get a variable shown as tekst I created the following model: ` class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telefoon = models.CharField(max_length=10, blank=True) telefoon_mobiel = models.CharField(max_length=10, blank=True) woonplaats = models.CharField(max_length=20, blank=True) postcode = models.CharField(max_length=6, blank=True) straat = models.CharField(max_length=20, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() ` I created the following Form.py ` class ProfileForm(forms.ModelForm): straat = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) postcode = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) woonplaats = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) telefoon_mobiel = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = Profile fields = ('telefoon', 'telefoon_mobiel', 'woonplaats', 'postcode', 'straat') ` i Created the following views.py ` @login_required @transaction.atomic def profiel(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Profiel aangepast')) return redirect('user') else: messages.error(request, ('Los ondestaande probleem op')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'public/profiel.html', { 'user_form': user_form, 'profile_form': profile_form, }) And created the following template: <div class="card-body"> <h5 class="card-title">Profiel {{ user.get_full_name }}</h5> <hr> <div class="container"> <div class="row"> <div class="col-sm"> {{ user.first_name }} {{ user.last_name }} </div> <div class="col-sm"> {{ straat }} </div> </div> <br/> … -
Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
I have this problem Reverse for 'detail_serial' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] and problem is here {{ serial.title }} I don't know how it fix, cause im new in django.Please help html > ``` > <div class="container" style="grid-template-columns: repeat(auto-fill, 300px);"> > for serial in serials %} > <div class="item"> > <img src="{{ serial.poster.url }}" class="img-fluid" alt=""> > <p> > <a href="{% url 'detail_serial' serial.url %}">{{ serial.title }}</a> > </p> > </div> > endfor %} > </div> > ``` > views.py > ``` > class SerialDetailView(View): > def get(self, request): > serials = Serials.objects.all() > genres = Genre.objects.all() > return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres}) > > ``` > > ``` urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('reg/', views.Reg.as_view(), name='reg'), path("serials_list/", views.SerialsView.as_view(), name='serials_list'), path("add/", views.AddView.as_view(), name='add'), path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'), path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'), path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'), ] models > ```` > class Serials(models.Model): > title = models.CharField('Name',max_length=100) > description = models.CharField('Description', max_length= 200) > poster = models.ImageField('Poster', upload_to='serials/') > date = models.DateField('Date') > country = models.CharField('Страна',max_length=100) > actors = models.ManyToManyField(Actor, verbose_name='actors', related_name='actor') > genre = models.ManyToManyField(Genre, verbose_name='genres') > category = models.ForeignKey(Category, verbose_name='category', on_delete=models.SET_NULL, null=True) > url = models.SlugField(unique=False) > link = models.URLField(max_length=200, blank=True) > ``` > … -
JavaScript fetch to Django view: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user. Error in views.py: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python310\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\rossw\Documents\Projects\Scry\apps\administration\views.py", line 47, in administration_users_page switchData = json.load(request)['switch'] File "C:\Python310\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Python310\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Python310\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python310\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Error in browser: 0 PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON JavaScript: const changeAdminUserAction = (id,data) => { console.log(data) fetch(`/administration/users/${id}/`,{ method: 'PUT', body: JSON.stringify({type: "adminUser", switch: data}), headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'}, }) .then((response) => response.json()) .then((result) => {location.reload()}) .catch((err) => {console.log(err)}) } views.py: if request.method == 'PUT': user = CustomUser.objects.get(username=kwargs.get('username')) switchType = json.load(request)['type'] switchData = json.load(request)['switch'] print(switchType, switchData) if switchType == 'adminUser': user.admin_user = switchData elif switchType == 'admindata': … -
I was running a test on my signal.py file and i am getting 'ValueError: seek of closed file' error
here is the signals.py file inside main app and here is the test_signals.py file enter image description here the full error is -
what is the best module for periodic tasks (django)
I am trying to save data from some external APIs every 3 minutes and i am wondering which module is the best and easiest one to use in general and also in deployment.( APScheduler , background-tasks or celery beat) -
Can't import properly in fast api project with multiple apps
I'm currently learning fast api cause it's needed for a new project i'm working on,the documentation and tutorials only make their sample project with the assumption that the project is a small project,they usually have file structures similar to this : - app | | | --- __init__.py | --- models.py | --- schemas.py | --- database.py | - main.py But coming from a django background in which most of my projects will be projects with lots of models and functionality, i will definately need a way to decouple the fast api application into separate apps so i took the django approach and made my own project structure into this . └── config ├── __init__.py ├── database.py ├── migrations.py └── recruiters ├── __init__.py ├── models.py ├── schemas.py └── jobs ├── __init__.py ├── models.py ├── schemas.py └── routers ├── __init__.py ├── job.py ├── recruiter.py └── views ├── __init__.py ├── job.py ├── recruiter.py └── main.py └── sqlite.db The only changes i made was to keep all views ( or repository for business logic, i choose to call it views cause that's what i'm used to) in one folder at the root directory same for routers (similar to url routes in django). The … -
NoReverseMatch Error while trying to delete file using django-htmx
I am getting a NoReverseMatch error while trying to delete a document from a list in an update page using htmx.Two parameters are passed to the url template tag: "doc.id" and the update page's object id "obj.id". I need the "doc.id" to delete the document with the view and the "obj.id" to then filter and return the new updated list, because we are dealing with multiple files field. The document gets deleted but for some reason the "obj.id" is blank as the error page (snapshot below) shows. But on refreshing the page the new updated list is returned. Please I need fresh eyes on this problem. What am I missing? What am I doing wrong? Thanks # html template (snippet) <label class="block mb-2 text-md font-bold text-gray-500"> Attached files </label> <span class="mb-4 block w-full p-2 rounded-sm border border-2 border-gray-300 bg-white"> <ol class="text-ellipsis overflow-hidden list-inside list-decimal"> {% for doc in sharefiles %} <li class="p-2 cursor-pointer text-blue-600 font-bold text-md w-auto"> <a target='blank' href="{{ doc.attach_share_capital.url }}" class="underline underline-offset-2"> {{ doc.attach_share_capital.url }} </a> <button type="button" hx-delete="{% url 'removescfile' pk=doc.id update_id=obj.id %}" hx-target="#sharecapital-files" hx-confirm="Are you sure?" class="cursor-pointer text-white bg-red-400 hover:bg-red-500 focus:ring-4 focus:outline-none focus:ring-red-400 font-medium rounded-sm text-sm items-center ml-2 px-2 py-1"> Remove </button> </li> {% endfor %} … -
Django: Send a SELECT value inside form action url
I have a form with multiple select inputs, as below: <form method="POST" class="row" action="{% url 'solution_product_list' %}"> {% csrf_token %} {# main select div: usage or model? #} <div class="col-md-3 mx-md-5"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب بر اساس:</h2> <select required aria-label="Select usage or model" id="usage_model_select" class="form-select" onchange="set_usage_or_model_dic()"> <option selected>----</option> <option value="usage">کاربرد</option> <option value="model">مدل</option> </select> </div> {# usage or model select div #} <div class="col-md-3 mx-md-5"> {# usage select div #} <div class="usage visually-hidden" id="usage_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب کاربرد:</h2> <select required aria-label="Select usage" class="form-select" name="usage_select" onchange="set_sub_usage_list()" id="usage_select_id"> <option selected>----</option> {% for usage in usage_queryset %} <option value="{{ usage.id }}">{{ usage.usage_name_fa }}</option> {% endfor %} </select> </div> {# model select div #} <div class="model visually-hidden" id="model_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب مدل:</h2> <select required aria-label="Select model" class="form-select" name="model_select" onchange="set_pump_type_list()" id="model_select_id"> <option selected>----</option> {% for model in main_model_queryset %} <option value="{{ model.id }}">{{ model.model_name_fa }}</option> {% endfor %} </select> </div> </div> {# select sub_usage or pump_type div #} <div class="col-md-3 mx-md-5"> {# sub_usage select div #} <div class="sub_usage visually-hidden" id="sub_usage_div"> <h2 class="h5 nm-text-color fw-bold mb-4">انتخاب کاربرد جزئی:</h2> <select required aria-label="Select sub_usage" class="form-select" name="sub_usage_select"> <option selected>همهی کابردهای جزئی</option> {% for sub_usage in sub_usage_queryset %} <option value="{{ sub_usage.id }}">{{ sub_usage.sub_usage_name_fa }}</option> {% endfor … -
How to make Django pagination with ajax without re-querying the DB
I've checked many related questions on building up pagination with ajax and implemented it in my app. The problem I still have is querying DB each time user сlicks next or prev because ajax call goes to the view function. My code: my_template.html <ul class="list-articles" id="dd"> </ul> <div class="buttons"> {% if page_obj.has_previous %} <a href="#" onclick="ajax_function('{{page_obj.previous_page_number}}','{{title}}')" id="prev">&#10094; prev</a> {% endif %} {% if page_obj.has_next %} <a href="#" onclick="ajax_function({{page_obj.next_page_number}},'{{title}}')" id="next"> next &#10095;</a> {% endif %} </div> views.py def my_view_function(request): if is_ajax(request=request): if 'page' in request.GET: return paginate(request) def paginate(request): parameter_a = request.GET['parameterA'] parameter_b = request.GET['parameterB'] li = MyModel.objects.filter(par_a=parameter_a, par_b=parameter_b) paginator = Paginator(li, 1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, ... } return render(request, f'my_app/my_template.html', context) main.js function ajax_function(page, title) { $.ajax({ url: '', type: "get", data: { 'page': page, 'title':title, }, success: function(response, status) { $('#dd').empty(); $('#dd').html(response); } }); } So this code is working but in real app I have more complex db queries to get my Model's objects, so every next/prev iteration will recall the objects again and again which look dump. Ideally I'd like to collect the list of objects once and then use them without any additional queries. I'm not a JS … -
how do you pass a parameter from post method to decorator?
I'm working a python django and django rest framework + swagger (drf-yasg) project. I need a dynamic decorator. how do you pass a parameter(named in this case "essource") of post method to decorator? def xxx(esSource): source = {} if esSource == 1: source = { 'field_1': openapi.Schema(type=openapi.TYPE_INTEGER) } else: source = { 'field_44': openapi.Schema(type=openapi.TYPE_INTEGER) } properties = { 'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"), 'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola") } return properties.update(source) class ShowResultsView(views.APIView): @swagger_auto_schema( operation_description="La prima pagina di risultati della ricerca", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['type_operator','column_to_hide'], properties=xxx(essource) ), ) def post(self,request,essource,page): resp = {} resp["status"] = 0 resp["data"] = {} resp["message"] = "I risultati della ricerca" return Response(resp,status=status.HTTP_200_OK) I get an error in this line code: properties=xxx(essource) -
Heroku app won't restart after error 14 (Memory quota exceeded)
We have a Django app deployed on Heroku with the following Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug celery: celery -A RDHQ worker -l info Yesterday the app was down and accessing the site returned ERR_CONNECTION_TIMED_OUT. When I looked at the logs, I saw that the celery process was showing an R14 (Memory usage exceeded) error: 2022-12-24T07:14:46.771299+00:00 heroku[celery.1]: Process running mem=526M(102.7%) 2022-12-24T07:14:46.772983+00:00 heroku[celery.1]: Error R14 (Memory quota exceeded) I restarted the dynos a couple of times, but the celery dyno immediately throws the same error after restart. I then removed the celery process entirely from my Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug After I pushed the new Procfile to Heroku, the app is still down! I tried manually scaling down the web dyno and then scaling it up again - nothing. This is what the logs show: 2022-12-24T07:57:26.757537+00:00 app[web.1]: [2022-12-24 07:57:26 +0000] [12] [DEBUG] Closing connection. 2022-12-24T07:57:53.000000+00:00 app[heroku-postgres]: source=HEROKU_POSTGRESQL_SILVER addon=postgresql-reticulated-80597 sample#current_transaction=796789 sample#db_size=359318383bytes sample#tables=173 sample#active-connections=12 sample#waiting-connections=0 sample#index-cache-hit-rate=0.99972 sample#table-cache-hit-rate=0.99943 sample#load-avg-1m=0.01 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0.076923 sample#tmp-disk-used=543600640 sample#tmp-disk-available=72435191808 sample#memory-total=8038324kB sample#memory-free=3006824kB sample#memory-cached=4357424kB sample#memory-postgres=25916kB sample#wal-percentage-used=0.06576949341778418 2022-12-24T07:59:26.615551+00:00 app[web.1]: [2022-12-24 07:59:26 +0000] [12] [DEBUG] GET /us/first-aid-cover/california/ 2022-12-24T07:59:28.421560+00:00 app[web.1]: 10.1.23.217 - - [24/Dec/2022:07:59:28 +0000] "GET /us/first-aid-cover/california/?order_by=title HTTP/1.1" 200 … -
Display related foreign keys in the parent model in Django admin
I'm using PostgreSQL for the DB. I have two models: Project: can contain N Assets. Asset: has a Foreign Key field that points to a Project. An Asset is related to 1 Project. I want the user to be able to set the order of the Assets of a Project in the Django Admin in a handy way like ordering a list in the edit Project screen. The order of the Assets is important in my bussiness logic, but I dont want the user to set the order in each individual Asset (just to improve UX). Is there a way to show a field in the Project admin screen that lists all the Assets that are related to the project and allow the user to order it as he wishes? I did not found any solution to this more than adding a new field in the Asset modal to specify the order and handling the logic by myself (which is expected), however, I don't want it to be a field that have to be changed manually in each individual Asset. -
How to convert my django web app to a portable .exe software?
I have developed a django project and currently deployed on localhost. Currently I am running it through a .bat file giving it the path of project directory and opening its IP address in chrome browser. MY BAT FILE - start chrome http://127.0.0.1:500 cd Desktop cd SFM python manage.py runserver 500 I want my project to make executable and portable after someone downloads it, it downloads all packages and libraries and runs the command to run it automaitcally. Help me.... -
What is the right redirection?
I'm a beginner in Django and I want to display the username from the nav bar. I did not use User athentication. I only created custom database table called JobseekerJobseeker database table. Because the criteria is the user should be able to login using username or email then password. I was able to achieve that using this code,code for username/email login. Now my problem is using {{request.user}} in the nav bar it display the superuser's username, instead on the jobseeker username. Superuser's username. Code for the HTML I want to display the username that i inputed in the login form. It should be one of these username that needs to be displayed sorry for the bad english but hopefully it makes sense. -
How to get rid of not existing errors?
Here is my code from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework import viewsets, status from .models import Actor from .serializers import ActorSerializer # Create your views here. class ActorView(viewsets.ModelViewSet): model = Actor queryset = model.objects.all() permission_classes = (AllowAny,) serializer_class = ActorSerializer http_method_names = ['get', 'post', 'put', 'delete'] def list(self, request): serializer = ActorSerializer(self.queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request): serializer = ActorSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.validated_data['name']) return Response("OK", status=status.HTTP_200_OK) else: return Response("nie ok") Pylance thinks that this line: print(serializer.validated_data['name']) is incorrect, but it is correct. Code works fine and it doesn't displaying any errors while server is running and request is sent. But it is underlined in red, so something must be wrong. How can i get rid of those "errors"? "__getitem__" method not defined on type "empty" Object of type "None" is not subscriptable I am using VSC python 3.10. I have alredy tried uninstalling Pylance and changing its' version but all for nothing. -
Django include template show no data
I am trying to include a html file, into my course page , but when i add the code it show just first tag that is h3 and don't show other data why ? the code : {% include 'android/side_bar_good_posts.html' %} note : i have added this code in other pages in my website and it work and show all data but in this page course it don't show anything else ( most read articles ) word -
pass a list to js to display a chart
Hi I am new to Js and I have some issues to display my chart property. I am trying to pass a list to the template, then grab by my js scrpit, and last pass that list to display chart. I have this tag en my template: <div style="display: none" id="listData" listmonth="{{ month_profit_list }}"></div> Then pass to js file like this: var ctx1 = $("#worldwide-sales").get(0).getContext("2d"); const div1 = document.getElementById('listData'); var listMonth = div1.getAttribute('listmonth'); console.log(listMonth) var myChart1 = new Chart(ctx1, { type: "bar", data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Ago","Sep","Oct","Nov","Dec"], datasets: [{ label: "USA", data: listMonth, backgroundColor: "rgba(0, 156, 255, .7)" }, ] }, options: { responsive: true } }); In fact my list displays in console fine but y got this chart: when my list output in cosole is this = [129, -69, 226, 25, 151, 114, -79, 4, 49, 61, -76, 65] Any idea why is showing in chart wrong data? -
ImportError: cannot import name 'Users' from partially initialized module tasks file
ImportError: cannot import name 'Users' from partially initialized module 'users.models from .models import Users from celery import shared_task from django.core.mail import send_mail from server import settings @shared_task() def send_mail_task(user_id): user = Users.objects.get(id=user_id) send_mail( subject='Congratulations!', message=f'Congratulations {user.username}', from_email=settings.EMAIL_HOST_USER, recipient_list=["waelelsafty07@gmail.com", ], fail_silently=False, ) print('Email sent successfully') return f'Email sent successfully' checking installing celery -
Django: make a copy of model admin page into website so normal users can do all the things that staff could
i am looking for make a replica of models admin page (like posts,comments, etc..) into a part of my website. so for example non staff users with given permission could make new posts or filter the posts or even delete them. basically a complete copy of post admin page with all its features -
How to handle IntegrityError exception of conditional unique constraint in Django/Postgres?
let's assume we have the below model class code: from django.db import models class SupplierAddress(models.Model): """Model to create supplier's address instances""" class Meta: """Customize django default way to plural the class name""" verbose_name = 'Supplier Address' verbose_name_plural = 'Supplier Addresses' constraints = [ models.UniqueConstraint( fields=['supplier', 'address'], name='supplier_address_unique_appversion' ), models.UniqueConstraint( fields=['supplier'], condition=models.Q(is_default=True), name='one_default_address_per_supplier' ) ] # Define model fields. supplier = models.ForeignKey( 'Supplier', on_delete=models.CASCADE, related_name='supplier_addresses_supplier' ) address = models.ForeignKey( 'Address', on_delete=models.CASCADE, related_name='supplier_addresses_address' ) is_default = models.BooleanField(default=False) def __str__(self): """String representation of model objects""" return '{}, {}'.format(self.supplier, self.address) This model constraints will make sure there is unique constraint between supplier and address foreign keys AND a conditional unique constraint between supplier and is_default when it's True. The conditional unique constraint in Django and Postgres as database engine, will raise an exception: IntegrityError: duplicate key value violates unique constraint... In case the input by user go against the constraint condition. Ideas to handle such case: 1- handle such case on user side, like using forms But not a good idea for testing. 2- using clean() method and raise an error message, like: def clean(self, *args, **kwargs): """Restrict the add/change to model fields""" if self.is_default is True: if SupplierAddress.objects.filter( supplier=self.supplier, is_default=True ).exclude(id=self.id).count() >= 1: … -
taggit django error, access posts through the links of the tags, error Cannot query "jazz": Must be "Post" instance
I'm new to Django and I'm studying through the book Django 3 by example, when implementing the tags, at the end of chapter 2, I can't access them. The assigned error is as follows: "Cannot query "jazz": Must be "Post" instance" my views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 2) # 2 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,'blog/post/list.html',{'page': page,'posts': posts, 'tag': tag}) my urls.py urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), # path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share'), my list.html % block content %} <h1>My Blog</h1> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "blog:post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <p class="date"> Published … -
how to connect correctly fastapi and aiogram
I have a api on fastapi with db, how correctly get data from server? Just connect to fastapi db or use http requests? I saw how used Django Rest Framework and aiogram -
I can't get VScode to activate a virtual environment called ll_env
I'm trying to create a virtual environment for Django Project ,(Chapter 18-20) of Python Crash Course, and it won't work I'm on python version 3.10.7 Here is a link to the book: https://www.google.com/books/edition/Python_Crash_Course_2nd_Edition/w1v6DwAAQBAJ?hl=en&gbpv=1 you can find the chapter in question at page 379 here is the file that generates when you run the first command: https://github.com/Hunty405/ll_env C:\Python\Projects\Learning Log> python -m venv ll_env **<- Create virtual Environment** C:\Python\Projects\Learning Log> source ll_env/bin/activate **<- Activate virtual Environment** source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + source ll_env/bin/activate + ~~~~~~ + CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\hlehm\Onedrive Transfer\Python\Projects\Learning Log> I tried running the given codes in the book but i can't get it to activate the environment please help