Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rails or Django when you know Python well and Rails well but not Ruby nor Django
I know Rails well enough to build apps quickly (and have code I can reuse). But I don't know Ruby well (I realize the oddity). At the same time I do know Python well, having used it for data science. But I don't know much about Django. I want to build an app that is well beyond Django official tutorial difficulty (the polls app), and at the same time use cutting-edge algorithms in ML and NLP (might use tensorflow). So if Rails, I'd need to use micro service or call python script. If you were in my shoes, which framework would you use? -
argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks
I am working with django-tenant-schemas and when I try to use "migrate_schemas" command I encounter an error. I've seen similar questions here but they didn't help at all. I've tried this on two different apps but the result is the same. Does anybody know how to fix this? Traceback (most recent call last): File "C:\DjangoNew\tenancy\manage.py", line 22, in <module> main() File "C:\DjangoNew\tenancy\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 322, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 296, in create_parser self.add_arguments(parser) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\tenant_schemas\management\commands\migrate_schemas.py", line 20, in add_arguments command.add_arguments(parser) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 28, in add_arguments help='Skip system checks.', File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1373, in add_argument return self._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1736, in _add_action self._optionals._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1577, in _add_action action = super(_ArgumentGroup, self)._add_action(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1387, in _add_action self._check_conflict(action) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1526, in _check_conflict conflict_handler(action, confl_optionals) File "C:\Users\asyey\AppData\Local\Programs\Python\Python37\lib\argparse.py", line 1535, in _handle_conflict_error raise ArgumentError(action, message % conflict_string) argparse.ArgumentError: argument --skip-checks: conflicting option string: --skip-checks -
Is there any way to use social auth in Django for multiple user types?
As the title says, is there any way to use social auth in Django for multiple user types? With user types I mean that there will be Students, Doctors and Patients in my platform. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) #TO DO - More attributes I want to let all of them to register and login with their Google Account. I have been looking at internet and allauth-django documentation, but I could´nt find any relevant info for my issue. Thanks in advance! -
Django - 500 error after launch on elastic-beanstalk
Hello I am still pretty green with the whole web deployment thing so bear with me this is only my second deployment. I've run into an issue called "500 Internal Server Error" I checked the aws documentation and all it can give me is error is unknown. The code all ran before I launched using runserver and the server was running before I put the code in so I don't know where the issue could be. I used eb logs to get the following data: ============= i-030b809a2708731e5 ============== /var/log/httpd/error_log [Tue Oct 06 19:47:09.942986 2020] [:error] [pid 4761] [remote 172.31.36.89:152] apps.populate(settings.INSTALLED_APPS) [Tue Oct 06 19:47:09.942991 2020] [:error] [pid 4761] [remote 172.31.36.89:152] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 81, in populate [Tue Oct 06 19:47:09.942994 2020] [:error] [pid 4761] [remote 172.31.36.89:152] raise RuntimeError("populate() isn't reentrant") [Tue Oct 06 19:47:09.943009 2020] [:error] [pid 4761] [remote 172.31.36.89:152] RuntimeError: populate() isn't reentrant[Tue Oct 06 19:47:22.721931 2020] [:error] [pid 4761] [remote 172.31.36.89:152] mod_wsgi (pid=4761): Target WSGI script '/opt/python/current/app/SpaceNerdsLaunch/wsgi.py' cannot be loaded as Python module. [Tue Oct 06 19:47:22.721979 2020] [:error] [pid 4761] [remote 172.31.36.89:152] mod_wsgi (pid=4761): Exception occurred processing WSGI script '/opt/python/current/app/SpaceNerdsLaunch/wsgi.py'. [Tue Oct 06 19:47:22.722087 2020] [:error] [pid 4761] [remote 172.31.36.89:152] Traceback (most recent call last): [Tue Oct … -
CSRF Token error when attempting to post from CURL to an API endpoint I control. How do I write the request?
I have not utilized this part of Django before, but I have an endpoint which is giving me a 403 error and is telling me that my request needs a csrf token. I was trying to figure out how best to get this since I was attempting to set up a bunch of curl requests to handle some simple queries to the endpoint. Likewise, I was thinking to also use POSTman, but I was not sure where documentation is to handle these request. I have seen the cookie csrftoken, but when I was attempting to curl with it, it was still giving me a 403. thought it would looking something like this: curl -d @profilepicturev2.png -b "csrftoken=Ebfn2OlfhSwFjAEQdoQon7wUjbynFoJqrtHMNPla3cy7ZfCMT9cxZ3OQHsbaedam" http://127.0.0.1:8000/api/files/uploader Maybe I am mistaken? -
Rest API schema to retrieve value from database and return
I need to make a Rest API which will take 3 inputs: input_list (list of srings sentences), from_lang (string), to_lang (string) and return list of string after fetching values from databse table. Example: input - {input_list: ['how are you', 'see you later', 'where are you'], from_lang: 'english', to_lang: 'spanish' } output - {['cómo estás', 'nos vemos más tarde', 'Dónde estás']} A service will call this API with list of sentences in any supported language, and in return they will get list of same length with translated sentence if it exist in database or null value if it doesn't exist. How should I proceed? What I have done is, I have created a serializer to handle/validate incoming request in serializers.py: def supported_lang(value): if value not in SUPPORTED_LANGUAGES: print(value) print(SUPPORTED_LANGUAGES) raise serializers.ValidationError('Language not supported') class TranslateSerializer(serializers.Serializer): input_list = serializers.ListField( child=serializers.CharField(allow_blank=False), allow_empty=False ) from_language = serializers.CharField(validators=[supported_lang]) to_language = serializers.CharField(validators=[supported_lang]) And I have defined a simple model for storing translations in model.py: class TranslationModel(models.Model): english = models.CharField(blank=False, max_length=MAX_LENGTH, unique=True) spanish = models.CharField(blank=True, max_length=MAX_LENGTH) italian = models.CharField(blank=True, max_length=MAX_LENGTH) is_active = models.BooleanField(default=True) Then in my views.py I have handled post requests like below class TranslateView(views.APIView): def post(self, request): serializer = TranslateSerializer(data=request.data) serializer.is_valid(raise_exception=True) serialized_data = serializer.validated_data result … -
In Django FileField, how to set file.name that contains also random url?
I am trying to modify the name of an uploaded file to include also some url in it. In my case it's the custom "file_url" variable. However the current result is: , but the expected result should be: http://www.google.com/ Here is my View.py: class CreateImage(CreateAPIView): permission_classes = (IsAuthenticated,) model = models.Image serializer_class = serializers.ImageSerializer def get_serializer(self, container, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs["context"] = self.get_serializer_context() old_filename = self.request.FILES['image'].name if self.request.FILES: if container == 'products': data = self.request.data.copy() product_name = data["product_name"] file_url = f"{settings.MEDIA_DOMAIN}{container}/" new_filename = get_product_new_filename(old_filename, product_name) data['image'].name = file_url + new_filename kwargs["data"] = data return serializer_class(*args, **kwargs) And simple model for reference: class Image(models.Model): image = models.FileField() def __str__(self): return self.image.name Do you have any idea, how to include given url in the filename? The workaround, would be to create additional field, say image_url as CharField, and save it there, but maybe there is a way to not duplicate table inputs. Thanks in advance! -
use django default PasswordResetView and my own view in one template
i want to use django's default password reset view "PasswordResetView" in a template that already has a view that i built on my own, after looking at the tutorials and the questions i found how to use it only on a different template that is made only for the password reset, but i don't want the user to go to a different page just to change his password when he forgets it, i want to make it in a bootstrap modal in the home page here is my home view in my views.py def home(request): user = request.user signin_form = SigninForm() signup_form = SignupForm() if request.method == "POST": if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') if 'signup_form' in request.POST: signup_form = SignupForm(request.POST) if signup_form.is_valid(): signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) context = {'signin_form': signin_form,'signup_form': signup_form} return render(request, 'main/home.html', context) NB: i tried copy pasting the source code of that view (PasswordResetView) from django's source code in my view but i found some errors because … -
Django / Drf "The 'image' attribute has no file associated with it."
I use sorl-thumbnail in my models. While querying the videolessons objects list, some of them tells me an error "The 'image' attribute has no file associated with it." . In the admin field I can see the image field and image. My model is: from sorl.thumbnail import ImageField class Videolesson(models.Model): def upload_location(instance, filename): VideolessonModel = instance.__class__ try: new_id = VideolessonModel.objects.order_by("id").last().id + 1 except: new_id = 1 return "{} {}".format(new_id, filename) # Relations # Attributes - Mandatory user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_( "user"), on_delete=models.CASCADE,) title = models.CharField(max_length=200, verbose_name=_( "title"), help_text=_("Enter the Videolesson title")) slug = models.SlugField(unique=True) image = models.ImageField(null=True,blank=True,upload_to=upload_location,) and my serializer class VideolessonSerializer(serializers.HyperlinkedModelSerializer): user = serializers.StringRelatedField(read_only=True) user_image = serializers.StringRelatedField(source='user.image.url', read_only=True) user_thumbnail = HyperlinkedSorlImageField( '60x60', options={"crop": "center"}, source='user.image', read_only=True ) thumbnail = HyperlinkedSorlImageField( '400x400', options={"crop": "center"}, source='image', read_only=True ) # A larger version of the image, allows writing image = HyperlinkedSorlImageField('1024') class Meta: model = Videolesson fields = [ "slug", "user_thumbnail", "user", "user_image", "thumbnail", "image",] I have tried to create a new videolesson now I have error in that one too. How can I fix this error ? Thanks -
Django Bootstrap modal carousel
Hello I am trying to create simple gallery and one of the feature I would like to add is modal window with carousel in it. For a backend I am using Django framework. And its current state it is partially working. If I click on image, the modal window opens but it show the 1st image on the site even though I click on any other image, it still shows the first image. Second issue is that the controls of the carousel do not work on any side and it keeps showing only 1st image and I am not able to see on any other. Here is the code of the template: <!--Loading images from Django.--> <div class="gallery" id="gallery" data-toggle="modal" data-target="#exampleModal"> <!-- Grid column --> {% for picture in images %} <div class="mb-3 pics animation all 1 filter {{ picture.gallery_cat.category }}" id="galleryImage"> <img class="img-fluid" src="{{ picture.image.url }}" data-target="#carouselExample" data-slide-to="{{ forloop.counter }}"> </div> {% endfor %} </div> <!-- Modal window --> <div class="modal fade " id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <!-- Indicators --> <div class="carousel slide" id="MyCarousel"> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for picture … -
Set a Model default value relative to another field
I'm building an auctions site and I want the highest_bid on a listing to be >= start_price and in turn set the bid_input to raise a ValidationError if a user tries to enter a bid_input < highest_bid. I don't want the user to have to enter a highest_bid when creating the form so I've set it to hidden input but want to figure out how to capture this value. I think I may have worked out how to validate bid_input using clean(self) but I am unsure how to set the highest_bid default value to greater or equal to the start_price. Should this be done on the model or on the form on saving? I'm quite confused on how to go about this really. models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) highest_bid = models.DecimalField(max_digits=9, decimal_places=2, default=None) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})" class … -
How does the "action" attribute work in a Django form?
I have learned about forms in Django(from scratch and using ModelForm). ModelForm is super helpful! I can code the whole thing, but one thing that got me confused is the "action=" attribute in a form tag on a template. This is what I have, for example: models.py : from django.db import models class Drinks(models.Model): size = models.IntegerField() color = models.CharField(max_length=10) brand = models.CharField(max_length=100) suggestion = models.CharField(max_length=100) forms.py : from django import forms from django.forms import ModelForm from django.forms import Textarea from .models import Drinks class DrinkForm(ModelForm): class Meta: model = Drinks fields = '__all__' widgets = {'suggestion': Textarea(attrs={'cols': 80, 'rows': 30})} views.py : from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Drinks from .forms import DrinkForm def thanks_3(request): return render(request, 'robots/drink_thanks.html') def get_drink_info(request): if request.method == 'POST': form = DrinkForm(request.POST) if form.is_valid(): s = form.cleaned_data['size'] c = form.cleaned_data['color'] br = form.cleaned_data['brand'] sgg = form.cleaned_data['suggestion'] new_instance = Drinks(size=s, color=c, brand=br, suggestion=sgg) new_instance.save() return HttpResponseRedirect('/drink-thanks-message/') else: form = DrinkForm() context = {'form': form} return render(request, 'robots/drinks_form.html', context) urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('drinks/', views.get_drink_info, name='drinks-007'), path('drink-thanks-message/', views.thanks_3, name='tnx3'), ] base.html : <!DOCTYPE html> {% load static %} <html … -
form validation errors not shown when condition is not met in Django template
I wrote below custom form validation to check the length of the message and if it is less than 8 characters it throws an error: class ContactForm(forms.ModelForm): def clean(self): cleaned_data = super().clean() message = cleaned_data.get("message") if len(message) < 8: raise forms.ValidationError( "Message can't be less than 8 characters.") class Meta: model = Contact fields = "__all__" and this is the view I use to handle form def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Message sent successfully.') else: messages.error( request, 'Please fill all the blanks with valid data.') return render(request, 'contact/contact.html', context) and to show errors in contact.html template I used this - {% if form.errors %} <ul class="field-errors" id="form_errors"> {% for field in form %} {% for error in field.errors %} <li> {{ error|escape }} </li> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div> {{ error|escape }} </div> {% endfor %} </ul> {% endif %} when testing it in template I didn't get this Message can't be less than 8 characters. error even thought I passed it in template. I tried passing form:form as context in contact.html template. It didn't work either. This is the model. class Contact(models.Model): name … -
Retrurning list from webscrape Django
This might be a noobie question but im trying to return a list of cars for this script: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup from pprint import pprint def carscrape(): # Script to extract the data from the website my_url = 'https://www.finn.no/car/used/search.html?orgId=9117269&page=1' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") carResults = page_soup.findAll("article", {"class": "ads__unit"}) for car in carResults: title = car.a.text img_url = car.img["src"] link = car.h2.a["href"] data = car.find("div", {"class": "ads__unit__content__keys"}) dataResult = data.findAll("div") model_year = int(''.join(list(filter(str.isdigit,dataResult[0].text)))) mileage = int(''.join(list(filter(str.isdigit,dataResult[1].text)))) try: price = int(''.join(list(filter(str.isdigit, dataResult[2].text)))) except: price = 0 # end of script to get the data #What should i do here? yield { "title" : title, "img_url" : img_url, "link" : link, "model_year" : model_year, "mileage" : mileage, "price" : price, } I was not sure if i should use the yield generator. But basically im trying to save all the webscraped data to a list then save every item in the list in my django database. If anyone could give me some pointers that would be great. Ive researched online but the examples i found did not fit this script. Thanks for any help in advance. -
Is there a way to know screen size in django template?
I am new in django, And I want a way to show diffrent things based on device width, I am making a movie website and the home page shows ten movies but I want the value to decrease if the screen size is smaller. Html Code: {% for movie in movieByView|slice:"10" %} <div> <h2>{{movie.name|truncatechars:25}}</h2> <h2>{{movie.rating}}</h2> <img src="home/static/img/{{ movie.moviePoster }}"/> </div> {% endfor %} I want to change the slice number to 12 if the screen size was bigger. How can I do that? is there a way? if I can do this in any other language please say. I thought of two ways to do it I dont know if its possible.1. showing 20 movies and using javascript to remove the unwanted. 2. passing variables from javascript to django by json and post request.but neither of the two is that effecient. -
Can we just use django server for deploying django app on linux server?
I am a complete beginner in deployment related stuff and haven't done any deployment yet. Recently i got a work where i had to deploy a django app on linux server but while searchin on internet their are very few resources that teaches you how to deploy django app on linux server. And all the tutorials are setting up with apache and mod wysgi . My question is can't we just use the django server to deploy the django app on linux server. If this could be possible then i just have to: install python on server. install virtual env. edit settings.py by changing allowed host , static root, run python manage.py collectstatic python manag.py runserver 0.0.0.0:8000 let me know if that is possible and if not then what and where i am getting wrong? Also if you can provide me some step by step tutorial to deploy django app on sever then it would be much of help. Any resource or reference will be helpful. Thanks in advance. -
Django queryset.field.unmask(request)
"facility" is a queryset in which "full_name" is a field. "request" is the request object passed from the view class. what does the following code achieve? cp_name = facility.full_name.unmask(request) if facility else None -
Django can only handle ASGI/HTTP connections, not websocket
Hello I am getting a error. Before coming here, I tried many different ways and looked at the topics that were opened here before. But whatever I do, it keeps giving me errors. I tried daphne and uvicorn but the result is the same, it opens in local environment but it does not work on the server and gives this error: Django can only handle ASGI / HTTP connections, not websocket My Codes: Js Code: <script> function connectSocket() { var ws = new WebSocket('ws://' + window.location.host + '/ws/notification/{{request.user.id}}/') ws.onopen = function(event){ console.log('opened', event); } //If there is a long onmessage codes here, I removed the code, no syntax error ws.onclose = function(e) { console.error('Chat socket closed unexpectedly; reconnecting'); setTimeout(connectSocket, 1000); }; ws.onerror = function(event){ console.log('error', event); } // window.setInterval(function(){ // loadNotifications(); // }, 1000); } connectSocket(); </script> Settings.py [/JSR] [CODE] CHANNEL_LAYERS = { "default": { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [("redis", 6379)], }, }, } ASGI_APPLICATION = "thesite.routing.application" asgi import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'thesite.settings') django.setup() application = get_default_application() Nginx: server { listen 80; server_name **.net www.**.net; #** = site name root /home/ftpuser/project; location /static/ { alias /home/ftpuser/project/site/static/; } location /media/ { } location / { … -
Could not parse the remainder: '{{comment.post}}=={{blog.post}}' from '{{comment.post}}=={{blog.post}}'
I am making a blog website and I have to add comments to my post for that I have to check which post the comment is associated with and I am writing this line {% if {{comment.post}}=={{blog.post}} %} I know this line won't work because {%%} and {{}} cannot be used in the same line so does anyone has a solution for this. -
Attribute Error: 'tuple' object has no attribute 'values'
I have a basic API to reset the password, however, it seems to be throwing this error, despite "values", not appearing in my code altogether: views.py class PasswordResetNewPasswordAPIView(GenericAPIView): serializer_class = SetNewPasswordSerializer def patch(self, request): user = request.data serializer = SetNewPasswordSerializer(data=user) serializer.is_valid(raise_exception=True) return Response({ "message": "password reset"}, status=status.HTTP_200_OK ) serializers.py class SetNewPasswordSerializer(serializers.Serializer): password = serializers.CharField(max_length=50, write_only =True) token = serializers.CharField(write_only =True) uidb64 = serializers.CharField(max_length = 255, write_only =True) fields = ("password", "token", "uidb64",) def validate(self, attrs): try: password = attrs.get("password", "") token = attrs.get("token", "") uidb64 = attrs.get("uidb64", "") print(uidb64) id = force_str(urlsafe_base64_decode(uidb64)) print(id) user = Author.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): raise AuthenticationFailed("Invalid Reset Parameter", 401) user.set_password(password) user.save() return user except Exception: raise AuthenticationFailed("Invalid Reset Parameter", 401) return super().validate(attrs) urls.py ... path('password-reset-setup/', PasswordResetNewPasswordAPIView.as_view(),name="password-reset-setup"), What could be the possible error? And how to I get around it? The traceback is: Traceback (most recent call last): File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/core/handlers/base.py", line 202, in _get_response response = response.render() File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "/home/pratyush/Desktop/NewsSite/newsite/lib/python3.8/site-packages/rest_framework/renderers.py", line 657, in get_context raw_data_patch_form = … -
Django For While Loops and counters when returning data
I am pulling some crypto data into my web app, and placing it into bootstrap cards. My issue is with the number of cards now populating my site. So I thought, no sweat. I'll just initialize a counter at 0 and throw a while loop in there until around 9 or 10. So far no bueno, the code below is the functioning version where it just unloads unlimited crypto cards. I've tried ranges, and If anyone has an idea how I can accomplish this, it'd be greatly appreciated. I don't think it's difficult, just not making the connection. I've even found cases now where you need to register the while loop just to use it in django ? @register.tag('while') had no idea {% for x in api.Data %} <div class="col-sm"> <div class="card-deck"> <div class="card" style="width: 18rem"> <img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}"> <div class="card-body"> <h5 class="card-title">{{ x.title }}</h5> <p class="card-text">{{ x.body }}</p> <a href="{{ x.url}}" class="btn btn-primary">Learn more</a> </div> </div> </div> <br /> </div> {% endfor %} -
Django populating table in template with two different data sets
I have problem. I need to populate one table with two different sets of data, one is queryset and the other is list. Is there any way to populate table with two sets of data using one {% for %} statement? Something like {% for categories, expenses in categoriesList and expensesList %}. -
Django query to extract values when there is an intermediate table
My database has the following structure. Table1: Name unique_name name_class Table2: Node tid rank path depth Table3: Synonym node (foreignkey to Node) name (foreignkey to Name) I want to extract tid and name based on a condition. I know I can do this names = Synonym.objects.filter(node__path__startswith=path, node__depth__gte=depth, name__name_class="ABC").order_by('node__path') for n in names: print(n.node.tid, n.name.unique_name) How can I make a query to extract tid and name in a single step avoiding the use of for loop ? -
how can i add a JavaScript object to be submitted with my Django form?
I am building a blog with Django and using editorjs as my block editor, the data gets returned as a JSON object, how can I include this object with my Django form? it can be submitted as a string since I am parsing it anyway, I know using an API would solve my issue but I was running into trouble trying to add the images through an API, besides I would like to make use of the built-in class views any help would be greatly appreciated, thanks in advance -
Django CreateView - if field is empty, don't create an object and instead redirect to different view. How do I do this?
I have a media model and a product model. When a user creates a product they first upload a picture and then after this, they're forwarded to the product detail page where they can edit the products attributes. This works fine, however if the user doesn't upload a picture I'd like the program to skip creating a media object and just go straight to the product detail page. I've tried returning a reverse() function from form_valid() but this doesn't work so I'm wondering if anyone knows why this is and how I can fix this? My code currently: class ProductMediaCreate(generic.CreateView): model = ProductMedia fields = ('media',) template_name = 'media/media_create.html' def form_valid(self, form): product_obj = Product.objects.create() if not form.instance.media: return reverse('product_detail', kwargs={'pk': product_obj.pk}) form.instance.product = product_obj return super().form_valid(form) def get_success_url(self): return reverse('product_detail', kwargs={'pk': self.product.pk}) Thanks in advance for any help! - GoingRoundInCircles