Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - While registering, registered data are not saved on database and so can't perform LogIn
I have been trying so hard to make an user registration and login using Django. I am using AbstractUser for this. Whenever, I enter the form fields, and click Signup the page is not getting redirected and the entered data aren't saved on the database This is my view.py def register(request): if request.method == "POST": print("method is post") form = UserRegisterForm(request.POST or None) if form.is_valid(): print("form is valid") form.save() username = form.cleaned_data.get("username") messages.success(request, f"hey {username}, account created successfully") new_user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password1']) login(request, new_user) return redirect("jew_app:home") else: print(form.errors) else: print("user can't be registered") form = UserRegisterForm() context = { 'form': form } return render(request, 'user/register.html', context) def user_login(request): if request.user.is_authenticated: messages.warning(request, f"Hey you are already logged in") return redirect("accounts:profile") if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.objects.get(email=email) user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.success(request, "You are logged in") return redirect("jew_app:home") else: messages.warning(request, "User Does Not Exist. Create an account") except: messages.warning(request, f"User with {email} does not exist") context = { } return render(request, 'user/login.html', context) models.py class User(AbstractUser): email = models.EmailField(unique=True, null=False) username = models.CharField(max_length=100) dob = models.DateField(null=True, blank=True) mobile_number = models.CharField(max_length=10, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS … -
Reportlab Muiltidoc pass args to canvasmaker
I am trying to pass custom values via my canvasmaker. But i can't create an instance of Canvas or pass values to it. This is my canvas Class. class PracticeBookCanvas(canvas.Canvas): #---------------------------------------------------------------------- def __init__(self, *args, **kwargs): """Constructor""" # canvas.Canvas.__init__(self, *args, **kwargs) canvas.Canvas.__init__(self, *args, **kwargs) self.pages = [] # def __init__(self, filename, subject_name, branch_name, *args, **kwargs): # canvas.Canvas.__init__(self, filename, *args, **kwargs) # self.pages = [] # self.subject_name = subject_name # self.branch_name = branch_name #---------------------------------------------------------------------- def showPage(self): """ On a page break, add information to the list """ self.pages.append(dict(self.__dict__)) self._startPage() #---------------------------------------------------------------------- def save(self): """ Add the page number to each page (page x of y) """ page_count = len(self.pages) for page in self.pages: self.__dict__.update(page) self.draw_page_number(page_count) self.draw_page_header() canvas.Canvas.showPage(self) canvas.Canvas.save(self) #---------------------------------------------------------------------- def draw_page_number(self, page_count): """ Add the page number """ page = "Page %s" % (self._pageNumber) self.setFont("Noto-Sans", 9) # self.drawRightString(195*mm, 272*mm, page) self.drawCentredString(195*mm, 0.4 * inch, page) def draw_page_header(self): self.setFont('Raleway', 14) self.drawString(self._pagesize[0] / 2, letter[1] - 0.5 * inch, "Practice Workbook") # self.drawString(self._pagesize[0] / 2, letter[1] - 0.5 * inch, f"{self.subject} / {self.branch}") This is my function which generates doc. def genPracticeWorkbook(user, branch, level): logger.info(f"Generating Practice Workbook {user}") BASE_DIR = Path(__file__).resolve().parent.parent usr = User.objects.get(id=user) # user_downloads = UserDownloads.objects.all() user_downloads = UserDownloads( user=usr, status="in_progress", file_name=f"Practice Workbook_{level}" … -
Dynamic custom fields in the Django Admin panel?
I have a number of Custom Fields in the Django Admin panel in which I'd like to be able to add values into and I'm wondering if that's possible to implement. Currently, I have one Custom Field in use that on the frontend shows "Masses: " and next to it I have a field but it's free text. The other Custom Fields are NULL and do not show on the frontend side. Below is a snippet of the loop which iterates through the items: {% for field in form %} {% for key, value in custom_fields_used.items %} {% if key == field.name %} <div class="row"> <div class="col-sm-2 text-right"> {{ value }} </div> <div class="col-sm-4"> {{ field }} </div> <div class="col-sm-2 text-right"> </div> <div class="col-sm-4"> </div> </div> {% endif %} {% endfor %} {% endfor %} Below I have also a JSON snippet from that specific table in which the values reside, the Custom Fields are part of the JSON template: "tenant": { "custom_field_1": "Masses:", # this field "custom_field_2": null, "custom_field_3": null, "custom_field_4": null, "custom_field_5": null, "custom_field_6": null, "custom_field_7": null, "custom_field_8": null, } I managed to implement a Multiselect in the Admin Panel...However the fields are empty and those fields I … -
Implementing django_multitenant in django 4.2
I'm working on a new django 4.2 project. To implement multi-tenancy, I'm using the django_multitenant library with Citus 12.1 and PostgreSQL 16. While defining the models I see that there is ambiguity in the recommended steps. There are multiple guides but with different suggestions. https://www.citusdata.com/blog/2023/05/09/evolving-django-multitenant-to-build-scalable-saas-apps-on-postgres-and-citus/ https://github.com/citusdata/django-multitenant#readme There is no clear explanation on how migrations are addressed. The former asks to write a custom migration file while the latter skipped that step. What is the recommended way and model structure if one is implementing django_multitenant in a new django 4.2 project using citus 12.1 and postgresql 16 using the default row-based sharding option? -
display django ckeditor uploaded images in vuejs frontend
I want to make a blog with django rest backend and vuejs frontend and I want to use ckeditor When I upload images in the RichTextUploadingField, the images are stored in '/media/ck/' address and as you know i can't display images with this address in vuejs frontend i need absolute url of images...i need this address -> http://127.0.0.1:8000/media/ck/ how can i display django ckeditor uploaded images in vuejs frontend actually how can i send the uploaded images in the django ckeditor with absolute url to vuejs settings: STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' CKEDITOR_UPLOAD_PATH = 'ck/' model: class Post(models.Model): name = models.CharField(max_length=200,) information = RichTextUploadingField() serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('name','information') views: def get_all_posts(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True, context={'request':request}) return JsonResponse(serializer.data,safe=False) -
Prefetch objects of Proxy model Django ORM
I have 2 models in my Django 3.2. class Order: ... daily_order = models.ForeignKey( DailyOrder, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders', ) class DailyOrder: class Meta: proxy = True ordering = ('id', ) default_related_name = 'daily_orders' verbose_name = 'Daily order' verbose_name_plural = 'Daily orders' My question is when i try to get info from related manager and iterate through it it's increase db queries. In Order model I have method: def available(self): orders_time = [order.time for order in self.orders.all().prefetch_related('daily_order')] #But this prefetch isn't work I want to decrease my DB queries, any ideas ? -
Is there a BPMN painter compatible with viewflow?
I want to integrate D with my existing Django application and want a graphical BPMN painter that my users can use to build workflows for viewflow. Someone recommended "flow designer", but that appears to be dedicated to service now. Another person recommended CWL,but I could find no supporting information. The viewflow demo lists 'material' but that too doesn't quite fit. So if someone knows a BPMN painter that is compatible with viewflow -
why next table repeated when first table take full page?
I am using weasyprint lib for make html to pdf. I have two table - product and summary. when product table take full page in pdf then summary table after page break repeated. it seems css issue. I tried page-break-insert, before, after. Its not working for me. see image for ref. 1. product table, page break, 2. summary table -
Django Email Already Exists
So i have tried to create Custome Users for my project Provider and Seeker, also i have create a register view, however, whenever i want to add a user (provider) it tells me that the email already exists, despite there is no users in the database yet I have tried to remove the UniqueValidator from the ProviderSerializer and implement the logic of finding duplicate emails in the view I have tried to save the user to the database then check if there is a email duplicate from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import AllowAny, IsAdminUser from .models import Provider, Seeker from .serializer import ProviderSerializer from django.contrib.auth.models import Group from rest_framework import serializers @api_view(['POST']) @permission_classes([AllowAny]) def Register(request): if request.data.get('work_email'): seri = ProviderSerializer(data=request.data) if seri.is_valid(): try: user = seri.save() try: group = Group.objects.get(name='Provider') user.groups.add(group) except Group.DoesNotExist: return Response({"Message": "Exception at group assigning"}) except serializers.ValidationError as e: return Response(e.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"Message": "User created successfully"}) else: return Response(seri.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({"Message": "No Work_email"}, status=status.HTTP_400_BAD_REQUEST) from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class GenericUser(AbstractUser): username = models.CharField(max_length=150, blank=True,null = True) email = models.EmailField(max_length=255,unique=True,db_index=True) … -
Online Quiz System Design [closed]
I looking for system design architecture for online quiz system using python, django and any SQL or nosql db, frontend framework. All possible type of questions and inputs from user should save in db. Full system design for online quiz system. -
Getting KeyError: 'id' when importing a CSV file using django-import-export
I am tring to update sqlite data by importing a csv file to django admin, only to get the error message for each single record I upload: Line number: 1 - 'id' Traceback (most recent call last): ... import_id_fields = [self.fields[f] for f in self.get_import_id_fields()] KeyError: 'id' Here is my models.py, which indicates a primary key: class HCPMaster(models.Model): external_id = models.CharField(max_length=200, primary_key=True) bi_external_id = models.CharField(max_length=200) name = models.CharField(max_length=200) ... The resources.py, which has the import_id_fields: class HCPMasterResource(resources.ModelResource): class Meta: model = HCPMaster import_id_fields = ['external_id'] The admin.py: class HCPMasterAdmin(ImportExportModelAdmin): resources_class = HCPMasterResource admin.site.register(HCPMaster, HCPMasterAdmin) The uploaded csv file (The columns match the HCPMaster model exactly): external_id,bi_external_id,name,primary_parent_name,parent_external_id,parent_parent_external_id,personal_title,administrative_title,license,network_external_id,status,verified_time,updated_time CNC1562173,CN1183335,John,Hospital A,Hospital A,CNHABCD,Doctor,Agent,,9.36678E+17,Active,44851,45231 CNC1531568,CN1183339,Mary,Hospital B,Hospital B,CNHABCE,Doctor,Agent,,9.37537E+17,Active,44799,45231 I have tried every possible solution on stackoverflow and github like: Specify import_id_fields to the actual primary key 'external_id'. Specify exclude = ['id'] in Meta Class of ModelResource. Specify fields in Meta Class of ModelResource: List all the fields in CSV file. Manually Create a id columns in the csv file with blank value. Sadly, none of them works. pip list: Django 4.2.7 django-import-export 3.3.3 -
CSRF token missing when making a POST request via Hoppscotch to Django
I'm working with a Django (version 4.0+) application and facing a CSRF verification issue when trying to make a POST request using Hoppscotch. I'm receiving the following error: { "detail": "CSRF Failed: CSRF token missing." } Here's the JSON body of my POST request: { "title": "Fiestaaaaaaaaaaaaaaaaaaaaaaaa", "description": "Para celebrar", "date": "2023-11-28T01:16:10Z", "location": "En mi casa" } I understand that I need to include a CSRF token in my request headers, but I'm not sure how to obtain this token when using Hoppscotch. I've made a GET request to my server expecting to see a csrftoken cookie that I can use for subsequent POST requests, but I couldn't find it in the response headers. Here are the response headers I received: allow: GET, POST, HEAD, OPTIONS content-length: 141 content-type: application/json ... (other headers) No Set-Cookie header appears with the CSRF token. Is there a specific way to configure Hoppscotch or Django to make this work? I'm lost on how to proceed with CSRF tokens in this environment. Any advice or guidance would be greatly appreciated. Thank you in advance. -
Not getting the right fields in Django
I am trying to create a subscription feature in my Django site where a user enters his name and email and clicks the 'Subscribe' button. I have written this code in the subscribe.html form but it keeps showing the main post form which is used to write the blog post. Can anyone help me fix this? Here are the relevant codes. forms.py Subscribe form (Please note that when I type http://127.0.0.1:8000/subscribe/, I see the 'Title' and 'Body' of the post form but not the Name and Email of the subscribe form.) class SubscribeForm(forms.Form): class Meta: model = Subscribe fields = ('Name', 'Email') widgets = { 'Name': forms.TextInput(attrs={'class': 'textinputclass'}), 'Email': forms.EmailField(widget=forms.TextInput(attrs={'class': 'emailinputclass'})) } class PostForm(forms.ModelForm): class Meta: model = Post # fields = ('author','title', 'body',) fields = ('title', 'body') widgets = { 'title': forms.TextInput(attrs={'class': 'textinputclass'}), 'body': forms.Textarea(attrs={'class': 'editable medium-editor-textarea postcontent'}), } views.py class SubscribeView(generic.CreateView): model = Subscribe form_class = PostForm template_name = 'blog/subscribe.html' success_url = reverse_lazy('subscribe') Templates Subscribe.html {% extends 'blog/base.html' %} {% block content %} <h1>Join my List</h1> <form method="POST" class="subscribe-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">Subscribe</button> </form> <script>var editor = new MediumEditor('.editable');</script> {% endblock %} Postnew.html {% extends 'blog/base.html' %} {% block content %} <h1>New post</h1> … -
How to set priorities for RQ queues under different supervisor programs
I'm using supervisor to run rqworker. I want to assign different number of workers for different queues, so I put each queue under a different program. How do I set priorities for these queues in this case? I know if I run workers for all the queues under single program, the order I specify queues in rqworker command is the priority of these queues. (https://python-rq.org/docs/workers/#strategies-for-dequeuing-jobs-from-queues) However, for my case, each queue is under a different program, wondering how I can set the priority. Should I start rqworker with nice command? Some config example would be nice. Thx! -
Is there a way to use Django's static method in a CSS rule?
I am trying to use background-image css rule for a django template. I am unable to use static mode with the image url. Is there a solution or work-around for this? Here's what I have tried to do: .hero-landing { background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url('{% static 'img/people_4.jpeg' %}'); background-size: cover; background-position: center; background-attachment: fixed; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 0 100px; color: #fff; } I can't get the url to work. -
django update statement not updating database as expected
I have django framework code where I am updating my database with simple found or not found on a condition where if cdr_number is equel to aparty variable update the database found if not update it with not found. but somehow even cdr_number is equal to aparty variable my code is still not updating the database with found although my if condition is working properly all the print statements and other operations are working. I have shared my print statements also for reference. please someone help on this thanks. for index,cdr_number in enumerate(cdr_numbers): # Read the CSV file # tests = reqData.objects.filter(data_id = data_ids[index]) test = temp_cdr_number[index].rec_data if str(aparty) == cdr_number: print(f"{aparty} FOUND") # print(f"{temp_cdr_number[index].data_id} {temp_cdr_number[index].req_data}") # COPY CDR TO CDRS FOLDER os.system(f"cp {file_path}{xlsx_file} cdrs/92{xlsx_file[:10]}-{data_ids[index]}.xlsx") # UPDATE DATA IN REQ_DATA TABLE # reqData.objects.filter(data_id=data_ids[index]).update(rec_data=f"{test}-{index}") print(reqData.objects.filter(data_id=data_ids[index]).update(rec_data=f"Found").query) # print(f"found updated {result}") # print(f"data_id : {data_ids[index]}") # RENAME FILE TO GLOBAL CSV os.rename(f'{file_path}{xlsx_file}',f"{file_path}global_csv.csv") # SAVE CDR INTO DATABASE # os.system("mysql -u root -p12341234 --execute='TRUNCATE ACCESS.global_csv;'") # os.system("mysql -u root -p12341234 --execute='SET GLOBAL local_infile=1;'") # os.system(f"mysqlimport -u root -p12341234 --local --fields-terminated-by=',' ACCESS {file_path}global_csv.csv") # os.system(f"mysql -u root -p12341234 --execute='CALL `ACCESS`.`ufone_imei_response`({req_id});'") # MOB IMEI RESPONSE MYSQL STORE PROCEDURE break else: print(f"not found {aparty}") # print(f"{cdr_number} not … -
I'm getting this error: ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiService -> _ApiService -> _HttpClient -> _HttpClient]
I have configured my ApiService with the HTTPClient and HttpHeaders and I am also using an Angular dependency injection to provide the HttpClient. But I kept encountering the same errors. I've already checked that the BrowserModule, AppRoutingModule and HttpClientModule imports were imported correctly and everything appears to be ok. Error Picture: ERROR: NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiService -> _ApiService -> _HttpClient -> _HttpClient]: My api.service.ts file: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseUrl = 'http://localhost:8000/'; httpHeaders = new HttpHeaders({'Content-Type': 'application/json'}); constructor(private http: HttpClient) { } getAllMembers() : Observable<any> { return this.http.get(this.baseUrl + 'members/', {headers: this.httpHeaders} ); }; } My app-routing.module.ts file: import { NgModule } from "@angular/core"; import { Routes, RouterModule } from '@angular/router'; import { MembersDetailComponent } from './members-detail/members-detail.component'; import { NewMemberComponent } from './new-member/new-member.component'; const routes: Routes = [ { path: 'member-detail/:id', component: MembersDetailComponent}, { path: 'new-member', component: NewMemberComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [ MembersDetailComponent, ] My app.module.ts file: import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppRoutingModule } from './app-routing.module'; import … -
What is difference between Celery Beats, Celery worker, Threads and Multiprocessors?
What is the difference between:- Celery beats and Celery Worker, and if Celery worker works just like threads or multiprocessors, why do we use celery worker especially? Thank you. I tried working with threads and Celery worker but found that threads is more clear and simple. -
Why is my Aleart Message not appearing after the user login wasn't correct? Django, html, css
This is the Script in my signIn.html {% if messg %} <script> aleart("{{messg}}"); </script> {% endif %} This is my Django View def postsign(request): email = request.POST.get("email") passw = request.POST.get("pass") try: user = auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials - try again" return render(request, "signIn.html", {"messg":message}) print(user) return render(request, "welcome.html", {"e":email}) def signIn(request): return render(request, "signIn.html") I was expecting an Aleart message on my screen that the Login was not correct. -
My Django models are saved, but the ImageField is not
I am using two classes to abstract the user in my system: the Django default User and my class Documentador. I treat them both as one on the interface side, and for creating a User and Documentador couple i use a Form passed to the template and deal with the data on the View to create and save both the models. My problem is: both models are saved without any errors, but the image in the Documentador class is not. I tried to create a Documentador model with an image in the Django admin, and it works. I also tested the fields that way: if not form.cleaned_data['foto']: return HttpResponseRedirect('/controle') and i was redirected to that path. I suppose is something with the form or the view, but can't find what. Form: class DocumentadorForm(forms.Form): foto = forms.ImageField(required=False) username = forms.CharField(label="Nome de usuário", max_length="20") first_name = forms.CharField(label="Primeiro nome", max_length="30") last_name = forms.CharField(label="Sobrenome", max_length="30") email = forms.EmailField() matricula = forms.IntegerField() password = forms.CharField(widget=forms.PasswordInput) my View: class UsuarioDocumentadorCreate(View): def get(self, request, *args, **kwargs): return render(request, 'mmrn/controle/crud_documentador/c_documentador.html', {'form':DocumentadorForm()} ) def post(self, request, *args, **kwargs): form = DocumentadorForm(request.POST, request.FILES) if form.is_valid(): f_foto = form.cleaned_data['foto'] f_username = form.cleaned_data['username'] f_first_name = form.cleaned_data['first_name'] f_last_name = form.cleaned_data['last_name'] f_email = form.cleaned_data['email'] … -
Can't render a plotly chart when using fetch
I have a chart that renders fine when loading the whole page, but if I use fetch to update data it doesn't render: Here are my views: def analytics(request): data = get_chart(60) context = { 'chart': data['chart'], } return render(request, 'app/analytics.html', context) def get_chart(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': data = get_chart(int(request.GET.get('interval'))) return JsonResponse({'chart': data['chart'], }) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') Here's template: <div class="row justify-content-start mb-2"> <div class="col"><a href="javascript:;" class="chart_scale" data-foo="1">1m</a></div> <div class="col"><a href="javascript:;" class="chart_scale" data-foo="60">1h</a></div> </div> <div class="row bg-light p-3 rounded justify-content-center align-items-center" id="chart"> {{chart|safe}} </div> <script type="text/javascript"> var chart = document.getElementById('chart') const chart_scales = document.getElementsByClassName('chart_scale') for (const button of chart_scales) { button.addEventListener('click', function (e) { url = '/analytics/update/?interval=' + e.target.dataset.foo fetch(url, { method: "GET", headers: { "X-Requested-With": "XMLHttpRequest", }, }) .then(response => response.json()) .then(data => { console.log(data['chart']) chart.innerHTML = data['chart'] }) }) } </script> I get the data both times, it's length is the same, but if I inspect the element after the fetch update I get empty div: <div id="my_chart" class="plotly-graph-div" style="height:768px; width:1024px;"></div> What am I missing? UPDATE The console output looks like this: Does the fact that half of it is red mean anything? -
How do you add viewflow to an existing django application
I have installed django-viewflow as per documentation. I have modified settings to add viewflow module. The workflow section of my admin pages has the process and tasks for viewflow. That is as far as I got. There is no viewflow.urls to include in my site.urls. I asked in the github discussion but the only reply was "just add the viewsets to your existing url configuration" but the example is their uquickstart demo and that was not helpful as the "demo" was empty. mysite.urls has from viewflow.contrib.auth import AuthViewset from viewflow.urls import Application, Site, ModelViewset ... vfsite = Site(title="Katacan", viewsets=[ Application( title='KTConnector', icon='people', app_name='KTConnector', viewsets=[ ModelViewset(model=User), ] ), ]) ... path('accounts/', AuthViewset(with_profile_view=False).urls), path('vf', vfsite.urls), I just need a little help on how to finish the install into my existing application. I feel that I am close but still no banana. Thanks MO -
Django with AWS S3, Debug False not working in production
I am using Django 4.2.5. I have deployed projects using Nginx, Docker, and AWS S3 before.But now, when Debug is True, there are no issues with AWS S3, but when Debug is set to False, CSS is not working. GET https://bucketname.s3-us-west-1.amazonaws.com/static/CACHE/css/output.bdb8c01056f5.css net::ERR_ABORTED 404 (Not Found) https://events.launchdarkly.com/events/bulk/88120c8d0102a7 net::ERR_BLOCKED_BY_CLIENT "This XML File Does Not Have Style Information" <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>static/CACHE/css/output.bdb8c01056f5.css</Key> <RequestId></RequestId> <HostId></HostId> </Error> I have configured the AWS S3 bucket policy, CORS, and made the necessary adjustments. I even created a new bucket and ran collectstatic with Debug set to False, but the issue persists. Any insights or solutions would be greatly appreciated.Thank you! AWS_S3_GZIP = True STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY =os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_FILE_OVERWRITE=False AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = False AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles") STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] -
Iterate through a list and create a html element for every item in the list?
I have a Model(Objectives) which stores the data I want to iterate through. Here is its code in the models.py class Objectives(models.Model): target = models.CharField(max_length=50) description = models.TextField(max_length=300) time_left= models.DateField() gamemodes= models.ForeignKey(User, on_delete=models.CASCADE) Here is my View.py for it. """@login_required""" def user_obj(request): modes_avalable = Task.objects.filter(gamemodes=request.user) print("__________________________________________________________") print(modes_avalable ) # Add this line for debugging return render(request, 'modes_avalable .html', {'modes_avalable ': modes_avalable }) and here is the html I have to iterate through the list: <div class="Q3" > {% for ab in user_obj%} <div class="task-item"> <h3>{{ ab.target }}</h3> <p>{{ ab.description }}</p> <p>Due Date: {{ ab.time_left|date:"F j, Y" }}</p> </div> {% endfor %} Essentially I need it to create a task-item for every objective, I have 4 objectives on the computer for testing so there is something to test on. I also have a user_obj.html file which has essentially the same code as the html code avove. -
Django: Duplicate action when I press Follow or Unfollow button
I am doing CS50w project4 problem, so I have to build a Social Media app. This problem has a part where in the profile of the user a follow and unfollow button has to be available. My problem is when I press the follow or unfollow button, this increase or decrease the followers and the people that the user follow. views.py def seguir(request): if request.method == 'POST': accion = request.POST.get('accion') usuario_accion = request.POST.get('usuario') usuario = request.user.username # Comprobación de si ya lo esta siguiendo y recuperación de información de usuarios perfil_usuario = User.objects.get(username=usuario) perfil_usuario_accion = User.objects.get(username=usuario_accion) esta_siguiendo = perfil_usuario.seguidos.filter(username=usuario_accion).exists() if accion == 'follow': # Si no lo esta siguiendo se añade a la lista de seguidos de uno y de seguidores del otro if esta_siguiendo == False: perfil_usuario_accion.seguidores.add(perfil_usuario) perfil_usuario.seguidos.add(perfil_usuario_accion) # Redirección a la página del usuario seguido return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) else: # Comprobación de que lo siga if esta_siguiendo: perfil_usuario.seguidos.remove(perfil_usuario_accion) perfil_usuario_accion.seguidores.remove(perfil_usuario) return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) profile.html {% extends "network/layout.html" %} {% block body %} <h1 id="titulo-perfil">{{ profile_user.username }} profile page</h1> <div id="contenedor-seguir"> <div id="seguidores">Followers: {{ profile_user.seguidores.count }}</div> <div id="seguidos">Following: {{ profile_user.seguidos.count }}</div> </div> {% if logged_user == 0 %} …