Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what approch should i follow to predict gift on the basis of data given by user. I using Django framework
http://localhost:8888/notebooks/KSproject/sk.ipynb link to the project ,here i am only getting one output for any random input -
New model objects disappear after five minutes in Django
whenever I create a new object in one of my models, they exist for around five minutes and then disappear. I checked in both my admin view and the queryset in the shell and they just disappear. I don't understand what's happening so if anyone has any idea, that'd be very useful. These are the models: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character, blank=True, related_name='movies') def __str__(self): return self.title These are the views: class CharacterCreateAPI(generics.CreateAPIView): queryset = Character.objects.all() serializer_class = CharacterSerializer permission_classes = (AllowAny,) class MovieCreateAPI(generics.CreateAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer permission_classes = (AllowAny,) These are the serializers: class CharacterSerializer(serializers.ModelSerializer): movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all()) class Meta: model = Character fields = ['name', 'age', 'image', 'movies', 'story'] extra_kwargs = {'image': {'required': False, 'allow_null': True}} class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('title', 'image', 'rating', 'characters') extra_kwargs = {'image': {'required': False, 'allow_null': True}} def create(self, validated_data): characters = validated_data.pop('characters') movie = Movie.objects.create(**validated_data) if characters: movie.set(characters) movie.save() return movie -
getting a list in response of serializer
I am trying to make something like this in my serializer response - [ { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "id":1 , "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "id":2 , "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, } ] Instead I am getting this - [ { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "c5f408bd-a07f-4ee5-b7a9-b2dee8f67634" }, { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c" } ] How can I make like this .. here is my models.py class Supports(models.Model): user = models.ForeignKey(HNUsers, on_delete=models.CASCADE, related_name='supporting_user') supporting = models.ForeignKey(HNUsers, on_delete=models.DO_NOTHING, related_name="supportings") is_support = models.BooleanField(blank=True, null=True, default=False) class Meta: verbose_name_plural = "Supports" here is my Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = HNUsers fields = ( 'hnid', 'username', 'profile_img', 'full_name', ) class SupportSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) # supporting = SupportingUserSerializer(read_only=True, many=False) class Meta: model = Supports fields = ( 'user', 'supporting', ) here is my views.py @api_view(['GET', 'POST']) @permission_classes((permissions.AllowAny,)) @parser_classes([FormParser, MultiPartParser]) def create_support(request): data = request.data print(data) if request.method == … -
'Movie' object is not iterable when making a post request
I keep getting the error ''Movie' object is not iterable' when I make a post request but the instance gets created anyway so I was wondering how I can get rid of it. This is the view that throws the error when I try to create a character: class CharacterCreateAPI(generics.CreateAPIView): queryset = Character.objects.all() serializer_class = CharacterSerializer permission_classes = (AllowAny,) These are the models: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character, blank=True, related_name='movies') def __str__(self): return self.title These are the serializers: class CharacterSerializer(serializers.ModelSerializer): movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all()) class Meta: model = Character fields = ['name', 'age', 'image', 'movies', 'story'] extra_kwargs = {'image': {'required': False, 'allow_null': True}} class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('title', 'image', 'rating', 'characters') extra_kwargs = {'image': {'required': False, 'allow_null': True}} def create(self, validated_data): characters = validated_data.pop('characters') movie = Movie.objects.create(**validated_data) if characters: movie.set(characters) movie.save() return movie -
How To Store exec and render it to a template in Django?
I am creating a website where I can store my code. I also want a feature where I can run the code! So I used exec, but I can't render it to a html page. It justs prints the output to the console. This is my views.py def SeeCode(request, code_pk): code = Code.objects.get(pk=code_pk) execute = exec(code) context = { "code": code, "execute": execute } return render(request, "base/see_code.html", context) And this is my html page: {% block content %} <h1>{{ code.title }}</h1> <br><br> <div class="row"> <div class="col md-7" id="col1"> <pre><code class="python">{{code.code}}</code></pre> <br> <a class="run">Execute</a> </div> <div class="col md-4" id="col2"> <h6>OUTPUT</h6> <p>{{ execute }}</p> </div> </div> {% endblock %} Can you please tell me how to fix this? Or any alternative ways to run the python code and render it to my html page? -
Django cannot connect to postgresql docker container
I have a postgres db running in a docker container: my docker-compose: version: "3" services: db: image: postgres:13.1-alpine environment: - POSTGRES_DB=mydb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test ports: - "5432:5432" volumes: - ./postgres_data:/var/lib/postgresql/data/ Django running on the host machine cannot connect to it. django's settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST' : "localhost", 'NAME' : "mydb", 'USER' : "postgres", 'PASSWORD' : "test", 'PORT':5432, } } Exception: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432" Database is certainly avaliable on port 5432(I can connect to it with dbeaver database client on localhost:5432). What could be the cause of the problem? -
Cookie issues with Django runing on IOS
I have a web app made using Django and uses cookies for maintance sesson because y based on chamilo LMS (it use cookies). The web app run ok in window and android devices but not in IOS devices. How is the manage for cookies in IOS? Currently I tried creating the cookie with secure check and samesite as None but the information is losing whe redirect between home and the rest of the site -
How to copy an existing django object to another table for temporary storage?
Basically I have an inventory system and a POS, cart and checkout. Here are my models: class OrderItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) qty = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) def __str__(self): return f"{self.item.upc} || ${self.item.sug_ind_retail} || ({self.item.item_name}) X {self.qty} " def get_total_item_price(self): return self.qty * self.item.sug_ind_retail def get_item_sales_tax(self): return self.get_total_item_price() * .095 def get_total(self): return self.get_item_sales_tax() + (self.item.sug_ind_retail * self.qty) class TempCartItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) qty = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) def __str__(self): return f"{self.item.upc} || ${self.item.sug_ind_retail} || ({self.item.item_name}) X {self.qty} " def get_total_item_price(self): return self.qty * self.item.sug_ind_retail def get_item_sales_tax(self): return self.get_total_item_price() * .095 def get_total(self): return self.get_item_sales_tax() + (self.item.sug_ind_retail * self.qty) Basically I want to save the TempCartItem's into the OrderItem model, this way I can delete all the items in the cart but save the OrderItem's when we check out a customer. Here is my view: @login_required def order_item_view(request): temp_order_item_form = TempCartItemForm(request.POST or None) if request.POST.get("submit"): temp_order_item_form.save(commit=False) form_upc = temp_order_item_form.cleaned_data.get('upc') if form_upc == '': messages.warning(request, "UPC is required to add to cart.") form_qty = temp_order_item_form.cleaned_data.get('qty') global customer customer = temp_order_item_form.cleaned_data.get('customer') # get item or create new one if … -
How to make a form save to the database every time it is edited in Django?
So I am trying to replicate the Google Docs functionality wherein every time you edit, the document will be saved. Will I be putting an onchange function on every input in the form then sending the data through ajax? How should I approach this or is this even feasible? Note: I am just asking for some sort of pseudocode or simply the flow-chart of how I should do things. -
Filter based on two tables Django
I have two models with a through table: class Subscriber(models.Model): first = models.CharField(max_length=30) last = models.CharField(max_length=30) email_confirmed = models.BooleanField(default=False) class Newsletter(models.Model): title = models.CharField(max_length=100, default="Tiffany's Dynamic Digest") body = models.TextField(null=False, blank=False) subscribers = models.ManyToManyField('Subscriber', through='NewsletterEngagement') class NewsletterEngagement(models.Model): subscriber = models.ForeignKey(Subscriber, on_delete=models.CASCADE) newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE) I need to search for: All subscribers where email_confirmed=True AND who have not received a newsletter. Thank you in advance. -
How to host two domains for one Django project in WSGI
I have two active domains which i want them to point to one project created using Django. i tried searching on other references but could not find satisfactory solution. Both sites should open same page. index.html residing in the project. Below is my current config file. I am using Apache server and Linux server. I am using SSL for one site as seen below but will not be using for other. <VirtualHost *:80> ServerAdmin admin@example.com ServerName (www.example.com) ServerAlias http://example.com DocumentRoot /home/tguser/tgportal/ ErrorLog /home/tguser/tgportal/core/err.log CustomLog /home/tguser/tgportal/core/access.log combined Alias /static/admin /home/tguser/tgportal/core/staticfiles/admin Alias /.well-known /home/tguser/tgportal/core/.well-known <Directory /home/tguser/tgportal/core/.well-known> Require all granted </Directory> Alias /media /home/tguser/tgportal/core/media <Directory /home/tguser/tgportal/core/media> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> Alias /static /home/tguser/tgportal/core/staticfiles <Directory /home/tguser/tgportal/core/staticfiles> Require all granted </Directory> <Directory /home/tguser/tgportal/core/core> <Files wsgi.py> # Require expr %{HTTP_HOST} == "example1.com" Require all granted </Files> </Directory> WSGIPassAuthorization On RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] WSGIScriptAlias / /home/tguser/tgportal/core/core/wsgi.py WSGIDaemonProcess tgproject python-path=/home/tguser/tgportal/core/ python-home=/home/tguser/tgportal/env WSGIProcessGroup tgproject </VirtualHost> <VirtualHost *:443> ServerAdmin admin@example1.com ServerName example1.com ServerAlias https://example1.com DocumentRoot /home/tguser/tgportal/ ErrorLog /home/tguser/tgportal/core/err.log CustomLog /home/tguser/tgportal/core/access.log combined SSLEngine on SSLCertificateFile /home/tguser/tgportal/core/keys/a4d9949d130ff93.crt SSLCertificateKeyFile /home/tguser/tgportal/core/keys/generated-private-key.txt SSLCertificateChainFile /home/tguser/tgportal/core/keys/gd_bundle-g2-g1.crt Alias /.well-known /home/tguser/tgportal/core/.well-known <Directory /home/tguser/tgportal/core/.well-known> Require all granted </Directory> Alias /media /home/tguser/tgportal/core/media <Directory /home/tguser/tgportal/core/media> Options Indexes FollowSymLinks AllowOverride All Require … -
Custom method create in ModelViewset Django Rest Framework
Hello guys and girls, Just having a little issue with Django Rest Framework : let's say I have a Book class : models.py class Books(models.Model): title = models.Charfield(max_length = 50, blank=False) serializers.py class BooksSerializer (serializers.ModelSerializer) class Meta: model = Books fields = ['id', 'title'] And now I want to allow the create method only until I have 30 books in database. This is the kind of code I have until now but it isn't working so far, how would you recommend me to proceed ? I can override the create method from the ModelViewSet class right ? views.py class BooksViewset(viewsets.ModelViewSet): queryset = Books.objects.all() serializer_class = BooksSerializer def create(self, serializer): number_of_books = queryset.count() if number of book < 30: serializer.save() else: response = {'message': 'You can't create more than 30 values'} return Response(response, status=status.HTTP_400_BAD_REQUEST) Thank you in advance for your help -
Applicatıon error on deployed django rest framework app on heroku
I'm trying to deploy my django rest framework app on Heroku. I read many other similar questions but I'm confused. My app structure is not right or I'm missing something. This is my structure on git: .gitignore requirements.txt src | --authorization --core --static --staticfiles --Procfile --manage.py --mainfolder | ---asgi.py ---settings.py ---urls.py ---wsgi.py authorization and core are apps under my django project. there wasn't static or staticfiles before heroku deploy. But it automatically created staticfiles. Then I also created static and followed instructions to make it work via changes in settings.py. It'd be awesome if someone help me figure out my problem on heroku and why it doesn't work. This is Procfile: web: gunicorn mainfolder.wsgi web: gunicorn mainfolder:app When I run app with this command my app works fine and run locally: gunicorn mainfolder.wsgi:application But I couldn't solve the error in deployed app. With heroku logs --tail I receive errors starts like below: heroku[router]: at=error code=H14 desc="No web processes running" When I run this heroku ps:scale web=1 --app mainfolder I get this: Scaling dynos... ! ▸ Couldn't find that process type (web). And finally when I try to run heroku locally under src folder with this command src % heroku local … -
RNCryptor - encrypted string cannot be validated in django backend
I am using RNCrytor to encrypt my JWT, however, the encrypted string cannot be validated from the backed, Django. I am using the SwiftJWT library to generate the jwt. Here is my Swift code let header = Header(kid: "KeyID1") var authHeader: String? = nil let clntConfig = ClientConfig() if clntConfig.isValid() { let clientID = clntConfig.getClientsID() let deviceID = clntConfig.getDevicesID() let appSecret = clntConfig.getAppsSecret() let deviceSecret = clntConfig.getDeviceSecrets() let myClaims = AuthClientClaims(clientKey: clientID,deviceUid: deviceID,deviceSecret: deviceSecret) do { print("****\(deviceSecret)***") let jwtSecret = passToPhrase(password: deviceSecret) print("****\(jwtSecret)***") let base64encodedSecretString = jwtSecret.data(using: .utf8)?.base64EncodedString() print("****\(base64encodedSecretString!)***") //let jwtSigner = JWTSigner.rs var myJWT = JWT(header: header, claims: myClaims) let privateKey: Data = base64encodedSecretString!.data(using: .utf8)! let jwtSigner = JWTSigner.hs256(key: privateKey) let signedJWT = try myJWT.sign(using: jwtSigner) print("****\(signedJWT)****") let ciphertext = RNCryptor.encrypt(data: signedJWT.data(using: .utf8)!, withPassword: appSecret) authHeader = ciphertext.base64EncodedString() } Here is the backend code def do_decrypt(en_data, secret): en_data = en_data + '===============' encrypted_data = base64.b64decode(en_data) decrypted_data = rncryptor.decrypt(encrypted_data, secret) return decrypted_data -
Can i pass form or other parametr, to the template, without doing it in view?
I have register form, and i need to display it on almost every template (on base.html), so can i do it without passing it in every view? -
How to customize message error for TokenAuthentication in Django Rest Framework
Right now I only get a brief message : [detail => Invalid token], how can I change it? I come more from a Java environment and I'm struggling with a whole new world now. I have found the custom exception handling in the official documentation but still unable to customize it. -
Django counting ForeignKeyField
I want to count from my brandListVeiw view how many assets I have of a certain brand models.py class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model = models.ForeignKey("asset_app.Model", on_delete=models.SET_NULL, blank=True, null=True) # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) name = models.CharField(max_length=30) mac_address = models.CharField(max_length=30, null=True, blank=True) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) notes = models.TextField(max_length=448, null=True, blank=True) ip = models.CharField(max_length=90, null=True, blank=True) class Meta: pass def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_asset_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_asset_update", args=(self.pk,)) class Brand(models.Model): name = models.CharField(max_length=30) notes = models.TextField(max_length=448, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False) class Meta: ordering = ["name"] def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_brand_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_brand_update", args=(self.pk,)) class Model(models.Model): # Relationships asset_type = models.ForeignKey("asset_app.Asset_type", on_delete=models.SET_NULL, blank=True, null=True) brand = models.ForeignKey("asset_app.Brand", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) notes = models.TextField(max_length=448, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: pass def __str__(self): return str(self.name) + " :: " + str(self.brand.name) + " :: " + self.asset_type.name def get_absolute_url(self): return reverse("asset_app_model_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_model_update", args=(self.pk,)) views.py class BrandListView(generic.ListView): model = … -
How to create/add multiple groups in single django channels view
Hello guys I am currently building real time Django web application . And i am in dilemma. How do i create or add different group or view in single view. My currently working solution is : class StatusConsumer(AsyncWebsocketConsumer): async def connect(self): self.me = self.scope.get('user') if not self.me.is_authenticated: await self.close() self.room_name = "online_status" await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.channel_layer.group_add( f"{self.me}-notify", self.channel_name ) await self.accept() this view has two groups one is "online_status" and other a unique group . I did create two group using await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.channel_layer.group_add( f"{self.me}-notify", self.channel_name ) This is working fine i believe there are more good ways to do this. -
How to include Django static URL for digital ocean spaces using JavaScript?
I have a django application storing static images on digital ocean spaces. I can easily display these static images in my template by doing:<img>{% static 'images/my_image.png' %}</img> If I inspect the HTML page after this loads, I will see something like: https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXX%3D&Expires=1621600823 But now I want to have this image change dynamically. So I thought I would use javascript to do this like: document.getElementById(id+"dynamicImage").src = "{% static 'images/my_image_2.png' %}"; Which almost works, but the image does not load. And the reason for this is after inspecting the src that the javascript supplied: https://nyc3.digitaloceanspaces.com/nameofmyspace/nameofmyspace-space-static_DEV/images/my_image.png?AWSAccessKeyId=XXXXXXXXXXXXXX&amp;Signature=XXXXXXXXXXXXXXXXXX%3D&amp;Expires=1621600823 You can see wherever there was an & it appended amp; to it. What is the correct way to do this? I can think of 2 ways to correct this, but they seem hacky. I could hard code the URL's into the javascript, which will be a nightmare later, and exposes the API key. I could do <img id = 'my_image' hidden >{% static 'images/my_image.png' %}</img> for all the links I plan on using, then access this URL in the javascript using let URL = document.getElementById("my_image").innerHTML;. This will be less of an updating nightmare, but will still expose the API key now that I think about it, … -
Is it possible to make nested queries in the Django ORM?
Is it possible to make a "nested query" (not sure of the correct term) in the Django ORM. For exampel in SQL: SELECT SUM("tbl1"."views") FROM ( SELECT DISTINCT "my_django_model" FROM INNER JOIN ... INNER JOIN ... ) AS tbl1 GROUP BY "tbl1"."date" I've tried SubQuery but that adds a Query in the SELECT fields, which is not the same thing. Why do I need this? I'm using Sum with a number of ForeignKeys and ManyToManyFields which i filter on. Django then joins all these tables to be able to filter. And that will cause duplicates. And no, Sum('views', distinct=True') does not work, because it is distinct on the actual value of 'views' which is not unique. I've tried a custom query in PGAdmin like the first one above. Then It works perfect. But I prefer to use the ORM and not Raw SQL when possible. Any suggestions welcome. -
Django Register Form redirecting to same url
i am new to django i have created a user registration form but when i click on submit it does nothing and just goes to the same page i am not under standing what i did wrong here views.py: class RegisterPage(FormView): template_name = "main/register.html" form_class = RegisterForm success_url = reverse_lazy('blog_list') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterPage, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect("blog_list") return super(RegisterPage, self).get(*args, **kwargs) forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): bio = forms.CharField(max_length=400, empty_value="Max Length 400") image = forms.ImageField() class Meta: model = User fields = ["username", "image", "password1", "password2", "bio"] register.html: {% extends "main/main.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <div class="form"> <h1>Register</h1> <form method="post"> {% csrf_token %} <label>{{form.username.label}}</label> {{form.username}} <br> <label>{{form.password1.label}}</label> {{form.password1}} <br> <label>{{form.password2.label}}</label> {{form.password2}} <br> <label>{{form.image.label}}</label> {{form.image}} <br> <label>{{form.bio.label}}</label> {{form.bio}} <br> <input style="margin-top: 10px" class="button" type="submit" value="Register"/> </form> <p>Already Have An Account <a href="{% url 'login' %}" class="button">Login</a></p> </div> {% endblock content %} in the views.py i have also tried form_class = UserCreationForm the built in django creation form but still the same result so what is wrong -
How to Show Code Properly In HTML with Django?
I making a website where I can store my python code in. I want the spaces,line breaks,indentations to show correctly on the HTML side of the page, but they are not working properly. I used the <pre> tag, but I gives some sort of space on the first line. This is what I get when i put the <pre> tags. : I want the first line to be vertically aligned to the if-else statement. This is my html code: {% extends 'base/base.html' %} {% block head %} <title>CodeBase | {{ code.title }}</title> {% endblock %} {% block content %} <h1>{{ code.title }}</h1> <br> <pre> {{ code.code }} </pre> {% endblock %} This is my views.py def SeeCode(request, code_pk): code = Code.objects.get(pk=code_pk) # first_line = code.code.split('\n')[0] context = { "code": code, # "first_line": first_line } return render(request, "base/see_code.html", context) Thank you! -
How can I return an nested data in a get request?
Looking for help i got stuck at a point where I need to return a nested content in response to a GET request but getting error : django.core.exceptions.FieldError: Cannot resolve keyword 'order' into field. Choices are: amount, created_at, datetime, direction, id, is_active, orders, orders_id, payment_mode_code, reference_identifier, settlement_status, updated_at views.py @api_view(['GET']) def return_order_details(request,id): if request.method=='GET': order = get_object_or_404(Orders,id=id) id=order.id collection_payments = get_object_or_404(Payments,order=order,direction='Collection') content = { 'orders': { "id":id, "purpose_code":order.purpose_code, "amount":order.amount, 'collection_payments':{ "id":collection_payments.id, "amount":collection_payments.amount, "datetime":collection_payments.datetime, } } } return Response(json.dumps(content), status=status.HTTP_200_OK) -
How to count inventory stock in django grup by product
Can anyone help me? I'm trying to get something like this | book.name| book.author | book.release_year | inventory.filter(available=True).count()| |:-------- |------------: | ------------: | --------------------------------------: | | book1 | Author1 aut2... | 2021 | 5 | | book2 | Author3 aut5... | 1986 | 7 | I have a model class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) biography = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='authors', blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name class Book(models.Model): CHOICE_CATEGORY = ( ) name = models.CharField(max_length=250, unique=True) author = models.ManyToManyField(Author) category = models.IntegerField( choices=CHOICE_CATEGORY, blank=True, null=True) release_year = models.CharField(max_length=4) def __str__(self): return self.name class Inventory(models.Model): book = models.ForeignKey( Book, related_name='book', on_delete=models.CASCADE) inventory_number = models.CharField(max_length=50, unique=True) available = models.BooleanField(default=True) def __str__(self): return self.book.name Problem is with authors, if i have more than one than i must get a list of authors With this code i get table but is grouped by authors individually def book_list(request): books = Inventory.objects.filter(available=True).values( 'book__name', 'book__id', 'book__release_year', 'book__author').annotate(total=Count('book')) print(books) context = {'books': books, } return render(request, 'book_list.html', context) if i remove authors from .values('book__author') i can't display author in template. Where I'm wrong? -
Django-channels can;'e connect to ws:mysite
I have some problems with django-channels,while connecting to wss://mysite.com server return this error.error with wss Here is my asgi.py settings,my template , supervisor settings, nginx settings Thanks for help!