Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
needs to have a value for field "id" before this many-to-many relationship can be used / Django
If you create clothes in admin, the above error "<Clothes: None: 0>" needs to have a value for field "id" before this many-to-many relationship can be used.. We also found that this error occurs on the save of the Clothes model. This problem seems to be that the pk value is not assigned, so I tried using primary_key=True, but it doesn't seem to be the case. I have one more question. The likes of the Post model are also the same code as the save of the Clothes model, but the Post model is created without any problems. For what reason? Below is the code of model.py from django.db import models # from django.contrib.auth.models import User from django.conf import settings # from server.apps.user.models import Profile class Clothes(models.Model): CATEGORYS =[ (0, '상의'), #상의 (1, '하의'), #하의 (2, '아우터'), #아우터 (3, '신발'), #신발 (4, '악세사리'), #악세사리 ] category = models.IntegerField(default=0,choices=CATEGORYS) img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d') save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Save', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) buying = models.TextField(null=True, blank=True) def __str__(self): return f'{self.pk}: {self.category}' #pk가 존재하지 않는것 같음. # class SavePeople(models.Model): class Post(models.Model): main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d') title = models.CharField(max_length=100) content = models.TextField() private = models.BooleanField(default=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) clothes = models.ManyToManyField(Clothes,related_name='Clothes') likes = models.ManyToManyField(settings.AUTH_USER_MODEL, … -
How to hide current image URL class-based view Django
I'm using class-based view and i have problem hiding my current image location in my page. here is my models.py card_image = models.ImageField( upload_to="buildings/main", null=True, verbose_name="Main picture" ) and this is my building.html {% csrf_token %} {% for field in form %} <div class="col-5"> {{ field.label_tag }} </div> <div class="col-5"> {{ field }} </div> {% endfor %} <img width="200vm" src="/media/{{ form.card_image.value }}"/> and this is the image of what I'm trying to hide(https://i.stack.imgur.com/1U4Yx.png) I had some research but all of them were changing the template {{image.url.value}} but I don't want to write anything outside my for loop -
Django ORM TruncDay works incorrectly
I'm trying to get time left till the day of an event using this annotation from django.db.models.functions import Now, TruncDay Events.objects.annotate(time_left=TruncDay("start")-Now()) where "start" is the column holding date and time when the event starts. Then if I print the "time_left" field of a resulting object I get wrong time which is bigger by my time zone shift. How can I fix that? -
AWS cognito required login in django rest api
I'm working on integrating aws congito login/register in a django react js app and i want to add the login_required decorator with cognito . Any kind of information will be appreciated -
Not able to save data from aDjango form: Django 4.1, Windows 10
I am working on a small student application. I designed a table for storing students' information in which those fields of information are requested at the first registration and those can be updated later or updated during the process. For example, a student's information can update in the process by putting on-hold (update the onhold field) in case that student has been absent for 3 weeks. Below is my code. ###Model.py from django.db import models from django.contrib import admin from django.utils.translation import gettext_lazy as _ class Student(models.Model): #std_matricule = models.CharField(verbose_name='Student matricule', max_length=6, null=False, unique=True, primary_key=True) std_matricule = models.CharField(verbose_name='Matricule', max_length=6, null=False, unique=True, blank=False, help_text='Matricule of the student') std_parents = models.ForeignKey(Parents, on_delete=models.DO_NOTHING, related_name='Parents', unique=False, default=1, verbose_name='Student parents') std_email = models.EmailField(verbose_name='Email', null=False, blank=True, help_text='Enter the email of the student or leave blank if not exist') std_password = models.CharField(verbose_name='Password', max_length=64, null=False, blank=True, help_text='Type the password with 6 characters minimum') std_surname = models.CharField(verbose_name='Surname', null=False, blank=False, max_length=64, help_text='Type the Surname of the student as in the birth certificate') std_firstname = models.CharField(verbose_name='First name', null=False, blank=True, max_length=64, help_text='Type the student first name') std_nickname = models.CharField(verbose_name='Student Nickname', max_length=64, null=False, blank=True, help_text='If exist, type student nickname here') class Sex(models.TextChoices): MALE = 'Male', _('Male') FEMALE = 'Female', _('Female') std_sex = models.CharField( … -
Using django-import-export: How to customise which fields to export Excel files
I just starting out using Django. I'm using django-import-export package and I tried to customize my Django admin panel in this page in order to choose which fields to export to excel file. Here is my admin model class CompanyAdmin(ImportExportMixin, admin.ModelAdmin): model = Company resource_classes = [CompanyResource] list_display = [ "name", "uuid", ] fields = [ "name", "email", ] def get_export_resource_kwargs(self, request, *args, **kwargs): formats = self.get_export_formats() form = CompanyExportForm(formats, request.POST or None) form_fields = ("name", "email", ) return {"form_fields": form_fields} Here is my model resource class CompanyResource(resources.ModelResource): class Meta: model = Company def __init__(self, form_fields=None): super().__init__() self.form_fields = form_fields def get_export_fields(self): return [self.fields[f] for f in self.form_fields] Here is my export form class CompanyExportForm(ExportForm): # what should i write here? is this the place that i should write the custom code eg: checkboxes where user have the options to export the 'name` or 'email' fields ?? I try to use the same way as in this post in order to achieve the same result. However, i have been stuck forever. -
Django deploy on AWS EB CLI
I'm trying to deploy a basic Django project on AWS using ElasticBean. I tried everything, but can't understand what mistake I have done. So I will summarise here all 'solutions' on the internet. Please help ! First of, this is my Django project: .ebextensions -django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: ebdjango.settings .elasticbeantalk branch-defaults: default: environment: eb-env global: application_name: ebdjango branch: null default_ec2_keyname: null default_platform: Python 3.8 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application settings.py ALLOWED_HOSTS = ['http://ebdjango-env.eba-b3pcnpc8.us-east-1.elasticbeanstalk.com/'] wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ebdjango.settings') application = get_wsgi_application() requirements.txt Django==3.2 gunicorn==20.1.0 There is nothing in my Django app, no templates, no modules. I created it to be able to upload it. I'm using Django 3.2 and Python 3.8 When loading the webpage (CNAME): 502 Bad Gateway / nginx/1.22.1 When looking the log file I see this error: web: ModuleNotFoundError: No module named 'ebdjango.wsgi' The entire project is available here: https://github.com/mkchmura/AWS-EB-CLI.git -
TypeError : expected bytes-like object, not HttpResponse
i am trying to send an email with pdf file attached. But I have an error when sending the email in my project django utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py def sendMail(request): pdf = render_to_pdf('cart/commande.html',context) subject, from_email, to = 'Message with pièce joint : N° 0001', 'aab@gmail.com', 'too@gmail.com' text_content = 'hello' html_content = '<p>hello, .</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach('commande_pdf',pdf,'application/pdf') msg.send() return render(request,'cart/succes.html') the error points to this line msg.send Noted the generation of the pdf file is OK, it must be attached to the email -
How to use stored procedure in Django
Recently, we started working on a Job portal website using the Django framework. And we got a requirement to use a stored procedure to update data at multiple tables. Can anyone suggest how to create and use the stored procedure in Django -
many to many field error __call__() missing 1 required keyword-only argument: 'manager'
enter image description hereFirst of all, sorry for using a translator as I can't speak English. I'm using the model and I keep running into problems with many to many. At first, I made it without giving an id value, but it seems that the id value is not entered, so when I put the id value directly, the same problem as above occurs. But in the Post model below, the same form of likes is used. Why? from django.db import models # from django.contrib.auth.models import User from django.conf import settings # from server.apps.user.models import Profile # Create your models here. class Clothes(models.Model): CATEGORYS =[ (0, '상의'), #상의 (1, '하의'), #하의 (2, '아우터'), #아우터 (3, '신발'), #신발 (4, '악세사리'), #악세사리 ] category = models.IntegerField(default=0,choices=CATEGORYS) id = models.IntegerField(primary_key=True) img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d') save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Pickitems', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) buying = models.TextField(null=True, blank=True) def __str__(self): return f'{self.id}: {self.category}' #pk가 존재하지 않는것 같음. # class SavePeople(models.Model): class Post(models.Model): main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d') title = models.CharField(max_length=100) content = models.TextField() private = models.BooleanField(default=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) clothes = models.ManyToManyField(Clothes,related_name='Clothes') likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Likes', blank=True) def __str__(self): return f'{self.pk}: {self.title}' def get_absolute_url(self): return f'/community/' #이거 나중에 detail page로 바꿔주세요 class Comment(models.Model): post = models.ForeignKey(Post, … -
How to connect views with forms Django
I have chained dropdown in views py and that`s all showing in html but how am i suppose to send them into my forms.py Bcs where im trying to save that form into database i got an error of validation bcs views functions are not connected to my form Im kinda tired of that function pls help me views.py @login_required def create_work_log(request): if request.method == 'POST': form = WorkLogForm(request.POST, user=request.user) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log = form.save() messages.success(request, 'Данные занесены успешно', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Ошибка валидации') return redirect('create_worklog') else: if request.user.is_authenticated: initial = { 'author': request.user } else: initial = {} form = WorkLogForm(user=request.user, initial=initial) context = {'form': form} return render(request, 'contractor/create_work_log.html', context) def contractor_object(request): contractor_guid = request.GET.get('contractor_counter') objects = ObjectList.objects.filter(contractor_guid__in=[contractor_guid]) context = {'objects': objects, 'is_htmx': True} return render(request, 'partials/objects.html', context) def contractor_section(request): objects_guid = request.GET.get('object') sections = SectionList.objects.filter(object=objects_guid) context = {'sections': sections} return render(request, 'partials/sections.html', context) forms.py contractor_counter = forms.ModelChoiceField( label='Контрагент', queryset=CounterParty.objects.none(), initial=CounterParty.objects.first(), empty_label='', ) contractor_object = forms.ModelChoiceField( label='Объект', queryset=ObjectList.objects.none(), initial=ObjectList.objects.first(), empty_label='', ) contractor_section = forms.ModelChoiceField( label='Раздел', queryset=SectionList.objects.none(), initial=SectionList.objects.first(), empty_label='', ) template.html <div class="mt-3"> {{ form.contractor_counter.label_tag }} {% render_field form.contractor_counter class='form-select mt-2' autocomplete='off' hx-get='/objects/' hx-trigger='change' hx-target='#objects' %} </div> <div id="objects" class="mt-3"> {% … -
serialiizer return always none. why?
serialiizer return always none. why?? creating custom models time? serialiizer return always none. why?? creating custom models time? views.py print password = None class UserLoginView(APIView): def post(self,request,format=None): serializer=UserLoginSerializer(data=request.data,) if serializer.is_valid(raise_exception=True): email=serializer.data.get('email') password=serializer.data.get('password') **print(password)** print(request.data) print(serializer.data) user=authenticate(email=email,password=password) print(user) return Response({'msg':'successful login'},status=status.HTTP_200_OK) Serializer.py file class UserLoginSerializer(serializers.ModelSerializer): email=serializers.EmailField(max_length=255) class Meta: model=User fields=['email','password',] extra_kwargs={ 'password':{'write_only':True}, } Models.py file class UserManager(BaseUserManager): def create_user(self, email, number,name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') if not number: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), number=number, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, number,name, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, number=number, password=password, name=name, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) number=models.CharField(max_length=10) name=models.CharField(max_length=30) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','number'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view … -
Authentication using GitHub is not using the primary email
Recently integrated GitHub authentication in my Django website and noticed that Python Social Auth is registering the users using a non-primary email address. How can that behaviour be modified? -
Why is my Django session working when I use Postman, but not when I use it via my React Frontend?
I'm currently working on a registration component for an application built using React with TypeScript and Tailwind CSS, Django and MongoDB. In my Django backend I have an app called login_register_app, which is used for registration functionality. I want to create a session that stores the id of the document when the document is created so that when the user is asked to add further details on the following page the correct document can be updated. So far, I have the following function for registration: @api_view(['POST']) def create_login(request): # parse json body = json.loads(request.body) # get email and password and confirm password email = body.get('email') password = body.get('password') confirm_password = body.get('confirm_password') email_is_valid = False password_is_valid = False error = '' # password must be at least 8 characters and contain digit 0 - 9, Uppercase, Lowercase and Special # character from list (#?!@$%^&*-) password_validation_pattern = re.compile('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$') # compare password to confirm password and regex pattern if password == confirm_password and re.match(password_validation_pattern, password): password_is_valid = True elif password == confirm_password: error = 'password is not valid. Requires at least one uppercase, lowercase, digit and special character [#?!@$%^&*-]' else: error = 'passwords do not match' # verify email does not already exist … -
Django - VSCode does not recognize foreign key related names and gives error
Post model has a foreign key to User model with posts as its related name. posts = user.posts.all() ^^^^^ Django works fine obviously. But the error in VSCode is annoying. How can I make VSCode know this is not an error? -
Getting 400 'bad request' for deployed django app with apach2 + mod_wsgi
I am running 2 django apps on same server (both are almost the same). First app is running without any issue in virtual env and prod mode. But for the 2nd deployed app I am getting the bad request error even its running in virtual env without any issue. I set 775 for the whole project and www-data as owner. My apache .conf file is <VirtualHost *:80> ServerName prod-domain.de <Directory /opt/myproject/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media/ /opt/myproject/mysite/media/ Alias /static/ /opt/myproject/mysite/base/static/ <Directory /static/> Require all granted </Directory> <Directory /media/> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error-myproject.log CustomLog ${APACHE_LOG_DIR}/access-myproject.log combined </VirtualHost> WSGIScriptAlias / /opt/myproject/mysite/mysite/wsgi.py WSGIPythonPath /opt/myproject/mysite/env/lib/python3.8/site-packages My settings.py DEBUG = True ALLOWED_HOSTS = ["prod-domain.de"] [...] STATIC_ROOT = BASE_DIR / 'base/static/' STATICFILES_DIRS = [BASE_DIR / 'myproject/static/', ] STATIC_URL = 'static/' # Base url to serve media files MEDIA_URL = 'media/' # Path where media is stored MEDIA_ROOT = BASE_DIR / 'media/' I played around a lot with apache conf and the settings.py but apache doesn't show any error in the logs and now I am stucked hardly. -
Uploading Files/Form with JQuery File Upload by blueimp
I am trying to understand how to use JQuery File Upload by blueimp. This is my test view with an Input from type file, a progress bar and a submit button. If I am selecting an Image in the Input, the value changes to undefined. What have I to do Upload this Image (and show the progression of the upload)? HTML with JQuery: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <input type="file" accept="image/png, image/jpeg"> </div> <div> <progress id="progress" value="0" max="100"></progress> </div> <div> <input type="submit"> </div> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="{% static 'blueimp/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'blueimp/jquery.fileupload.js' %}"></script> <script src="{% static 'blueimp/jquery.iframe-transport.js' %}"></script> <script type="text/javascript"> $('#form').fileupload({ url: '{% url 'upload' %}', sequentialUploads: true, dataType: 'json', type: 'POST', add: function (data) { console.log(data, data.result); }, progress: function (data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress').val(progress); if (progress === 50) { console.log('We made it half way...'); } else if (progress === 100) { console.log('We made it...'); } else { console.log(progress + '%'); } }, done: function(data) { console.log(data.result.name); }, fail: function () { console.log('Failed') } }); </script> </body> </html> My Views: def image_upload(request): … -
Python datetime.date.today() not formatting inside sqllite3
In my database query which is executed with the sqlite3 module I insert a new row of data which includes a date field. The problem is when getting todays date with datetime.date.today().strftime('%Y-%m-%d') which outputs '2023-02-06' (expected output), it changes inside the database to '2015'. Why does this happen? This is a Django project so that is where i created the model for the database. models.py class User(models.Model): ... date_joined = models.DateField('%Y-%m-%d') ... database.py def add_user(self, email, password): date = datetime.date.today().strftime('%Y-%m-%d') self.cursor.execute(f""" INSERT INTO App_user ('username','email','password', 'email_preference', 'region', 'date_joined') VALUES ('{username}', '{email}', '{password}', 'All', 'None', {date}) """) self.con.commit() -
Django include custom @property on ORM model into queryset for future use inside customer filters
Hey there and thank you in advance. I have defined custom property on my ORM model: class MyModel(BaseModel): optional_prop_1 = models.ForeignKey(Model, null=True) optional_prop_2 = models.ForeignKey(AnotherModel, null=True) optional_prop_2 = models.ForeignKey(DifferentModel, null=True) @property def external_reference(self): if self.optional_prop_1: return self.optional_prop_1 if self.optional_prop_2: return self.optional_prop_2 ... All those three fields have a common field that I want to access inside my custom filer query, but because external_reference is defined as "virtual" property I know that I cannot access it inside queryset, so when I do this it would actually work: queryset.filter(top_level_relation__my_model__external_reference__common_field="some_value") I think I got an idea that I need to somehow convert my "virtual" property into a field dynamically with custom models.Manager and with queryset.annotate() but this didn't seem to be working. I tried this: def _get_external_reference(model) -> str: if model.optional_prop_1: return "optional_prop_1" elif model.optional_prop_2: return "optional_prop_1" ... return "" def get_queryset(self): external_reference = _get_external_reference(self.model) return super().get_queryset().annotate(external_reference=models.F(external_reference)) But inside my custom filter I always get Related Field got invalid lookup: external_reference telling me that this field doesn't exist on queryset. Any ideas how to convert property (@property) into a field that I could use later inside queryset -
AJAX and Django, AJAX success not working
In an HTML page I have a table where one can drop items into and that is posted to the server via AJAX as follows: function drop(ev, el) { if (ev.target.tagName=="IMG") { return; } ev.preventDefault(); var data = ev.dataTransfer.getData("text"); el.appendChild(document.getElementById(data)); el.style.width = "168px"; var newWidth = document.getElementById(data); $.ajax({ type: 'POST', url: server_url + currentPath, data: { 'version': data }, success() { console.log(data, "ranked "); }, }); } on the same page, users submit an answer using a button which is linked to a function that sends a POST request to the server: function NextPage(){ answer = $("#justification").val(); if (answer.length < 10){ document.getElementById("warning1").innerHTML = "Please provide an answer"; } else { $.ajax({ type: "POST", url: server_url + currentPath, data: {'answer' : answer}, success: function () { window.location.href = server_url+ nextPath; } }); } } I can read the data from the post request on the server side (i.e., version and answer), and it gets saved as well, but then I cannot move to the next page, and there are no error messages; I noticed that the answer is now passed as a parameter on the URL; not sure what that means. I guess it gets stuck because of an error. I … -
Making a django model field readonly
I am creating a django DB model and I want one the fields to be readonly. When creating a new object I want to set it, but later if someone tries to update the object, it should raise an error. How do I achieve that? I tried the following but I was still able to update the objects. from django.db import models as django_db_models class BalanceHoldAmounts(django_db_models.Model): read_only_field = django_db_models.DecimalField(editable=False) Thank you -
Django don't makemigrations my apps after i install app in install applications Ubuntu(linux)
this is my installed applications ubuntu system ` INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stu', 'stu2', ] ` I get this error, if any one have solution, plz help me It is ubuntu system 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ python3 manage.py makemigrations stu 1. No installed app with label 'stu'. 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ python3 manage.py makemigrations stu2 1. No installed app with label 'stu2'. 1. ashish@ashish-MS-1050:~/Desktop/aculance/test1$ I tried many time to force migrations but it can't reconise my app and send me this error No installed app with label 'stu'. -
Comment relier ma base de données django avec ma page de connexion
Bonjour, Je dois faire un site en django et je dois relier ma abse données que j'ai créer en django avec la page de connexion de mon site c'est à dire que je dois extraire les informations de ma base de données pour pouvoir vérifier si les informations de connexions sont bonnes. MA base de données et composé d'un id , mots de passe , nom_complet Comment je dois m'y prendre Merci Bonjour, Je dois faire un site en django et je dois relier ma abse données que j'ai créer en django avec la page de connexion de mon site c'est à dire que je dois extraire les informations de ma base de données pour pouvoir vérifier si les informations de connexions sont bonnes. MA base de données et composé d'un id , mots de passe , nom_complet Comment je dois m'y prendre Merci -
Django - Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I am new to Django. I have been working based on the template from Mozilla: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website I have created a project called 'debtSettler'. And it has an app called 'home'. I have the following url mappings: ./debtSettler/debtSettler/urls.py: urlpatterns = [ path('home/', include('home.urls')), path('admin/', admin.site.urls), path('', RedirectView.as_view(url='home/')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ./debtSettler/home/urls.py: app_name = 'home' urlpatterns = [ path('', views.index, name='index'), path('clubs/', views.ClubListView.as_view(), name='clubs'), ] And views: ./debtSettler/home/views.py: from django.http import HttpResponse, HttpResponseRedirect def index(request): num_clubs = Club.objects.all().count() # The 'all()' is implied by default. num_members = Member.objects.count() context = { 'num_clubs': num_clubs, 'num_members': num_members, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class ClubListView(generic.ListView): model = Club def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(ClubListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['some_data'] = 'This is just some data' return context In the template, I have two urls that give the error: <a href=" {% url 'index' %} ">Home</a> <a href=" {% url 'clubs' %} ">All clubs</a> Reverse for 'index' not found. 'index' is not a valid view function or pattern name. If I add the my_app:my_view, it … -
Conection between chrome extension and django website
I am developing a Chrome extension that detect when a file is dowloaded, send it to a website (also created by me with Django) and after the website processed it, Chrome extension receives another file with some results. I would like to know how I could connect them. Does someone have any example or name of some technology that allows Chrome extension send and receive files from a website or server? Thank you in advance!