Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List of correct urls not displayed in browser when in django debug mode
Normally in debug modewith django, if you type a bad url the browser displays an error message with the list of available urls. like it : Request Method: GET Request URL: http://127.0.0.1:8000/blorp Using the URLconf defined in bricole.urls, Django tried these URL patterns, in this order: admin/ accounts/ [name='home'] accounts/ simple/ (etc...) but in one of my projects, by typing a bad url I have the following result: Request Method: GET Request URL: <a href="http://127.0.0.1:8000/phot" target="_blank">http://127.0.0.1:8000/phot</a> Raised by: django.views.static.serve “C:\Users\Lou\PycharmProjects\photoglide\phot” does not exist and it does not display the list of available urls. in debug the list of urls is not displayed in browser I am with venv (django 3.1.2 and python 3.8 with pycharm) I compared the .py settings with that of a project for which the list of available urls is correctly displayed in the event of a url error and the only difference seems to be: the project where the url debug works : STATIC_URL = '/static/' STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] ... and where the list of urls is displayed (the project where the url debug works fine): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] It seems … -
Template Issue of Views.py
i am new to django.So i am trying to add a html template to the views.py but it is showing an error, it would be great if you would help me. The Error: TemplateDoesNotExist at / platform/home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: platform/home.html views.py: from django.shortcuts import render def home(request): return render(request, 'platform/home.html') urls.py: from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings from Platform import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='Home'), ] settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My HTML template that i am trying to add: <h1>This is my project</h1> -
Django complicated annotation/aggregation
Using Django 3.1 and Postgres, I'm trying to flatten some rows and I'm not exactly sure how to do it without raw sql. Let's say I have the following data in the table: | id | count | location_id | reading_id | |----|-------|-------------|------------| | 1 | 0 | 6 | 4382 | | 2 | 3 | 5 | 4382 | | 3 | 7 | 4 | 4382 | | 4 | 1 | 6 | 4383 | | 5 | 5 | 5 | 4383 | | 6 | 4 | 3 | 4383 | I want the output to be | location_3_count | location_4_count | location_5_count | location_6_count | reading_id | |------------------|------------------|------------------|------------------|------------| | NONE | 7 | 3 | 0 | 4382 | | 4 | NONE | 5 | 1 | 4383 | This is a simplified version, eachid has a Model with a name, etc. For each reading_id there are 0 to many location_ids, so it's a bit of a hassle. Anybody have any ideas? -
Using uwsgi.ini file in Django application
I am running a django app on a remote server. When I ssh into the remote server and try accessing the uwsgi-master logs I get a permission denied error. When I run the log access command with sudo I can access the log. This behavior is due to the default configuration of the uwsgi that I want to change to allow other users to read the logs. Based on https://serverfault.com/questions/602128/python-uwsgi-logs-have-no-read-permissions it seems like I want to create a .ini file with the updated permissions. Is there a way to configure django so that it will use uwsgi.ini file automatically (without running uwsgi --ini uwsgi.ini? I would prefer to not install the uwsgi package on the remote server. -
Using TabularInline showing different errors
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting different errors like the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' and django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. I don't have much experience in using TabularInline that is why I am not able to do it corrrectly or what might be the mistake that I am doing. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'payment', 'coupon' ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] inlines = [ OrderItemAdmin, ] admin.site.register(OrderItem, OrderItemAdmin) admin.site.register(Order, OrderAdmin) Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ------------------------------------------------------ status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') def __str__(self): return self.user.username -
Problem with websocket, urlretrieve and Filefield django
I have one computer which creates a new image, and which sends the url by websocket to another server (with Django). The server can access the image. The problem is that the Django cannot save the image in the system when it is sent by the websocket, a new entry is only created in the database, but with a non-existent file. But the result of the urlretrieve has correct headers. When I execute the same code in the console of the django server, there is no problem. This is the code to save the image: result = urllib.request.urlretrieve(image_url) my_instance_model.my_field.save( os.path.basename(image_url), File(open(result[0], "rb")) ) lg_file.save() Why the server cannot save the content of the image when it is called by the websocket? How to fix the problem? Thank you! -
Does the model, the view or the serializer represent a REST resource in Django Rest Framework?
I am building an API using Django Rest Framework, and I'm trying to make it as RESTful as possible. Following this question (and also this question on SoftwareEngineering), I have described a number of resources that my API endpoints will expose, such as an Invoice that can be seen at the following URL: /api/v1/invoices/<invoicenumber>/ However, I am having trouble relating the RESTful design principles to the concrete workings of Django Rest Framework. It is unclear to me what constitues a resource: the model, the serializer or the view? In particular, I am confused about the correct place to implement my calculate_total() method. In a regular Django application it would certainly live in the the Invoice model: class InvoiceModel(models.Model): def calculate_total(self): # do calculation return total Although the actual calculation could be complex, the "total" is conceptually a part of the representation of the Invoice. In this sense, the resource is more equivalent to the InvoiceSerializer: class InvoiceSerializer(serializers.Serializer): total = serializers.SerializerMethodField() def get_total(self, obj): # do calculation return total Finally, the resource will always be accessed by a view. So you could also argue that the view is actually the resource, while the serializer and the model are simply implementation details: … -
How to modify Django models.DateTimeField type?
I am running an api server using django rest api. I want to change 2020-01-01T00:00:00+09:00 to 2020-01-01 00:00:00 in model. This is my model code.. from django.db import models class Data(models.Model): time = models.DateTimeField(auto_now_add=True) sensor = models.CharField(max_length=30) measure = models.IntegerField() def __str__(self): return self.sensor And my serializer code.. from rest_framework import serializers from .models import Data class MovieSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id','time','sensor','measure') lastly my view from .models import Data from .serializers import MovieSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class DataList(APIView): def get_object(self, pk): try: return Data.objects.filter(sensor=pk) except Data.DoesNotExist: raise Http404 def get(self, request, format=None): dt = Data.objects.all() serializer = MovieSerializer(dt, many=True) return Response(serializer.data) def post(self, request, format=None): val = request.data.values() if val is not None: for i in val: snippet = self.get_object(i) serializer = MovieSerializer(snippet, many=True) return Response(serializer.data) I think I can't modify the code of view and serialize. I need a way to modify the type in the model. Thank you. -
What does this Django migration error message mean?
When I try to create migrations for the Django models shown below, I'm getting an error message I don't understand. I am trying to model a website member who can add one or more other members as either friends or followers. In addition, a member can block any other member. Here are my models: class Member(models.Model): FRIEND = "friend_of" FOLLOWS = "follows" RELATION_TYPES = ((FRIEND, "friend"), (FOLLOWS, "follower")) user = models.OneToOneField(User, on_delete=models.CASCADE) relations = models.ManyToManyField( "self", choices=RELATION_TYPES, through="MemberRelation" ) blocks = models.ManyToManyField("self", through="MemberBlock") def __str__(self): return self.user.first_name class MemberRelation(models.Model): source = models.ForeignKey( "Member", related_name="source_member", on_delete=models.CASCADE ) target = models.ForeignKey( "Member", related_name="target_member", on_delete=models.CASCADE ) relation = models.CharField(max_length=8) # Contains Member.FRIEND or .FOLLOWER def __str__(self): return "Member {} {} member {}".format(self.source, self.relation, self.target) class MemberBlock(models.Model): source = models.ForeignKey( "Member", related_name="blocker", on_delete=models.CASCADE, ) target = models.ForeignKey( "Member", related_name="blocked", on_delete=models.CASCADE, ) def __str__(self): return "Member {} is blocking Member {}".format(self.source, self.target) I started out with the Member and MemberRelaton classes and my migrations ran without any errors. But after I add the MemberBlock class and a blocks ManyToMany field in my Member model, I'm getting the following error when I run the makemigrations command which I don't understand: You are trying to change the … -
Django sum objects filtering another model
I have this 3 models: class Provider(models.Model): name = models.CharField("Provider",max_length=200) def __str__(self): return self.name class Contract(models.Model): active = models.BooleanField(default=False, verbose_name="Active?") provider = models.ForeignKey(Provider, on_delete=models.CASCADE,verbose_name="Provider") total_to_spent = models.IntegerField(blank=True, null=True, verbose_name="Total to spend") def __str__(self,): return str(self.id) + '- ' + str(self.provider) class Invoice(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE,verbose_name="Contract",related_name='ContractObject',) value = models.IntegerField(verbose_name="Value") def __str__(self,): return str(self.contract) total_to_spent in Contract.model is the amount of money i can spent in that contract value in Invoice.model is the money related to that invoice that is then associated with the contract My view def ServicoView(request): contract_active = Contract.objects.filter(active=True) contratos_finish = Contract.objects.filter(active=False) context = { 'contract_active': contract_active, 'contratos_finish':contratos_finish, } return render(request, 'dashboard_servico.html', context) In my view i want to do the SUM of all invoices (value) related to one Contract for later compare to the total_to_spent to see if it passes the value or not -
How are arguments passed to view functions
I am reading a book on Django and see this blog example with the following files: views.py def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) subject = f"{cd['name']} recommends you read {post.title}" message = f"Read {post.title} at {post_url}\n\n" \ f"{cd['name']}\'s comments: {cd['comments']}" send_mail(subject, message, 'admin@myblog.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('<int:post_id>/share/', views.post_share, name='post_share'), ] template {% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %} I am struggling to understand how the parameter post_id get passed into views.py. I see it appears in the urls.py in the path … -
After login not authenticated in Django
i wanted to create login functionality on my website. I did it with help of one tutorial (i use 'django.contrib.auth' app so i didn't create any own views yet), but when i log in, i get information that user is not logged (only authentication is not working because i see on admin panel i am logged succesfully). What should i change? My code: login.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> </form> homepage.html {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} urls.py from django.contrib import admin from django.urls import include, path from django.contrib.auth import views from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='homepage.html'), name='homepage'), settings.py LOGIN_REDIRECT_URL = 'homepage' Everything is working good, templates etc, but this authentication not, i get information "You are not logged in" which is displayed when user is not authenticated. Could someone help me? I do something wrong probably. -
How to check session.modifed = True in response object in Django test?
[django 1.4, python 2.7] We have a custom session engine that stores session to redis (Pretty much the same as db session engine, just stores in redis). There are some public endpoints that the session middleware stores a session to redis (session.modified is set to True), which is not our intention. I am trying to write unit tests to check which endpoints do generate session. # This endpoint would always save session to redis def test_endpoint(request, **kwargs): request.session['asdfsaf'] = 1 # Or, request.session.modified = True (Both fine) return httplib.OK, "good" Attempt 1: response = self.client.post(reverse('test_endpoint', kwargs=self.kwargs), data={...}) print(response.status_code, response.content) # Ok print('am i modified?', self.client.session.modified) # False for i in range(10): redis = get_redis_instance(db=i) print("redis key", i, redis.keys()) # All return empty redis This unit test is unable to detect a session is saved via django session middleware. probably due to the fact that a new SessionStore is created every time this property is accessed (https://docs.djangoproject.com/en/2.2/topics/testing/tools/#persistent-state) Attempt 2: Taking inspiration from SessionMiddlewareTests: request = RequestFactory().post(reverse('test_endpoint', kwargs=self.kwargs), data={...}) response = HttpResponse('Session test') middleware = SessionMiddleware() middleware.process_request(request) # Handle the response through the middleware response = middleware.process_response(request, response) print('am i modified', request.session.modified) # False for i in range(10): redis = get_redis_instance(db=i) print("redis … -
Getting the value in a field in the json object that comes in tabular form with django
I get the data from the postgresql table as json as follows. But for example in the data coming in json; I want to display the data in the "symbol" field in the "for" loop. How can I do that ? So more than one data is coming and I want to print it on the screen one by one. [ {"model": "cryptoinfo.cryptoinfo", "pk": 4, "fields": {"createdDate": "2020-10-08T20:49:16.622Z", "user": 2, "created_userKey": "25301ba6-1ba9-4b46-801e-32fc51cb0bdc", "customerKey": "61754ecf-39d3-47e0-a089-7109a07aca63", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "2200", "secretKey": "0022"}}, {"model": "cryptoinfo.cryptoinfo", "pk": 7, "fields": {"createdDate": "2020-10-08T20:51:16.860Z", "user": 1, "created_userKey": "2f35f875-7ef6-4f17-b41e-9c192ff8d5df", "customerKey": "b1c8cee3-c703-4d27-ae74-ad61854f3539", "status": true, "side": "BUY", "type": "1", "symbol": "NEOUSDT", "quantity": "1", "reversePosition": "1", "stopMarketActive": "1", "shortStopPercentage": "1", "longStopPercentage": "1", "takeProfit": "1", "addPosition": "1", "takeProfitPercentage": "1", "longTakeProfitPercentage": "1", "shortTakeProfitPercentage": "1", "groupCode": "1453", "apiKey": "0011", "secretKey": "1100"}} ] def webhook(request): json_body = json.loads(request.body) queryset = CryptoInfo.objects.filter(status=True, symbol=json_body['symbol'], side=json_body['side']) data = serializers.serialize('json', queryset) print(data['symbol']) return HttpResponse(data, content_type='application/json') -
Implement Google Analytic on Website Django
I am looking to integrate Google Analytic in django website in html page or in django admin. I need to show the show data in Graphical format on Separate HTML Page. The Graphical data will be based on number of visitor on page in a month. My Website is purely based on Python Django. -
Django Form post action
So I can't figure it out how to make form submit action link to external website be invisible in inspect element. For example I got my html form something like this: <form method='POST' action='some link to external website'> <div>{{ form }}</div> Is it possible to make it hidden or not ? -
Django psycopg2.OperationalError when entering correct data
I have this problem recently with Django. I have postgreSQL database in Django and it used to work fine. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database_name', 'USER': 'database_user', 'PASSWORD': 'database_pwd', 'HOST': 'host', 'PORT': '5432', } } Recently, for some reason, it stopped working and it gives me this error: psycopg2.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Based on that specific error I would blame something PostgreSQL (server) side, but I can connect manually with the very same data 1:1 to this database and it works just fine. (Using pycharm's database management for example, or just with pgAdmin). This is hard tho because it does not allow me to use runserver at all. Also, others can connect to this database with very same data that I try with. How come I do something wrong? What should I check? Data in DATABASES is correct Others can connect with django I cannot connect with django I can connect outside of a django (pycharm's database management/pgAdmin) This is not IP-related -
AttributeError: 'NoneType' object has no attribute 'save'; Django & VanillaJS
I'm trying to update my Django database without having to refresh the page and I'm trying to achieve this with javascript making a fetch with a POST method and for some reason, python doesn't even register it as a post request, here are my models: class User(AbstractUser): pass class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wrote') body = models.TextField(blank=False) timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "author": self.author.username, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p") } def __str__(self): return f'Post #{self.id}: posted by {self.author.username} on {self.timestamp}' class Like(models.Model): """ This is the class of the likes """ user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="liked") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="likes") def serialize(self): return { "id": self.id, "user": self.user, "post": self.post } def __str__(self): return f'like #{self.id}: {self.user.username} liked {self.post}' class Follow(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') class Meta: unique_together = ('follower','followed') def __str__(self): return f'#{self.id}: {self.follower} followed {self.followed}' Here is my js: document.querySelector('.posts').addEventListener('click', (event) => { if(event.target.innerHTML === 'Edit'){ appear(event.target); }else if(event.target.value === 'Update'){ disappear(event.target); update(`${event.target.previousElementSibling.innerHTML}, ${event.target.parentNode.firstElementChild.value}`); return false; } }) function update(identity, new_content) { fetch('/post', { method: "POST", credentials: "same-origin", headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ id: parseInt(identity), body: new_content … -
unable to create, migrate model, register the model to admin and restart django server programmatically
I am trying to create dynamic models and trying to migrate it programmatically and registering a model to the admin site. I could not hack into migration api but was able to run the manage (makemigrations and migrate command). I am able to do it. But when I register the model in the admin, it shows grayed out and I have to restart the server to get it enabled. I have not been able to restart server programmatically. Any help here? model = type(m.get("name"), (models.Model,), m.get("attrs")) def migrate(): from django.core import management from django.db.migrations.recorder import MigrationRecorder db_name = "programaticfetchfromdatabase" app_label = "programaticfetchfromdatabase" try: management.call_command("startapp", app_label) management.call_command("makemigrations", app_label) management.call_command("migrate", app_label, MigrationRecorder.Migration.objects.filter( app=app_label).last().__dict__.get("name"), "--database=="+db_name) return True catch: # raise Exception("Unable to perform migration) return False if migrate(): from django.contrib import admin # If register and dont restart the model is grayed out admin.site.register(model) # so restarting server here # restart server (WHICH API do I use here) from django.utils import autoreload autoreload.restart_with_reloader() # I get port already in use error I want to know why the model is grayed out after dynamic admin registration or I want to reload the django server programmatically -
What are different inheritance styles in Django
I want to know about the different types of inheritance styles that are used in Django -
Django: DRY / modular dynamic Django emails? (emails.py)
Question Is there a better way of organizing Django emails that's more class based? (like maybe a package that works similar to how we write Django models, managers, tables, CBVs, etc.) Context And there's a lot... sorry. I've been learning how to send emails with Django recently, and have found it really unintuitive so far compared to other parts of Django (like models, managers, CBVs, etc.). It seems to add really bulky amounts of code, and besides with comments, you can't really tell what you're sending when you use send_mail(). Also, parameter from_email is mandatory and will raise an error if empty, but in the documentation it literally says from_email: A string. If None, Django will use the value of the DEFAULT_FROM_EMAIL setting. Again, If None, Django will use the value of the DEFAULT_FROM_EMAIL setting. But, if you don't assign it directly, you'll get this error: send_mail() missing 1 required positional argument: 'from_email' Soon after learning that one, I thought there was hope with the EmailMessage class. In fact, I thought it did make it much more intuitive because 1. You don't have to write everything directly in the in the line of code you want to send it because … -
Django / postgresql - model with only foreign keys
I have a model which looks like this: class InputTypeMap(models.Model): input_type = models.ForeignKey(InputType, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) gender = models.ForeignKey(Gender, on_delete=models.CASCADE) When I try to create instances of this model with: InputTypeMap.objects.create(input_type=input_type, training=training, gender=gender, category=category) I get an exception when using Postgres-11.9: Traceback (most recent call last): File "/home/hove/sleipner/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, Maintenance, Female, MareGielding, No). From the error message it seems to me that a ID key for the new entry is not generated. This code has worked as I expected for quite some time, but has "suddenly" started to fail locally - probably after a apt get upgrade. When I run the same code with sqlite or Postgres-10.14 thing continue to work as before. It is not clear to me whether this is a bug in my code (most probable ...), Django or Postgres. I am using Django version 3.1.2 -
Email field encryption django
I want to save my email as a encrypted form and in future other fields aswell may include. I checked is https://github.com/erikvw/django-crypto-fields but I am unable to figure out KEY_PATH = '/etc/myproject/django_crypto_fields') what is this and what I am suppose to paste here ? And if somebody knows any other good solution kindly tell me . Any help would be highly appreciated -
updating a queryset throws an error upon iteration in python/django
I have an ordered query that I want to append to a list and then split into sublists based on the price. My code is as follows: def home(books): grouped_books = [] for i in range(len(books) - 1): this_book = books[i].price next_book = books[i+1].price if this_book != next_book and price >= 100: r = books[:i+1] grouped_books.append(r) for ob in grouped_books: books = books.exclude(id__in=[o.id for o in ob]) Upon iterating after the query is updated, this code throws an error that list index is out of range Am I doing something wrong here? I'd appreciate your help. Thanks! -
Python Django how to interact and link from one app to another?
I created an app called 'user' that has all of the login, registration, and logout (user/login, user/registration, user/logout) logic using the Django's User model. If the user logs in, how do I redirect them to a different app, say, 'posts' where they can view a list of different posts? Here's the main urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('user/', include("user.urls")), ] Also, if I wanted to create a view for the main index page, do I create a views.py file in the main folder and add a path to that page? What would that path look like? I am trying to teach myself everything so let me know if there are some gaps of information. Thanks.