Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Face detection box does not appear on the local server. (Django)
It is a mask detection code (camera.py) using Yolo model. I tried to implement this on django server. The video appeared on the screen by webcam without any problems. However, the face detection box is not showing up. I tried using VideoStream instead of VideoCapture, but the results were the same. And when I printed out the jpeg, I checked that it came out properly. What's the problem?... import cv2,os,urllib.request import numpy as np from django.conf import settings # from imutils.video import VideoStream import imutils # load our serialized face detector model from disk os.chdir(r'C:/Users/rjsgh/OneDrive/Desktop/Mask_Detection/warming_up_project/streamapp') weightsPath = "./face_detector/yolov4-tiny-obj_best.weights" cfgPath = "./face_detector/yolov4-tiny-obj.cfg" yoloNet = cv2.dnn.readNet(weightsPath, cfgPath) layer_names = yoloNet.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in yoloNet.getUnconnectedOutLayers()] LABELS = ["Mask", "No Mask"] COLORS = [(0,255,0), (0,0,255)] class yoloDetect(object): def __init__(self): self.vs = cv2.VideoCapture(0) def __del__(self): self.vs.release() cv2.destroyAllWindows() def detect_mask(self, frame): (h,w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1/255.0, (416, 416), swapRB=True, crop=False) yoloNet.setInput(blob) layerOutputs = yoloNet.forward(output_layers) class_ids = [] cofidences = [] boxes = [] for output in layerOutputs : for detection in output : scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5 : box = detection[:4] * np.array([w,h,w,h]) (center_x, center_y, width, height) = box.astype("int") x … -
how can I download image with different sizes in jquery or python django?
I have an image which is displayed to user. User can select the size of image which he/she want to download. How can I do so. I don't want to store the different sizes of image. I want to create a function with parameter specifying the size which will be called when the user click the download button. From that function the image should get downloaded (without changing the actual file size and should not create a new file or if created should not get stored anywhere). If it is possible to do such thing in jquery will be appreciated, so that there will be no need to send request to backend, if not then in python django. -
How do I send a post with Django superuser authorization with the post method of HttpClient in Angular?
Can someone tell me how to login to my Django superuser making a post? (I am using HttpClient) I usually use httpie to do it: http -a post lalala.com:80 whatever="whatever" Now I need to get django to do the same thing. I tried: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('mydjangosuperuser:mypassword') }) }; var item = ({key: key, url: url} as Object) return this.http.post<any>(this.fullDictURL, item, httpOptions) .pipe( catchError(this.handleError) ); } -
'CustomerPurchaseOrder' object has no attribute 'get_user_visible_fields'
I am doing import-export to excel in my admin.py, every time i click the import button i receive this error 'CustomerPurchaseOrder' object has no attribute 'get_user_visible_fields' i dont know what is wrong with my code, i been following the documentation (below). did i miss something in my code?. class CustomerPurchaseOrderResource(resources.ModelResource): class Meta: model = CustomerPurchaseOrder fields = ('profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) class CustomerPurchaseOrderAdmin(ImportExportModelAdmin): list_filter = ("process", "deliverySchedule", "inputdate") list_display = ( 'profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) ordering = ('id','requestedDate') resource_class = CustomerPurchaseOrder this is my models.py class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customerdeliveryaddress = models.ForeignKey(CustomerDeliveryAddress, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Delivery Address") customer_Purchase_Order_Detail = models.ForeignKey('CustomerPurchaseOrderDetail', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer Purchase Order") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") attachment = models.ImageField(upload_to='images', null=True, blank=True) requestedDate = models.DateField(auto_now_add=True) deliverySchedule = models.ForeignKey(DeliverySchedule, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Schedule") deliveryDate = models.DateTimeField(null=True, blank=True) instructionToSeller = models.CharField(max_length=500, null=True, blank=True) paymentmethod = models.ForeignKey('PaymentMethod', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") address = models.CharField(max_length=500, null=True, blank=True) city = models.CharField(max_length=500, null=True, blank=True) country = models.CharField(max_length=500, null=True, blank=True) recordStatus = models.ForeignKey(RecordStatus, on_delete=models.SET_NULL, null=True.) ..... this is the documentation i follow https://django-import-export.readthedocs.io/en/stable/getting_started.html this is my full traceback Environment: Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File … -
(Django) OperationalError at / no such column: minishop_app_products.user_id
I am building an ecommerce shop and I'm fectching items from database and rendering on the template. But i have this issue. i am trying to render a dynamic url and its throwing back some errors. i have tried debugging it but no avail. This is the error it displays (on the browser): OperationalError at / no such column: minishop_app_products.user_id Here are some code snippets: View.py from django.shortcuts import render from .models import * from django.http import HttpResponse def index(request): header = headerSlider.objects.all() new_item = Products.objects.all() context = { 'header': header, 'new_item': new_item, } return render(request, 'index.html', context) def product_single(request, pk): single_product = Products.objects.get(pk=id) print(single_product) sizes = Size.objects.all() context = { 'single_product':single_product, 'sizes': sizes } return render(request, 'product-single.html', context) Models.py from django.db import models from django.contrib.auth.models import User class headerSlider(models.Model): title = models.CharField(max_length=200 , null=True) description = models.CharField(max_length=400 , null=True) category = models.CharField(max_length=200 , null=True) image = models.ImageField(null=True, blank=False) def __str__(self): return self.title class Meta: verbose_name_plural = 'Head Slider' class Size(models.Model): size = models.CharField(max_length=50) def __str__(self): return self.size class Products (models.Model): product_title = models.CharField(max_length=200 , null=True) product_price = models.FloatField() product_category = models.CharField(max_length=200 , null=True) product_image = models.ImageField(null=True, blank=False) detail_title1 = models.CharField(max_length=200 , null=True) detail_title2 = models.CharField(max_length=200 , null=True) detail_description1 = … -
Crispy form filter user -> Cannot assign "<UserProfile: fredo>": "Channel.seller" must be a "User" instance
I don't understand why I got this issue and in addition my submit button is not displayed. My goals is to filter a specific type of user. The user I want to chose have a boolean true for a model field. channel/models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) is_sugar = models.BooleanField('Become sugar', default=False) slug = models.SlugField(editable=False) ... channel/forms.py class CreateChannelForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(CreateChannelForm, self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method="post" self.helper.layout = Layout( Field("name",css_class="single-input"), Field("seller",css_class="single-input"), ) self.helper.add_input(Submit('submit','Create a channel',css_class="btn btn-primary single-input textinput textInput form-control")) class Meta: model = Channel widgets = { 'name':forms.TextInput(attrs={'class':'','style':'','placeholder':'First group'}), } fields = [ 'name', 'seller', ] def __init__(self, *args, **kwargs): super(CreateChannelForm, self).__init__(*args, **kwargs) self.fields['seller'].queryset = UserProfile.objects.filter(is_sugar=True) -
Django : automatically fill in one of the fields of the form
I have a query for security reasons, I would like to automatically fill in one of the fields of the form. a- depending on the selected channel automatically fill in the seller field. b- if the consumer field (form.instance.consumer = self.request.user) does not match the channel user, return an error. if you have any idea or similar stack page I'm interested in :) forms.py #Channel RATING @method_decorator(login_required(login_url='/cooker/login/'),name="dispatch") class ChannelReview(FormView, ListView): model = Rating template_name = 'channel_review.html' form_class = ChannelRatingForm context_object_name = 'userrating' def get_context_data(self, **kwargs): context = super(ChannelReview, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): #form.instance.channel = self.object form.instance.consumer = self.request.user form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) models.py class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.channel.name class Meta: ordering = ['-publishing_date'] class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='channel/') date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField('Make it happen', default=False) … -
How to Connect celery to Redis without Password?
I know connect celery to Redis with Password? app = Celery('celery_tasks.tasks', broker='redis://:appleyuchi@127.0.0.1:6379/0') but how to connect celery to Redis without Password? Thanks for your help. -
template datepicker post form.is_valid send back error message not a valid date
I don t understand where is my mistake: my model: class Listing(models.Model): enddate= models.DateField('Ending Date', blank=False) forms: class NewListingForm(forms.ModelForm): def __init__(self, *args, **kwargs): self._newly_created = kwargs.get('instance') is None self.Creation_date = datetime.now() super().__init__(*args, **kwargs) class Meta: model = Listing _newly_created: bool # permit to test if instance is a new one or an existing instance fields = ('title','description','enddate','category','initialBid','photo','active') widgets = {'Creation_date': forms.HiddenInput(), 'author': forms.HiddenInput()} my template: {% load crispy_forms_tags %} {% block body %} <h2>{% if not listing_id %}Create Client {% else %} Edit {{ object.name }}{% endif %}</h2> <form id="create-edit-client" class="form-horizontal" action="" method="post" accept-charset="utf-8"> {% csrf_token %} {{ form.title|as_crispy_field }} {{ form.description|as_crispy_field }} <br> <br> <div class="row"> <div class="col-3"> {{ form.enddate|as_crispy_field }} </div> <div class="col-2"> {{ form.active|as_crispy_field }} </div> </div> <br> <br> <div class="form-actions"> <input type = submit type="submit" value="Save" name="submit"> </div> </form> <script> $(function () { $("#id_enddate").datetimepicker({ format: 'Y/m/d', changeMonth: true, changeYear: true }); }); </script> {% endblock %} views.py: def newlisting(request): form = NewListingForm() if request.method == "POST": form = NewListingForm(request.POST) if form.is_valid(): if form._newly_created: # test if the form concern a new instance form = form.save(request, commit=False) form.save(request) messages.success(request, 'listing saved') # message for inform user of success - See messages in html file return HttpResponseRedirect(reverse("index", {"title": … -
GET is working but POST is not working on Docker
The application is on Django configured with Docker. GET requests are working fine. But the POST requests are not working. I am adding the nginx.conf file below for the reference. The POST request is necessary for authentication. upstream app_server { server djangoapp:8000 fail_timeout=0; } server { listen 80; server_name samplewebsite.com; root /opt/djangoapp/src/samplewebsite/samplewebsite; index index.html; server_tokens off; location / { try_files $uri $uri/ /index.html; } location /media { alias /opt/djangoapp/src/media/; } location /static { alias /opt/djangoapp/src/static/; } location /api/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://app_server/; } location /admin/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_pass http://app_server/admin/; } client_max_body_size 128m; } Let me know if I need to add more information to the question. -
Creating if statment in Django Crispy Forms, conditional form layout
I am using Django Cripsy Forms. I want to write if else statement, when the value of field name is "Daisy" Age field should appears, otherwise there should not be field 'age". My code: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper.layout = Layout( HTML(form_opening.format('Cats')), 'name', 'age', HTML(form_closing), ), ``` -
Dynamic foreign key filter for add/change admin form django 2.2
I have 3 following models: class Brand(models.Model): name = models.CharField(max_length=255) class Branch(models.Model): name = models.CharField(max_length=255) class Admin(models.Model): brand = models.ForeignKeyField('Brand', on_delete=models.CASCADE) branch = models.ForeignKeyField('Branch', on_delete=models.CASCADE) I need to filter branches by brand Admin model in admin panel. In other words, when adding or changing new admin, I need to choose brand and based on brand I get branches. -
Configure DynamoDB in Django
I'm new using Django, and I'm trying to configure settings.py to define DynamoDB using a library called pynamodb. The main structure of my project is: ⌙ env ⊢ bin ⌙ lib ⌙ pynamodb ⌙ src ⊢ core ⌙ djangoserver ⌙ settings.py So, in settings.py i wrotte: DATABASES = { 'default': { 'ENGINE': '..env.lib.pynamodb', 'NAME': 'posts', } } But i get this error TypeError: the 'package' argument is required to perform a relative import for '..env.lib.pynamodb.base' I tried inserting package=pynamodb in different parts of the dictionary's arguments, but it doesn't work.. -
Object of type QuestionAnswer is not JSON serializable
I hope everyone is fine and safe! I am working on a requirement where data is taken from a voice synthesizer and convert to text and sent as a ajax request to the Django backend. In the backend it takes the values checks in the database and returns a JSON response to the front-end. I have below codes here and i tried changing the code but "i am getting Object of type QuestionAnswer is not JSON serializable error" and have no clue on moving further **views.py** def Answer(request): if request.method=='GET' and request.is_ajax(): question_asked=str(request.GET.get("message_now")) try: answer=QuestionAnswer.objects.filter(question=question_asked)[0] data={"data":answer} return JsonResponse({"success": True, "data": data}, status=200) except Exception as e: print(e) return JsonResponse({"success": False}, status=400) else: print("Not Suceess") **main.js** function chatbotvoice(message){ const speech = new SpeechSynthesisUtterance(); if(message!==null && message!==''){ $.ajax({ url: "http://127.0.0.1:8000/getanswer", type: 'GET', data: { message_now:message }, success: function (data) { speech.text=JSON.parse(data); window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, error: function(error){ speech.text = "Oh No!! I don't Know !! Maashaa Allah, I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours"; window.speechSynthesis.speak(speech); chatareamain.appendChild(showchatbotmsg(speech.text)); }, }); } } Please help me with this code and let me know if you need any more information -
Error: UNIQUE constraint failed: auth_user.username
I keep getting this error: UNIQUE constraint failed: auth_user.username I can't work out why though. I am trying to extend the User model in Django so I can build my own profile model if anyone has any tips on how to do that or why this error keeps appearing please could you let me know. Thanks. Also, if a Stack Overflow moderator is reading this, don't tell me I haven't researched this problem enough before posting this, because I have! Here is my code. models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length=32) lastName = models.CharField(max_length=32) nickName = models.CharField(max_length=32) phoneNumber = models.IntegerField() def __str__(self): return f'{self.user.username}' @receiver(post_save, sender=User) def create_profile_for_user(sender, instance=None, created=False, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) @receiver(pre_delete, sender=User) def delete_profile_for_user(sender, instance=None, **kwargs): if instance: user_profile = UserProfile.objects.get(user=instance) user_profile.delete() views.py from django.shortcuts import render from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from .models import UserProfile from .serializers import UserProfileSerializer from django.contrib.auth.models import User from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated, AllowAny class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer serializers.py from rest_framework … -
How to tell django to use variable as html?
So, I have created an html page and it gets content from Python.I am able to get the text from the python program in view.py but unable to set it as an html tags. I have setup the css and js in HTML file but only this problem is arising. Is there a way out? IN SHORT: How to tell Django that it is html and it has to simply join it in the code.(Not to use as text.) Details Python 3.8.2 Django 2.2.7 -
Error while installing misaka( using windows 10 OS ) in django virtual env
First Screenshot Second screenshot -
Django Serializer using multiple Models joined by and use it as api in Flutter application
I have a Model "Question" , which is inherited by class "MCQUestion". I have another model "Answer" along with model "Quiz" I am trying to create a serializer which displays all the Questions and its answers in a Quiz class Question(models.Model): """ Base class for all question types. Shared properties placed here. """ quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True, on_delete=models.CASCADE) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Figure")) content = models.CharField(max_length=1000, blank=False, help_text=_("Enter the question text that " "you want displayed"), verbose_name=_('Question')) explanation = models.TextField(max_length=2000, blank=True, help_text=_("Explanation to be shown " "after the question has " "been answered."), verbose_name=_('Explanation')) DIFFICULTY_LEVEL=[ ('1','Beginner'), ('2','Intermediate'), ('3','Advanced'), ('4','Exppert'), ] difficulty = models.CharField( max_length=2, choices=DIFFICULTY_LEVEL, default=2, ) objects = InheritanceManager() class Meta: verbose_name = _("Question") verbose_name_plural = _("Questions") ordering = ['category'] def __str__(self): return self.content class MCQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True, choices=ANSWER_ORDER_OPTIONS, help_text=_("The order in which multichoice " "answer options are displayed " "to the user"), verbose_name=_("Answer Order")) def check_if_correct(self, guess): answer = Answer.objects.get(id=guess) if answer.correct is True: return True else: return False @property def order_answers(self, queryset): if self.answer_order == 'content': return queryset.order_by('content') if self.answer_order == 'random': return queryset.order_by('?') if self.answer_order == 'none': … -
Integrating Django and React
So guys, I was trying to integrate Django and React. I have seen different ways of doing that. The method that I tried using is the one where there are two different folders frontend and backend. The backend has my Django project and the frontend has my React app created by the create-react-app command. I could fetch data from the API using axios. What has been difficult for me is the authentication part. It uses actions and reducers for that. It also uses tokens and other stuffs too. I found a tutorial which explains this clearly. But it's kindda outdated. I was following it step by step until it reached the authentication part and it didn't work, which made it more complicated for me to understand it. So I was looking for another approach or guide that I can follow for the integration of Django and React - specially the authentication part. Thank you! -
Trying to connect Django to Payfort with an API .(Payment gateway integration). when i run the pay.html it gives me a value error in my views file
Error is :ValueError: The view hadid.views.initiate_payment didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\Chaims music\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 I am adding my def initiate_payment below def initiate_payment(request): if request.method == "GET": return render(request, 'templates/pay.html') try: username = request.POST['username'] password = request.POST['password'] amount = int(request.POST['amount']) user = authenticate(request, username=username, password=password) auth_login(request=request, user=user) except: return render(request, 'templates/pay.html', context={'error': 'Wrong Account Details or amount'}) transaction = Transaction.objects.create(made_by=user, amount=amount) transaction.save() This is just the initiate_payment where the error is coming from. please help i already tried similiar error if any other file is needed let me know . any help is appreciated . -
django - How to create a form inside a detail view
I am creating a online debate app using django. I have used class based list view to create different topics using pk and once i click on the topic it takes me to its details page and once I go to the detail page I need a two text boxes to enter my for point and against point and after entering the point I need to display the point below the textbox. I have create the list of topics but unable to do the textbox to that particular page. Please help me. -
Django max_length character count shows the wrong number of characters
models.py class Tweet(models.Model): content = models.TextField(max_length=1000) ... forms.py ... tweet = forms.CharField( widget=forms.Textarea( label='Tweet', max_length=Tweet._meta.get_field('tweet').max_length) ... views.py class TweetCreate(LoginRequiredMixin, CreateView): login_url = reverse_lazy('home:login') model = Tweet slug_url_kwarg = 'tweet_slug' form_class = TweetForm template_name_suffix = '-create' def form_valid(self, form): self.tweet = form.save(commit=False) self.tweet.author = self.request.user print(form.cleaned_data['tweet']) # Passing case return super(TweetCreate, self).form_valid(form) def form_invalid(self, form): print(form.data['tweet']) # Failing case return super(TweetCreate, self).form_invalid(form) Failing case This is the test text I am using. It has exactly 1000 characters. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta suscipit tellus eget tristique. Etiam sit amet neque ac sem posuere mollis a imperdiet tellus. Nulla facilisi. Nulla pulvinar in nunc eget pellentesque. Integer volutpat, mauris in sollicitudin dictum, velit turpis rhoncus lacus, ac feugiat libero risus id risus. In ac gravida risus. Sed nec enim vel est interdum scelerisque. Integer at fringilla tortor, sit amet porta tortor. Maecenas congue euismod ipsum. Integer efficitur est risus. Quisque id erat tincidunt, convallis justo eget, eleifend lacus. Praesent volutpat tellus et accumsan accumsan. Curabitur sollicitudin, sem eu finibus iaculis, lectus orci suscipit eros, nec faucibus quam metus quis orc. Aliquam erat volutpat. Cras risus ex, venenatis nec risus eu, scelerisque fermentum neque. Praesent in finibus metus. … -
What does API endpoint refers to?
For example, I have a simple model for a bookshop. models.py class Author(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) author = models.ForeignKey(Author, on_delete=models.CASCADE) added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title and the serializers too serializers.py from .models import Author, Book class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ['id', 'name', 'added_by', 'created_by'] class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'title', 'description', 'created_date', 'author', 'added_by'] and I have designed the api views for the crud operation which is not necessary to show here. I have also completed the urls.py for the four crud views. I just want to know what api endpoints actually refers to in this case. -
Get file URL from raw django SQL query
I have two models class Post(models.Model): ... class PostImage(models.Model): post = models.ForeignKey(Post) ... In a ListView I need to query post and one image for it, so I end up writing raw query. What I hit now is that the url fields are simple path strings which django tries to load from my app, instead of the MEDIA_URL which otherwise works if object is loaded via the ORM. Is there a way to convert that path to url in the template using the django sytax ? {{ post.image.url }} -
Formset and Form Wizard, Django
I have created a working first page using Form Wizard, on second page I am trying to use the value from first page which is stored to create formset forms. Is there a tutorial/guidance or documentation which helps? I went through documentation but am unable to figure it out.