Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid IntegrityError issue with update_or_create?
I would appreciate it if someone could explain why I'm having IntegrityError exception being thrown here, and how to avoid it. When an object already exists, isn't the update_or_create method supposed to update it ? models.py class OHLCV(TimestampedModel): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='candles', null=True) index = models.ForeignKey(Index, on_delete=models.CASCADE, related_name='candles', null=True) timeframe = models.CharField(max_length=10) open, high, low, close, volume = [models.FloatField(null=True) for i in range(5)] datetime = models.DateTimeField(null=True) class Meta: verbose_name_plural = "OHLCV" unique_together = [['market', 'timeframe', 'datetime'], ['index', 'timeframe', 'datetime']] tasks.py @app.task def bulk_update_ohlcv(timeframe): for obj in Market.objects.filter(active=True): if obj.exchange.is_status_ok(): update_ohlcv.delay('market', obj.pk, timeframe) @app.task def update_ohlcv(self, type, pk, timeframe): [code here] if obj.__class__ == Market: ohlcv, created = OHLCV.objects.update_or_create(market=obj, timeframe=timeframe, datetime=dt, open=candle[1], defaults=defaults ) elif obj.__class__ == Index: ohlcv, created = OHLCV.objects.update_or_create(index=obj, timeframe=timeframe, datetime=dt, open=candle[1], defaults=defaults ) Error: -celery_worker-1 | 2023-04-01T06:55:47.710298043Z IntegrityError: duplicate key value violates unique constraint -celery_worker-1 | 2023-04-01T06:55:47.710302260Z "market_ohlcv_market_id_timeframe_datetime_8ffd84de_uniq" -celery_worker-1 | 2023-04-01T06:55:47.710306227Z DETAIL: Key (market_id, timeframe, datetime)=(84, 5m, 2023-03-31 21:20:00+00) -celery_worker-1 | 2023-04-01T06:55:47.710310646Z already exists. -
I can connect django with two databases?
I want to use two databases in my Django project to store the data in the first and the metadata in the second. is it possible and how do I do it? -
How to use React and Django for user token authentication and storage
I am aware this has been asked so many times but the more I search the more conflicted I seem with the answers I find. What I want to accomplish is a secure and user experience friendly approach to authenticating and storing user's token. As seen here the recommended answer suggests to use a set of two cookies which would have to have the secure and httpOnly attributes (Since I have Django and React on different domains I would not be able to use any sort of sameSite cookie) In the same question the next best answer proposes using Redux (Is Redux even more secure?) to store the token in a variable and refresh it with a refresh token stored in LocalStorage that would be used to get a auth token. Now the problem I see with this is that he mentions that he used LocalStorage in his solution as a cookie would not be good for his stateless approach. If I am not mistaken a cookie is neither stateful nor stateless as is just a transport medium and what is inside is what is stateless or not such as a sessionId which Django does with its templates and Session … -
Django doesn't load static files from React
Django gives 404 error for static files. I created a Django and React projects in separate folders following this tutorial but created the React project with Vite https://www.youtube.com/watch?v=tYKRAXIio28 . Then brought React project as "frontend" into the Django. Ran npm run build which created below inside frontend folder. │ index.html │ vite.svg │ └───assets index-757929e7.js index-a9bba2ed.css Added BASE_DIR / 'frontend/dist' in Django settings.py file TEMPLATES = [ { "DIRS": [ BASE_DIR / 'frontend/dist' ], }, ] Added this below that for static files npm created. STATICFILES_DIRS = [ BASE_DIR / 'frontend/dist/assets' ] Added path('', TemplateView.as_view(template_name='index.html')) to urls.py When I go to 127.0.0.1:8000 it successfully loads the html file but not the css or js. I'm getting this error in the browser. Refused to apply style from 'http://localhost:8000/assets/index-a9bba2ed.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The html file in frontend/dist folder. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React</title> <script type="module" crossorigin src="/assets/index-757929e7.js"></script> <link rel="stylesheet" href="/assets/index-a9bba2ed.css"> </head> <body> <div id="root"></div> </body> </html> -
How to pass a model name to django realated like _set?
IS there any way to pass dinamically model name to realted field if my qyery is like instance.instance_set.all()? Here's my code? Models class Category(models.Model): name = models.CharField(max_length=100, db_index=True, verbose_name='Имя категории') slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name='URL') objects = CategoryManager() class Product(models.Model): class Meta: abstract = True MIN_RESOLUTION = (400, 400) MAX_RESOLUTION = (1800, 1800) # MAX_IMAGE_SIZE = 3145728 MAX_IMAGE_SIZE = 314 title = models.CharField(max_length=255, verbose_name='Наименование товара') slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name='URL') description = models.TextField(blank=True, verbose_name='Описание') price = models.DecimalField(max_digits=9, decimal_places=2, verbose_name='Цена') photo = models.ImageField(upload_to='photos/%y/%m/%d', verbose_name='Фото', blank=True, null=True) time_create = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') time_update = models.DateTimeField(auto_now=True, verbose_name='Дата обновления') category = models.ForeignKey('Category', on_delete=models.CASCADE, verbose_name='Категория') class NoteBook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') processor = models.CharField(max_length=255, verbose_name='Частота процессора') ram = models.CharField(max_length=255, verbose_name='Оперативная память') video = models.CharField(max_length=255, verbose_name='Видеокарта') chargeless_time = models.CharField(max_length=255, verbose_name='Время автономной работы') Abastract class for child models I want to get all Notebook objects through model Category, so i created a serializer for products. It would be easier to get Notebook objects not using Category model, but problem is Notebook model's parent is abstract class Product and i don't know how to pass a model name to serialier dynamically Serializer class CategorySerializer(serializers.ModelSerializer): products = serializers.SerializerMethodField(method_name='get_product') class Meta: model = … -
how I can connect project django with HDFS?
I want to connect my project django with HDFS to storage data I want to connect my project django with HDFS to storage data, how can I do that -
Django Debug toolbar is not showing though `view page source` is showing debug tool's html
I am a beginner at Django. Django-debug-tool is not showing. I have gone through the official documentation step by step. But It did work for me. I have seen lots of existing answers as well seems it doesn't work. Interestingly from the browser when I go to view page source it shows the debug tool's HTML after my page's code. But it doesn't show. Django version: 4.1.7 django-debug-toolbar: latest settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-ug*k0401%7v_i887cu4m$szp%(i=h=*9yyi&4b#71%ozksz1%6" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "playground", "debug_toolbar" ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", ] INTERNAL_IPS = [ "127.0.0.1", ] ROOT_URLCONF = "storefront.urls" 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", ], }, }, ] WSGI_APPLICATION = "storefront.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, … -
Axios request not sending expected cookie header to Django server
I'm trying to upload a file to a Django server using an Axios post request in a React app. The server expects a CSRF cookie to be included in the request headers. The request already includes all the methods I could find for setting the cookie. Through document.cookie, setting withCredential: true, and specifying the Cookie header. Here is my Axios request: const onSubmit = async (data) => { const formData = new FormData() formData.append('file', data.file[0]) const csrftoken = getCookie('csrftoken'); document.cookie = `csrftoken=${csrftoken}` const res = await axiosInstance.post('/upload/', formData, { timeout: 0, headers: { 'Cookie': `csrftoken=${csrftoken}`, 'Content-Type': 'multipart/form-data', 'x-csrftoken': csrftoken, }, withCredentials: true, }) console.log(res) } And here is my Django view: def upload_file(request): form = UploadFileForm() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_id = save_file_to_database(request.FILES['file']) response = JsonResponse({'id': file_id}, status=201) return response else: response = HttpResponse({'message': 'Upload failed'}, status=400) return response return render(request, 'upload.html', {'form': form}) Also, I believe I have properly set the relevant Django settings in settings.py: CORS_ORIGIN_WHITELIST = ( "http://localhost:8000", "http://127.0.0.1:5173", ) CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:5173" ] SESSION_COOKIE_SAMESITE = 'None' What can I do to ensure that the CSRF cookie is included in the request headers or that the CSRF requirements are met … -
is it sensible to make a utility function in django that redirects a user to the same page that they came from?
i frequently involve using taskflows that accept a form input through a [synchronous] post request. is it sensible to make a function for redirecting the user to the same page that the request came from? my understanding is that redirecting the user is desirable as opposed to just rendering the same page from the post request. this allows the user to refresh the page without getting the popup for resubmitting the form. i'm thinking of this design pattern here https://en.wikipedia.org/wiki/Post/Redirect/Get does django have any inbuilt utilities to perform this? i'm imagining a code like this def redirect_to_self(request: HttpRequest, path_suffix: str = '') -> HttpResponseRedirect: return redirect(request.path+path_suffix) this also allows me to return messages to the user through ?alert=hello or something like that. using only asynchronous submits [via fetch api or such] is another option. but i dont want to touch the frontend for the time being. of course, this is assuming that the post request for submitting the form is handled by the same view that renders the form via get, which is true for my use case. -
Why does GET Details returns all Null and Delete Details returns "detail": "Method \"GET\" not allowed." when getting some and deleting some objects?
I built a rest framework in Django. When I do getAll, I get all the data from my database (no problem). The problem is when I do GET details and DELETE details. For the get and delete, I need to return and delete multiple objects (not just one and not all). models.py: class ProA(models.Model): var1 = models.CharField(max_length=200, null=True, blank=True) var2 = models.CharField(max_length=200, null=True, blank=True) var3 = models.CharField(max_length=200, null=True, blank=True) serializers.py: class ProASerializer(serializers.ModelSerializer): class Meta: model = ProA fields = '__all__' urls.py: urlpatterns = [ path('proa-getAll/', views.getAll, name='proa_getAll'), path('proa-getOne/<str:var1>', views.getOneSet, name='proa_getOne'), path('proa-delete/<str:var1>', views.deleteOneSet, name='proa_delete'), ] views.py: @api_view(['GET']) def getAll(request): proas = ProA.objects.all() serializer = ProASerializer(ProA.objects.all(), many=True) return Response(serializer.data) @api_view(['GET']) def getOneSet(request, var1): proa = ProA.objects.filter(var1=var1) serializer = ProASerializer(proa, many=False) return Response(serializer.data) @api_view(['DELETE']) def deleteOneSet(request, var1): try: data = ProA.objects.filter(var1=var1) except data.DoesNotExist: return Response({'message': 'The var1 value does not exist'}, status=status.HTTP_404_NOT_FOUND) data.delete() return Response({'message': 'Data was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) When I go to the getOneSet URL to get all the objects where var1=MS107, I get the following: When I go to the deleteOneSet URL to delete all the objects where var1=MS107, I get the following: I have tried many things, but no idea how to solve them. I am new to Django, … -
Django: I'm adding the correct namespace to my apps but it doesn't work
I have 2 apps main and accounts this is the urls: Main: enter image description here Accounts: enter image description here enter image description here I did try to make changes in the settings but nothing worked -
Django DRF serializer multiple database
When I check if data is valid or not serializer.is_valid() Serializer checks relationships in defualt connection but i am using different database connection. How makes Serializer using/change database connection or stop check, I mean ignore this message Invalid pk \"27\" - object does not exist.? serializers.py class CompetitionSerializer(serializers.ModelSerializer): sections = SectionSerializer(many=True) class Meta: model = Competition # depth = 1 #fields = '__all__' exclude = ('updated_date_at', ) -
Python (Django rest framework): Trying to remove a temporary file in unit test tearDown() claims file is in use
I'm creating a simple API using DRF, where one of my models ("Card") has an ImageField. I'm now writing unit tests for the serializer and I'm having trouble on one specific test that updates the image field. The file keeps being in use so the temp directory created to store it can't be deleted. My model stores this image files in <project_root>/media/img. My test class has a setup method that creates a temp folder and then creates some test data, including an image: class CardSerializerTestCase(APITestCase): def setUp(self): # Temporary directory for images: super().setUp() temp_dir = os.path.join(settings.BASE_DIR, "media") self.temp_media = tempfile.TemporaryDirectory(dir=temp_dir, prefix=f"{self.__class__.__name__}_") settings.MEDIA_ROOT = self.temp_media.name print("Created temp directory for images:", self.temp_media.name) # test data 1: self.valid_card = { "image": self.create_temp_image('image1.png') # some other fields, not important now } # test data 2: self.updated_card = { "image": self.create_temp_image('image2.png') # some more fields } def create_temp_image(self, filename): img_data = BytesIO() img = Image.new("RGB", (100, 100)) img.save(img_data, format="PNG") img_data.seek(0) return SimpleUploadedFile(filename, img_data.getvalue()) Now this is my unit test (the relevant part, since there are other fields being tested): def test_card_serializer_update(self): # Create a new card serializer = CardSerializer(data=self.valid_card) self.assertTrue(serializer.is_valid()) card = serializer.save() # Update card with new values serializer = CardSerializer(instance=card, data=self.updated_card) self.assertTrue(serializer.is_valid()) saved_card … -
How to remove an object from a QuerySet in Django
A room consists of predefined timeslots and a customer can book any time slot. models,py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models. CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() """class used when a user books a room slot.""" class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) check_in_date = models.DateField() timeslot = models.ForeignKey(TimeSlot, on_delete=models. CASCADE) A room manager can see the list of all the time slots and also filter them. forms.py class SearchTimeSlotsForm(forms.Form): date = forms.DateField(widget=FutureDateInput(attrs={'class': 'unbold-form'}), required=False, initial=date.today()) available_from = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False) available_till = forms.TimeField(widget=TimeInput(attrs={'class': 'unbold-form'}), required=False) STATUS = ( (None, 'Any'), ('Vacant', 'Vacant'), ('Booked', 'Booked'), ) occupancy = forms.ChoiceField( required=False, widget=forms.RadioSelect(attrs={'class': 'unbold-form'}), choices=STATUS, ) SORT = ( ('available_from', 'Ascending'), ('-available_from', 'Descending'), ) sort_by = forms.ChoiceField( widget=forms.Select(attrs={'class': 'unbold-form'}), choices=SORT, ) """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = … -
django and drf serializer error: expected a dictionary but got a string
class TodoView(views.APIView): serializer_class = TaskSerializer def get(self,request,date): tasks = Task.objects.filter(date=date) return Response(TaskSerializer(tasks,many=True).data,status=200) def post(self,request,date): data = TaskSerializer(data=request.data, many=True) print(data.is_valid()) print(data) print(data.errors) when i print the data i get something like this: ([{'title':'title1'},{'title':'title2'}] which seems like the correct format for me, because i am sending a list of objects, here is models.py: class Todo(models.Model): published = models.DateField(unique=True) class Task(models.Model): title = models.CharField(max_length=200) date = models.ForeignKey(Todo,on_delete=models.CASCADE,related_name='todo_date',to_field='published') serializer.py: class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = 'id','published', class TaskSerializer(serializers.ModelSerializer): date = TodoSerializer() class Meta: model = Task fields = 'id','title', anyone knows how to resolve this? -
How to import app level views to project level urls file?
These are the instructions I received from my project The course instructs me to open the project level URLS and configure the router settings then it wants me to open the app level urls and add the include routers path. The problem im having is the view is defined in the app level views.py so it gives me a name error router = DefaultRouter(trailing_slash=False) router.register(r'tables', views.BookingViewSet, basename='tables') the name error is that views. is not a defined module but there seems to be no way to import this at the project level ive tried all the ways I can find to get it imported, the only way I can get this to even run the development server is to ignore the instructions and configure the router at the app level where the views are defined, however then the router doesnt work. Im struggling to understand what i need to do here. as far as i can tell I have it configured exactly as it asks me to here is my views.py at the project level from django.shortcuts import render from rest_framework.decorators import api_view from .models import Menu, Booking from .serializers import MenuSerializer, BookingSerializer from rest_framework import generics, viewsets, permissions # … -
Adding new feature computed from Raw Query to GeoDjango+DRF serializer
It's all about GeoDjango and Django Rest Framework. I have a collection of points over the world (WSG84) stored in a model and I would like to add them a buffer of 800m of radius. In plain SQL I'll do it simply: SELECT id, ST_Buffer(L.geom::Geography, 800, 'quad_segs=8')::Geometry AS circle FROM location AS L; And it does exactly the job. Form there I am trying to use the Django Rest Framework to get a GeoJSON from the Location table with all circles sampled from this Raw Query. That's where things become tricky. After few tries trying to bind everything together, the best I could achieve is more or less: class Location(Model): geom = models.PointField() class CircleSerializer(GeoFeatureModelSerializer): id = serializers.IntegerField(required=True) circle = GeometrySerializerMethodField() def get_circle(self, obj): return obj.circle class Meta: model = Location geo_field = "circle" fields = ('id',) class CircleViewSet(ListAPIView): queryset = Location.objects.raw(""" SELECT id, ST_Buffer(L.geom::Geography, 800, 'quad_segs=8')::Geometry AS circle FROM location AS L; """) serializer_class = CircleSerializer Which leave me with this error: Traceback (most recent call last): File "site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "site-packages\django\views\generic\base.py", line … -
Use orjson in drf
Hi all im looking into faster ways of returning JSON data etc. I know that FastAPI uses ojson orjson Is there a way to replace the standard drf serializer to orjson? -
how to resolve this error Websocket connection error Django Nginx
I am unable to make websocket connection with javascript in my django project, currently hosted with nginx. I tried to put the port 8000, 443 and 0 and it didn't work enter image description here I need the connection to work -
Setting initial value for a new foreign key on django admin
I have the following django models: class ModelA(models.Model): something = models.ForeignKey('Something') extra_data = models.ForeignKey('ModelB') class ModelB(models.Model): something = models.ForeignKey('Something') I have registered both models with django admin. Is is possible to pre-set ModelB's something to the parent's something value when I create a new Model B via the + button? I have tried using formfield_for_foreignkey and setting kwargs["initial"] but that only is able to set the foreign key itself, it does not provide default values for new objects. This should be possible to do by making the + link URL to add &something= to the current object's something value. But I am not sure how to tell django to do this. -
Heroku Build Error: Unable to load xmlsec-openssl library
I was in the process of trying to update my team's app from heroku-18 stack to heroku-22. Due to the Python version that supports heroku-22, I had to update to Python 3.9.16 too and as well as one of the Python build-packs for Django SAML2 Authentication. Going from this buildpack:django-saml2-auth to grafana-django-saml2-auth however one of the installations needed (xmlsec1) is resulting in the website saying Sorry, you are not allowed to access this app and this error. Any ideas of how to fix it? Error: unable to load xmlsec-openssl library. Make sure that you have this it installed, check shared libraries path (LD_LIBRARY_PATH) envornment variable or use "--crypto" option to specify different crypto engine. Error: initialization failed func=xmlSecCryptoShutdown:file=app.c:line=69:obj=unknown:subj=cryptoShutdown:error=9:feature is not implemented: func=xmlSecAppCryptoShutdown:file=crypto.c:line=48:obj=unknown:subj=xmlSecCryptoShutdown:error=1:xmlsec library function failed: Error: xmlsec crypto shutdown failed. output=Usage: xmlsec [] [] xmlsec is a command line tool for signing, verifying, encrypting and decrypting XML documents. The allowed values are: --help display this help information and exit --help-all display help information for all commands/options and exit --help- display help information for command and exit --version print version information and exit --keys keys XML file manipulation --sign sign data and output XML document --verify verify signed document --sign-tmpl create … -
Complex dependencies and relationships between Celery tasks
I'm working on an integration between my Django REST-based LMS and Google Classroom via the Classroom API. Using signals, when certain actions happen in my LMS, I dispatch specific actions from an "integration class", which ultimately fire API calls to the Classroom API. I run the integration class methods as Celery tasks. I didn't want to have to code the Celery-task-related logic inside of my integration class, in order to separate the business logic with the logic relating to executing the methods, so I made a task that receives the method name and the kwargs and runs the method with the given kwargs. Since the integration class' methods accept model instances as arguments, I also perform "(un)marshalling" of the arguments by turning them to pk's and querying for them inside of the task: dispatching function: https://github.com/Evo-Learning-project/sai_evo_backend/blob/classroom_integration/integrations/registry.py#L10 task: https://github.com/Evo-Learning-project/sai_evo_backend/blob/classroom_integration/integrations/classroom/tasks.py#L20 Here's the issue: some tasks rely on other tasks having successfully run before; however, those tasks aren't run together. I'll give an example: when a student enrolls in a course in my LMS, they are also enrolled in the paired course on Classroom. Later, when a student participates in an exam in my LMS, which is paired with a courseWork item on … -
messages not rendering from Djangos login or logout request
I am trying to show alerts on my home page when some one successfully logs in or logs out, and also show an error alert if something goes wrong with login. All my message alerts are working with all of my views apart from the login and logout views and I have no idea why. VIEWS: def user_login(request): data = cartData(request) cartItems = data['cartItems'] context = { 'cartItems': cartItems, } if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {'context': context}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML: {% if messages %} <div class="alert alert-success" id="msg" role="alert"> <h4 class="alert-heading">Success</h4> {% for message in messages %} <p>{{message}}</p> {% endfor %} </div> {% endif %} -
How do create and append to a list in html template, django
I'm trying to access the completed attritbute of each user_coursecontents with the 'username' foreign key that matches the user in the loop (technically the same as this {{ user.user_coursecontents.completed }}), and append them all to an array. Then I will display this as a field in a table. e.g. my_list = [True, True, False, False, True, False, False] Listed below are 2 tables/ databases with only relevant fields User username (char field) CourseContent username (foreign key) completed (bool field) This is the view def usersView(request): users = CustomUser.objects.all() user_coursecontents = Users_CourseContent.objects.all() #user.coursecontents context = { 'users': users, 'user_coursecontents': user_coursecontents } return render(request, 'main/users.html', context) this is part of the html template {% for user in users %} <table> <tr> <td>{{ user.username }}</td> **my_list = []** {% for user_coursecontent in user_coursecontents %} {% if user_coursecontent.username == user.username %} **my_list.append(user_coursecontent.completed)** {% endif %} {% endfor %} <td>{{ user.user_coursecontent.completed }}</td> </tr> </table> I'm aware that your text and my_list.append(user_coursecontent.completed) isn't the correct syntax but I cannot find the correct syntax anywhere. If anyone knows how to create an array and append to it, that'd be great. I'm not sure if that will solve it but I assume it will. Any help is amazing … -
TemplateDoesNotExist at /payment/process/
My views, templates and urls are perfectly fine, but for some reason Django doesn't see process.html Here is my file structure and the error (https://i.stack.imgur.com/MCRod.png) (https://i.stack.imgur.com/F0Wta.png) I tried to change the file structure and the names of the templates multiple times, but no good outcome resulted