Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError object is not iterable on (rest_framework) Django
I'm unable to understand how to handle this error. TypeError at /auctions/api/AuctionDetails/68/ 'Request' object is not iterable in "auctions/view.py" def detail(request, auction_id): auction = get_object_or_404(Auction, pk=auction_id) auction.resolve() already_bid = False if request.user.is_authenticated: if auction.author == request.user: own_auction = True return render(request, 'auctions/detail.html', {'auction': auction, 'own_auction': own_auction}) user_bid = Bid.objects.filter(bidder=request.user).filter(auction=auction).first() if user_bid: already_bid = True bid_amount = user_bid.amount return render(request, 'auctions/detail.html', {'auction': auction, 'already_bid': already_bid, 'bid_amount': bid_amount}) return render(request, 'auctions/detail.html', {'auction': auction, 'already_bid': already_bid}) in API folder: api/serilazers.py class AuctionsSerializer(serializers.ModelSerializer): class Meta: model = Auction fields = ["title", "desc", "min_value", "is_active", "date_added","winner","author","image","date_added","final_value","title"] in api/url.py path('AuctionDetails/<int:auction_id>/', AuctionsDetailsApiView.as_view()), I tried to put this code in "api/views.py" Thank you very much! -
django gunicorn on nginx problem to deploy in production
hello i have django in www directory and i have created gunicorn socket so its kinda works but problem is to cannt create secret kay in environment and cannt find what type of file should be i have seen how created for docker yml file and also .sh file but how can i create file which will be writed some file to change instance like yml file gunicorn django_project.wsgi also this runs for like dev like runserver and i have to pin in gunicorn and rund to be production right? i have but still cannt find how to make backside code for environment ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2021-02-01 09:24:43 UTC; 1h 13min ago TriggeredBy: ● gunicorn.socket Process: 66236 ExecStart=/home/user/venv/bin/gunicorn django_project.wsgi (code=exited, status=3) Main PID: 66236 (code=exited, status=3) Status: "Gunicorn arbiter booted" Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/var/www/html/web/django_project/settings.py", line 23, in <module> Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: SECRET_KEY = os.environ['SECRET_KEY'] Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: File "/usr/lib/python3.8/os.py", line 675, in __getitem__ Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: raise KeyError(key) from None Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: KeyError: 'SECRET_KEY' Feb 01 09:24:43 ip-123-44-51-87 gunicorn[66248]: [2021-02-01 09:24:43 +0000] [66248] … -
How to control allowed methods in Django Rest Framework?
I've already seen a number of questions on this topic, but none of the answers seem to solve my issue. I have the following python modules: views.py: class MyObjectViewSet(viewsets.ModelViewSet): queryset = MyObject.objects.all() serializer_class = MyObjectSerializer permission_classes = [permissions.AllowAny] # For testing @action(methods='POST', detail=True) def my_request(self, request, *args, **kwargslf): # Do stuff urls.py: router = routers.DefaultRouter() router.register(r'myobject', views.MyObjectViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] When I try to make an actual POST-request to the my_request-route, I get Method POST not allowed. But as I understand, ModelViewSet should allow all methods. Even if I include http_method_names = ['get', 'post', 'patch', 'put', 'head', 'delete'] in my view, it still doesn't work. -
Download processed opencv images from Django template
I am new, both to Django and Opencv. I work on a Django website where i would like to allow the user to upload some images, to process them and in the end to download them without storing them in the database. How can i include a link in the template where the user can download the processed images from? cv2.imwrite returns a boolean value. Is there any way to append the processed images to a list to be able to send it back to the template? -
I want to search for products in my html page using javascript but it does not show anything
I am making an online shopping website as in django and wanted to use the searchbar using javascript but can't do it right. I think that I am not accessing the elements in javascript correctly. Any help would be appreciated. TIA! HTML Code <div id = 'Products'> <div class="col-12"> <div class="row"> <div class="col-12 py-3"> <div class="row"> <div class="col-12 text-center text-uppercase"> <h2>Featured Products</h2> </div> </div> <div class="row"> <!-- Product --> {% for prd in prds %} <div class="col-lg-3 col-sm-6 my-3"> <div class="col-12 bg-white text-center h-100 product-item"> <div class="row h-100"> <div class="col-12 p-0 mb-3"> <a href=" {% static 'product.html' %} "> <img src="{{prd.img.url}}" class="img-fluid"> </a> </div> <div class="col-12 mb-3"> <a href=" {% static 'product.html' %} " class="product-name">{{prd.name}}</a> </div> <div class="col-12 mb-3"> <span class="product-price"> ${{prd.price}} </span> </div> <div class="col-12 mb-3 align-self-end"> {% if user.is_authenticated %} <button onclick="location.href= '/xyz/{{prd.id}}'"class="btn btn-outline-dark" type="submit" ><i class="fas fa-cart-plus mr-2"></i>Add to cart</button> {% else %} <a href= "accounts/login"><button class="btn btn-outline-dark" type="submit" ><i class="fas fa-cart-plus mr-2"></i>Add to cart</button></a> {% endif %} </div> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> Search Bar <div class="input-group"> <input type="search" onkeyup="search_product()" class="form-control border-dark" placeholder="Search..." required> <div class="input-group-append"> <button class="btn btn-outline-dark"><i class="fas fa-search"></i></button> </div> </div> JavaScript Code function search_product() { let input … -
Is the a Django serializer to serialize reverse relations individually?
I have these two models, where A has a many-to-one relation with B: class A(models.Model): field_A1 = models.ForeignKey('B', ...) field_A2 = ... class B(models.Model): field_B = ... #primary key I know I can setup a serializer for B to also serialize the related instances of A, taking advantage of .a_set. For instance, if I tried to serialize an instance of B having two related instance of A I would get something like the following: { "field_B": "instance of B", "a_set": [ { "field_A2": "first related instance of A" }, { "field_A2": "second related instance of A" } ] } What I want the serialize to output instead is the 'product' of instance of B with the related instances of A, e.g. in the same scenario as in the previous example, I would like to get the following: [ { "field_B": "instance of B", "field_A": "FIRST related instance of A" }, { "field_B": "instance of B", "field_A": "SECOND related instance of A" } ] How can I obtain this in Django? Do I need to populate a data structure with the product myself or there's something built-in in the framework I can use? -
How to resolve “django.core.exceptions.ImproperlyConfigured: Application labels aren't unique
Traceback (most recent call last): File "/home/lewis/Documents/FakeNewsProject/fakenewsgui/myapp/class_learner.py", line 62, in class ArticleExample(models.Model): File "/home/lewis/.local/lib/python3.6/site-packages/django/db/models/base.py", line 321, in new new_class._meta.apps.register_model(new_class._meta.app_label, new_class) File "/home/lewis/.local/lib/python3.6/site-packages/django/apps/registry.py", line 231, in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'articleexample' models in application 'Article_Examples': <class 'myapp.models.ArticleExample'> and <class 'main.ArticleExample'>. I have tried various solutions from here but none seems to have worked -
Specify database inspectdb in django
Is there any way how can I inspectdb specific database in Django. I've been open new connection and then I want to inspectdb under matchyv3_revamp. How do I specify matchyv3_revamp in inspectdb? It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Currently I'm using this line python manage.py inspectdb --database=matchy > models.py but it seems it inspect all database under matchy connection, is there any way to specify matchyv3_revamp? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'payroll', 'USER':'root', 'PASSWORD':'', 'HOST':'localhost', 'PORT':'3306', }, 'matchy': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'matchy', 'USER':'test_user', 'PASSWORD':'sample', 'HOST':'172.26.111.111', 'PORT':'80', }, } -
Using middleware class for user authentication in Django project
One of my company's project is in Django and I was assigned to a task to 'add authentication to the top-level router' so we don't forget to add an authentication code to every view, such as: if not request.user.is_authenticated: return HttpResponseRedirect('/admin/login/?next=/admin/some-page/') After doing a bit of research I found out that this can be accomplished by writing my own middleware. I was not familiar at all with the concept until doing my homework. So now I am trying to write a LoginRequiredMiddleware class that intercepts every request and sends the user to the login page if not authenticated and, after authentication, to the original page the user was trying to access. This is the code I have so far. middleware.py from django.conf import settings from django.http import HttpResponseRedirect from django.utils.deprecation import MiddlewareMixin from django.utils.http import is_safe_url import re EXEMPT_URLS = [re.compile(settings.LOGIN_REDIRECT_URL.lstrip('/'))] # '/admin' class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user'), "The Login Required Middleware" if not request.user.is_authenticated: path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): redirect_to = settings.LOGIN_REDIRECT_URL if len(path) > 0 and is_safe_url( url=request.path_info, allowed_hosts=request.get_host()): redirect_to = f"{settings.LOGIN_REDIRECT_URL}/login?next={request.path_info}" return HttpResponseRedirect(redirect_to) I have already registered the middleware in the MIDDLEWARE list in settings.py and included both SessionMiddleware … -
Django Rest Framework - ImageField - use default value if no image is provided
I am sending a POST request with Axios using FormData that contains an individual image and also a list of images, like this: React State: "thumbnail": thumbnailImage, "gallery": [ galleryImage0, galleryImage1, galleryImage2 ] FormData: formData.set("thumbnail", this.state.thumbnail); for (let image of document.querySelector("#gallery").files){ formData.append("gallery", image); } Note: this part is probably fine, as the problem persists even when using Postman to craft the request In Django, using DRF I can perfectly deserialize this data if there are actual images sent, but if for example the "thumbnail" does not contain a file (user did not choose a file), I get the following: [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')] What I actually want is to use the default provided in the model, which looks like this: class Item_ThumbnailImage(models.Model): image = models.ImageField(upload_to=hash_image_thumbnail, default='items/no-image.gif', blank=True) belongs_to = models.ForeignKey( 'Item', related_name='thumbnail', on_delete=models.CASCADE) I get the data ready this way: thumbnail_data = { 'belongs_to': item.id, 'image': request.data.get("thumbnail") } Here's the deserialization: thumbnail = Item_ThumbnailImageSerializer(data=thumbnail_data) if thumbnail.is_valid(): thumbnail.save() else: print(thumbnail.errors) Serializer: class Item_ThumbnailImageSerializer(serializers.ModelSerializer): class Meta: model = Item_ThumbnailImage fields = '__all__' I have tried this in the serializer: image = serializers.ImageField(required=False, allow_empty_file=True, allow_null=True) ...along with this: thumbnail_data = { 'belongs_to': … -
How do I make a project for purchase orders ؟ as described on Body
The life cycle of purchase order within an organization or company How do I implement the automatic transfer mechanism after approval of the request? What are the packages required to implement this project? What are the sources that talk about such topics? details User A writes the purchase order after pressing Save, and it is sent automatically to user B and the status of the request changes to the user name B and a notification arrives to the user B has a purchase order task If User B approves, the request will go to User C automatically and the status of the request changes to User C name and a notification will be sent to the users of the status of the purchase order If User C approves, the request will go to User D automatically and the status of the request changes to User D name and a notification will be sent to the users of the status of the purchase order If the user has approved, the request will be launched to the user Z automatically and the status of the request changes to the name expired, and a notification will be sent to the users of the … -
Django Using setCustomValidity method in form fields clean
new to Django and Python here, building my first project. I´m making a form for registering new user and I´m controlling my fields in a forms.py file class UserRegisterForm(forms.ModelForm): password1 = forms.CharField( label='Contraseña', required=True, widget=forms.PasswordInput( attrs={ # 'placeholder': 'Contraseña', 'class': 'input-group-field', 'oninvalid': "this.setCustomValidity('Ingrese una contraseña')", 'oninput': "setCustomValidity('')" } ) ) password2 = forms.CharField( label='Contraseña', required=True, widget=forms.PasswordInput( attrs={ # 'placeholder': 'Repetir Contraseña', 'class': 'input-group-field', 'oninvalid': "this.setCustomValidity('Repita la contraseña')", 'oninput': "setCustomValidity('')" } ) ) class Meta: """Meta definition for Userform.""" model = User fields = ( 'user_name', 'full_name', 'phone', 'email', 'role', 'gender', 'date_birth', ) widgets = { 'user_name': forms.TextInput( attrs={ # 'placeholder': 'Usuario ...', 'class': 'input-group-field', 'max_length': '20', 'oninvalid': "this.setCustomValidity('Ingrese un nombre de usuario')", 'oninput': "setCustomValidity('')" } ), 'full_name': forms.TextInput( attrs={ # 'placeholder': 'Nombres ...', 'class': 'input-group-field', 'max_length': '100', 'oninvalid': "this.setCustomValidity('Ingrese su nombre completo')", 'oninput': "setCustomValidity('')" } ), 'phone': forms.TextInput( attrs={ # 'placeholder': 'Teléfono ...', 'class': 'input-group-field', 'max_length': '50', 'oninvalid': "this.setCustomValidity('Ingrese su teléfono')", 'oninput': "setCustomValidity('')" } ), 'email': forms.EmailInput( attrs={ # 'placeholder': 'Correo Electronico ...', 'class': 'input-group-field', 'max_length': '100', 'blank': True, 'oninvalid': "this.setCustomValidity('Ingrese un mail válido')", 'oninput': "setCustomValidity('')" } ), 'role': forms.Select( attrs={ # 'placeholder': 'Rol ...', 'class': 'input-group-field', 'required': True, } ), 'gender': forms.Select( attrs={ # 'placeholder': 'Género ...', 'class': 'input-group-field', … -
Estoy recibiendo IOError: [Errno 13] Permission deniedy no sé qué está mal
from django.http import HttpResponse from django.template import Template, Context def InterPro(request): doc_externo=open("C:/Users/KAMI-SAMA/Documents/Pg InterPro/WedInterPro/plantillas") plt=Template(doc_externo.read()) doc_externo.close() ctx= Context() return HttpResponse(doc_externo) #"""me sale este error""" Método de solicitud: OBTENER URL de solicitud: http: // localhost: 8000 / InterPro / Versión de Django: 2.1 Tipo de excepción: FileNotFoundError Valor de excepción: [Errno 2] No existe tal archivo o directorio: 'C: / Users / KAMI-SAMA / Documents / Pg InterPro / WedInterPro / plantillas' Ubicación de excepción: C: \ Users \ KAMI-SAMA \ Documents \ Pg InterPro \ WedInterPro \ WedInterPro \ views.py en InterPro, línea 5 Ejecutable de Python: C: \ Archivos de programa \ Python37 \ python.exe Versión de Python: 3.7.0 -
Django - Reset a save variable to 0, preferably at home view
I'm creating a simple quiz (99% done), just need help with one last thing - probably trivial to intermediate/advanced programmers. I have created a save variable to save the user's current score. This is so that the user navigates from page to page and can still see their current score. As the user navigates last template view, it gives the final score and a link to redirect to the homepage. This allows the user an opportunity to "retake the quiz". At this moment (home page) I need help to reset the saved score variable to 0. Please let me know how I can do this, thanks in advance! models.py class Scorer(models.Model): score = models.IntegerField(default=0) page = models.IntegerField() condition_number = models.IntegerField(default=0) views.py def vote(request, question_id, *args, **kwargs): model = Question template_name = 'quizzes/vote.html' question = get_object_or_404(Question, pk=question_id) ### To create user scoring system ### scorer, created = Scorer.objects.get_or_create(page=1) try: selected_choice = question.answer_set.get(pk=request.POST['answer']) ### To save user score ### if selected_choice in Answer.objects.filter(id=1): scorer.score +=10 scorer.save() elif selected_choice in Answer.objects.filter(id=6): scorer.score +=10 scorer.save() elif selected_choice in Answer.objects.filter(id=12): scorer.score +=10 scorer.save() elif selected_choice in Answer.objects.filter(id=13): scorer.score +=10 scorer.save() elif selected_choice in Answer.objects.filter(id=19): scorer.score +=10 scorer.save() elif selected_choice in Answer.objects.filter(id=22): scorer.score +=10 scorer.save() elif … -
Django urls.py not call the right view class
Here is my code: urls.py: urlpatterns = [ path('', showGameLists.as_view(), name='home'), path('<pf>/',showGameLists.as_view(), name='platforms'), path('<pf>/<curDate>/', showGameLists.as_view(), name = 'pfWithDate'), path('game/<slug>/', showGameInformation.as_view(), name = 'gameInformation'), ] view.py: class showGameLists(FormView): ...... class showGameInformation(View): template_name = "showList/gameDetail.html"; def get(self, request, *args, **kwargs): gameSlug = self.kwargs['slug']; gameInf = getInformation(gameSlug); return render(request, self.template_name, {'gameInf': gameInf}); in the HTML page, I have a <a href="{% url 'gameInformation' slug=game.slug %}> but it seems after I click it, he call the showGameLists not the showGameInformation. I try to change URL to urlpatterns = [ path('', showGameLists.as_view(), name='home'), path('<pf>/$',showGameLists.as_view(), name='platforms'), path('<pf>/<curDate>/$', showGameLists.as_view(), name = 'pfWithDate'), path('game/<slug>/', showGameInformation.as_view(), name = 'gameInformation'), ] and it works. But if I don't want to add $ at last, what should I do? -
Django DRF calling ModelSerializer with model object as dict throws 'object has no attribute RelatedManager'
I'm trying to call a ModelSerializer named RegistrationSummarySerializer with my model object. When I'm trying to insert the object directly it throws Invalid data. Expected a dictionary, but got Registration. When I create a dict from my object, it gets validated successfully but now the Serializer throws AttributeError: 'collections.OrderedDict' object has no attribute 'participantgroup_set' as obj is not the model object but a dict, as obj is now an OrderedDict and not a Registration. Does someone have tips how to solve that? registration = get_object_or_404(Registration, pk=data['id']) registration_dict = { 'id': registration.id, 'scout_organisation': registration.scout_organisation.name, 'responsible_persons': [i.username for i in registration.responsible_persons.all()], 'event': registration.event.name, 'free_text': registration.free_text, 'is_confirmed': registration.is_confirmed, 'is_accepted': registration.is_accepted } serializer = RegistrationSummarySerializer(data=registration_dict) valid = serializer.is_valid(raise_exception=True) print('valid', valid) registration_data = serializer.data print('serializer data ', registration_data) class RegistrationSummarySerializer(serializers.ModelSerializer): total_participants = serializers.SerializerMethodField('get_total_participants') responsible_persons = serializers.SlugRelatedField( many=True, read_only=False, queryset=User.objects.all(), slug_field='username' ) scout_organisation = serializers.SlugRelatedField( many=False, read_only=False, queryset=ScoutHierarchy.objects.all(), slug_field='name' ) event = serializers.SlugRelatedField( many=False, read_only=False, queryset=Event.objects.all(), slug_field='name' ) class Meta: model = Registration fields = ( 'total_participants', ) def get_total_participants(self, obj): num_group = obj.participantgroup_set.aggregate(num=Coalesce(Sum('number_of_persons'), 0))['num'] num_pers = obj.participantpersonal_set.count() result = num_group + num_pers self.total_participants = result return result -
How to pass form data to stripe webhook in Django so it emails them to me once payment's done
I'm trying to get my Django app to email order details to me (name, shipping address, etc.) once my Stripe webhook confirms payment but have no idea how to pass on that data. To webhook? (checkout function redirects to a Stripe server checkout) buy.html <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="nume">Nume si Prenume</label> <input type="text" name="nume" class="form-control" id="nume" required> <div class="form-group"> <label for="strada">Strada</label> <input type="text" name="strada" class="form-control" id="strada" required> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" id="email" required> </div> <div class="form-group"> <label for="telefon">Telefon</label> <input type="text" name="telefon" class="form-control" id="telefon" required> </div> <div class="form-group"> <label for="cantitate">cantitate</label> <input type="number" id="cantitate" name="cantitate" min="1" max="8" required> </div> <button type="submit" class="btn btn-primary">Send order</button> <div class="jumbotron"> <h1 class="display-3">The Product</h1> <p class="lead">Purchase The Product for only $99.</p> <a href="#" id="buy_now_btn" class="btn btn-primary">Buy Now</a> </div> <script src="https://js.stripe.com/v3/"></script> <script> const buy_now_button = document.querySelector('#buy_now_btn') buy_now_button.addEventListener('click', event => { fetch('/checkout/') .then((result) => { return result.json() }) .then((data) => { var stripe = Stripe(data.stripe_public_key); stripe.redirectToCheckout({ sessionId: data.session_id }).then(function (result) { }); }) }) </script> I already have a working email function set up and can call it with sendemail('sample@outlook.com', 'subject', email_content) And also got how to extract the data from the .html form. Just don't know how to send email … -
Drop down list for different products
Drop down list for different products in page. my html page {% for deal in Deals %} <div id="innermain"> <div id="dealsdesc"> <div id="desc"> <div class="deals_fav flex-row"> <span class="smallgreytext">{{ deal.source }}</span><br/> {% if request.session.name %} <span class="far fa-heart dropbtnDeals" onclick="myFunctionDeals()" data-original-title="Click" data-toggle="tooltip" style="position: relative; left: 154px; color: #01ABAA; cursor: pointer;"></span> <div class="dropdown-contentDeals" id="myDropdownDeals"> <a href="#" data-dismiss="modal" data-target="#myModal_create" data-toggle="modal">Create new list</a> <a href="/wishlist_deal/{{deal.id}}">Deals</a> </div> {% endif %} </div> {% if deal.type_of_product == 'D' %} <div class="price_presentation flex-row"> <span><strike style="color:lightgray;">${{ deal.price }}</strike></span><br/> <span class="dealsale_price">${{ deal.sale_price }}<span class="pipe">|</span></span> <span class="deal_rebate">{{ deal.rebate }}%</span><br/> </div> {% endif %} {% endfor %} In views.py def wishlist_deal(request, id): data_deals = master_table.objects.filter(type_of_product='D', id=id) if data_deals: for i in data_deals: wishqury = Wishlist_cl.objects.filter(wished_item=i.product_name).first() if wishqury is not None: messages.error(request, "Already this product exists in the selected wish list.") else: Wishlist_cl.objects.create(wished_item=i.product_name, email=email, price=i.price, sale_price=i.sale_price, image=i.img_url, type_of_product=i.type_of_product, adv_id=i.id, name="Deals") messages.success(request, "Added successfully") return redirect(request.META.get('HTTP_REFERER')) return redirect(request.META.get('HTTP_REFERER')) For list of products it has drop down list should be prompted in for different products after clciking fav icon. Please help me ton achieve this thank you. -
how can i transilate english to arabic language using checkbox toggle button
i am working in python-Django.I need to convert english to arabic language by using checkbox <input type="checkbox" id="che" style="margin-top: 30px;padding-top: 15px;"> #che { -webkit-appearance: none; position: relative; width: 80px; height: 40px; background-image: url(../images/us.png); background-size: cover; border-radius: 50px; outline: none; transition: background-image .90s; box-shadow: 0px 2px 5px 1px gray; } #che:before { content: ""; position: absolute; top: 0; left: 0; height: 40px; width: 40px; background-color: navy; border-radius: 50px; transition: all .9s; background-color: #004d66; } #che:checked { background-image: url(../images/kwd.png); transition: background-image .90s; } #che:checked:before { transform: translate(100%); transition: all .9s; background-color: #ECF0F3; } this is the image of my checkbox-toggle button -
Is it feasible to create an extra field that indicates the number of related entries to be searched in another table?
My goal is to get the best compromise between space and performance for the situation. I have two similar situations but they differ slightly. Situation 1: Suppose I have two tables for a classic situation: 'survey' and 'question'. class Survey(models.Model): survey_owner_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) survey_title = models.CharField(max_length=70, blank=False, null=False) class Question(models.Model): survey_id = models.ForeignKey(Survey, on_delete=models.CASCADE, blank=True) question = models.TextField(max_length=150, null=False, blank=True) One survey can have up to 10 questions, but may also have fewer, but must have at least 5. I am pondering whether it would be feasible to add another field to the 'survey' table that indicates the number of questions that this survey has, and therefore, the number of rows that will need to be queried in the 'question' table, so that not the entire table needs to be queried from start to end, each time the survey is pulled up. In this case, a survey will likely not be pulled up as frequently. For example: class Survey(models.Model): survey_owner_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) survey_title = models.CharField(max_length=70, blank=False, null=False) question_amount = models.IntegerField(blank=False, null=False) Situation 2: Suppose a similar situation as in the survey-question example, but in this case, the survey can only have up to 4 questions (but may also … -
Conditional formatting Bootstrap cards in Django
I am building a Django template using Bootstrap 4. I'm looking at formatting the badges based on a categorical field from my Project model (for example, if category is "Complete", I'd like the badge to be green). So far, I've created this long if / elif statement with a lot of repetition but as I'm looking at implementing something with more categories, I feel like I'm missing out on a smarter / cleaner way to do this. Below is my Django template (which currently leverages default Bootstrap colors / formats). {% if project.status == "complete" %} <span class="badge rounded-pill bg-success text-light">{{ project.status|title }}</span> {% elif project.status == "review" %} <span class="badge rounded-pill bg-active text-light">{{ project.status|title }}</span> {% elif project.status == "autopilot" %} <span class="badge rounded-pill bg-light text-dark">{{ project.status|title }}</span> {% elif project.status == "issues" %} <span class="badge rounded-pill bg-warning text-dark">{{ project.status|title }}</span> {% elif project.status == "submitted" %} <span class="badge rounded-pill bg-dark text-light">{{ project.status|title }}</span> {% elif project.status == "draft" %} <span class="badge rounded-pill bg-info text-light">{{ project.status|title }}</span> {% endif %} Things that I've been thinking about but there must be something simpler or more straightforward: Create a new model attribute for formatting only (possibly derived from the categorical attribute). … -
I am not able to import of icons in django from font awesome. help me about it
I have copy the icon from font-awesome to my html file and bootstrap-CDN for font-awesome to CSS file but I am not able to show the icons. Is there any suggestion for me to show the icon -
Django tests response object zipped
So I have SearchResultView(listview) with a method get_context_data were i zip publications and images. For easy looping in the template: context['publications'] = zip(context['publications'], cover_images) Now I am testing and I have the following: def setUp(self): user = User.objects.create_superuser(username='admin', password='12345', email='') user.save() Publication.objects.create(title='eindhoven') Publication.objects.create(title='لحضور المؤتمر الدولي العاشر ليونيكود') Publication.objects.create(title='مزامير') #mazamir And this: def test_search_results(self): client = Client('127.0.0.1') response = client.login(username='admin', password='12345') response = client.get('/publication/show/', {'q': 'eindhoven'}) Now I need to unpack zip that is in the response. I tried the following: list(zip(*response.context['publications'])) list(zip(*response.context[-1]['publications'])) But they are returning an empty list. Anyone any ideas? -
BFF architecture with Python
I dont know if SO is the better place to discuss about that, but i need some opinions and suggestions about how to do a system using BFF architecture. I'm asking that, because at my internship i will need to refactor a system that was written with Golang and microsservices architecture with 4 services decoupled, and a BFF with Node. And now this system it will work with a single API and the BFF will be written in Python. Gimme some views about architecture and tools and how can i implement this. * I was thinking to implement that with Django, but i have never use this. Thanks for your help. -
How to save URL to a Django ImageField
I have Django model with Image field, but sometimes I don't need to actually upload file and store path to it, but I need to store only path. Especially url. I mean, I have web client, that receives both foreign urls like sun1-17.userapi.com and url of my own server, so sometimes I don't need to download but need to store url. Is it possible, to store url in ImageField, or I need to make CharField and save files via python? If its impossible, how do I save file in python3, having one, sent me via multipart?