Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-channels 1.x detect when user leaves/refreshes page
How can I detect this? Currently I can only do_something if the user clicks a back button and I manually disconnect from the websocket under consideration. Sometimes Websocket DISCONNECT fires, but much of the time it doesn't. If a user refreshes or leaves a page, the disconnect code cannot run. How can I detect when a user leaves/refreshes? -
Callable to add to list_display that references extra field in the intermediary model of a M2M relationship
I have two models, Tender and Status, that have a many-to-many relationship with an intermediary model TenderStatus. TenderStatus has an extra date field which denotes the date on which each status was applied. I want to show all the statuses for each Tender in the list_display. I understand that I have to create a callable in my TenderAdmin class to include in list_display, and although I am able to list out the statuses, I'm having trouble accessing the date field in the intermediary model. Here's an abbreviated version of my models.py: class Tender(models.Model): name = models.CharField( max_length=255, null=False ) tender_status = models.ManyToManyField( 'Status', through='TenderStatus', related_name='tender_status' ) class Status(models.Model): status = models.CharField( max_length=50, null=False ) class TenderStatus(models.Model): tender = models.ForeignKey('Tender', on_delete=models.DO_NOTHING, blank=True, null=False) status = models.ForeignKey('Status', on_delete=models.DO_NOTHING, null=False) date = models.DateField(blank=True, null=False) And here's an abbreviated admin.py--note the status_list callable, this one works but it doesn't have the date in there. Any attempts I've made to access the date have not worked. class TenderAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = ['name', 'status_list'] def status_list(self, obj): return [x.status for x in obj.tender_status.all()] status_list.allow_tags = True I've tried this, but it can't find the date and returns a 500 error: def status_list(self, obj): return [str(x.date) + … -
Django Crispy_forms doesn`t load the correct layout
I spent a few hours trying to debug this error but could not find out why. I don`t have any errors message. I would like to display my form in two columns using the crispy forms layout. Goal: Display the forms with the layout defined in the forms.py file Issue: The layout doesn`t display as expected and list all fields on different lines. forms.py from crispy_forms.helper import FormHelper from .models import Project from django.core.exceptions import ValidationError from crispy_forms.layout import Layout, Submit, Row, Column, ButtonHolder class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['type','chantier','customer','contact'] def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) helper.form_method = 'POST' Row( Column('type', css_class='form-group col-md-6 mb-0'), Column('chantier', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('customer', css_class='form-group col-md-6 mb-0'), Column('contact', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) Createproject.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form %} {% block body %} <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} </form> {% endblock %} Many Thanks -
what am I doing wrong at the moment to validate my lesson class?
I want to validate if my lesson material belongs to a xyz user with pro right it will show the correct conent, but if not it will display become a member , but however I am getting if I change id membership to pro or vice versa it always true the statement def get(self, request): template = loader.get_template(self.template_name) template_member = loader.get_template(self.template_payment) #rendering the template in HttpResponse lesson = Lesson.objects.first() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): return HttpResponse(template.render()) else: return HttpResponse(template_member.render()) models class Lesson(models.Model): allowed_memberships = models.ManyToManyField(Membership) class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.email -
Custom User model in django. UNIQUE constraint failed: users_user.username
I am trying to make a custom registration form. Main idea is that users should use email as login method and be able to set username in profile(so I dont want to override username field). Problem with built-in django User model is that username field is required so I made my own model based on AbstractUser. Now when I am trying to register a new user I get "UNIQUE constraint failed: users_user.username". models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass forms.py from django import forms from .models import User class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, required=False) email = forms.EmailField(label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'email@example.com'})) password = forms.CharField(label='', max_length=100, widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) class Meta: model = User fields = ['username', 'email', 'password'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('trade') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) AUTH_USER_MODEL = 'users.User' is set I tried to set email unique=True in models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) Now I get "The view users.views.register didn't return an HttpResponse object. It returned None instead" instead. … -
Django urls and views properly defined, still showing 404 error
I have a blog which was running without any error. Different users can register, login, and post articles. Users can write/edit/delete comments on the articles. Previously, the URL of the articles were decided using 'article id'. Later, I read this tutorial and added slug along with id in the URL for every article's Detail View. Then I deleted my old articles since they didn't have any slugs. After this change, a user can create a comment successfully, but cannot 'edit' or 'delete' any comment. Whenever 'edit' or 'delete' button is pressed, 404 error is shown. See the error image by pressing this link. Page not found (404) Request Method: GET Request URL: http://localhost:8000/articles/33/comment_edit/ Raised by: articles.views.ArticleDetailView No article found matching the query My corresponding files are listed below: urls.py (inside Articles App directory) from django.urls import path from .views import (ArticleListView, ArticleUpdateView, ArticleDetailView, ArticleDeleteView, ArticleCreateView, CommentCreateView, CommentUpdateView, CommentDeleteView) urlpatterns = [ path('', ArticleListView.as_view(), name='article_list'), path('<int:pk>/<str:slug>/edit/', ArticleUpdateView.as_view(), name='article_edit'), path('<int:pk>/<str:slug>/', ArticleDetailView.as_view(), name='article_detail'), path('<int:pk>/<str:slug>/delete/', ArticleDeleteView.as_view(), name='article_delete'), path('new/', ArticleCreateView.as_view(), name='article_new'), #Comments below path('<int:pk>/<str:slug>/comment/', CommentCreateView.as_view(), name='comment_new'), path('<int:pk>/comment_edit/', CommentUpdateView.as_view(), name='comment_edit'), path('<int:pk>/comment_delete/', CommentDeleteView.as_view(), name='comment_delete'), ] I have tried and run the website by commenting out the url for comments, i.e., the last three lines above. The error … -
Gunicorn not loading environment file
I have a gunicorn service file that looks like this [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=afrinovate-admin Group=www-data EnvironmentFile=/etc/afrinovate/gunicorn.env WorkingDirectory=/home/afrinovate-admin/afrinovate ExecStart=/home/afrinovate-admin/.local/share/virtualenvs/afrinovate-VhxtDRfD/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ afrinovate.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target But when i try starting gunicorn i get this error about not SECRET_KEY empty, which is in the EnvironmentFile specified in the gunicorn file. File "/home/afrinovate-admin/.local/share/virtualenvs/afrinovate-VhxtDRfD/lib/python3.7/site- May 06 20:54:25 afrinovate-test-api gunicorn[7293]: raise ImproperlyConfigured("`enter code here`The SECRET_KEY setting must not be empty.") May 06 20:54:25 afrinovate-test-api gunicorn[7293]: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django 3.0: Unable to get username in template
I have issue is that in template, I automatically get access of username of Superuser (if that is logged-in) but not username of user based on Buyer (Model). User is getting registered and also can login (I can see it in database). But in template I am unable to get username of user other than superuser. I don't what i am missing here. So i am putting all code of view.py here. Also after user logging he sees bookrepo:home and i am using user logic in header.html (bookrepo:home extends header.html) I have model named Buyer in models.py file. And based on this model, two modelForm has made. This is code of model.py class Buyer(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # additional attributes contact = models.CharField('Contact #', max_length=16, unique=True, validators=[ RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number (Up to 15 digits) must be entered in the format: '+923001234567'." ), ], ) devices = models.CharField('Devices', unique=False, max_length=115, blank=True) picture = models.ImageField(upload_to=profile_pic_path, null=True,blank=True) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Meta: get_latest_by = '-user.date_joined' This is code of modelForms class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password') def clean(self): cleaned_data = super(RegistrationForm, … -
DRF-Filtering with multiple query params and foreign keys
I'm new to Django and I'm trying to create a route that can be called to retrieve an array of vehicles from my database, but I want the user to be able to provide multiple query params in the url (something like: http://127.0.0.1:8000/vehicles/?year=2020&make=Toyota). The problem that I have come across is that my vehicle model includes references to foreign keys for the make and the v_model (so named to avoid conflict with the Django "model"). I have a solution that doesn't seem very graceful. The fact that I have three nested conditional statements for each search field makes me suspicious. I tried using "filters.SearchFilter" but I was only able to provide a single value on which to base the search. So a request like this: http://127.0.0.1:8000/vehicles/?search=2020&search=Toyota would only search for vehicles with a make of "Toyota", ignoring the "year" parameter. Is there some other way to do this that is cleaner or more "Django-approved"? Here is my code: models.py: class Make(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class VModel(models.Model): name = models.CharField(max_length=200, unique=True) make = models.ForeignKey(Make, on_delete=models.CASCADE) def __str__(self): return self.name class Vehicle(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) v_model = models.ForeignKey(VModel, on_delete=models.CASCADE) year = models.CharField(max_length=5) def __str__(self): return self.year … -
Django form wokrs first time but not the rest
I have a Django form to filter a queryset. I use a MultipleChoiceField there. The first time I execute the form it works fine but after that it looks like it has all the options checked. I added a message line within the form part in the view only if I have both values. The second time I run the form it gets printed. Thanks in advance! The Form class FilterEmpresaFulbergForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FilterEmpresaFulbergForm, self).__init__(*args, **kwargs) self.fields['Nombre'].required = False self.fields['pais'].required = False self.fields['company_type'].required = False company_type = ( ('Client', 'Client'), ('Supplier', 'Supplier'), ) mis_clientes = forms.BooleanField(required=False, initial=False, label='Extra cheeze') company_type = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=company_type, required=False) class Meta: model = Contactos_Fulberg fields = ('Nombre', 'pais') def save(self, commit=True): return super(FilterEmpresaFulbergForm, self).save(commit=commit) The view @login_required def EmpresasFulbergView(request): page_title = str("Empresas") now = date.today() - timedelta(days=365) filter_form = FilterEmpresaFulbergForm(request.POST) empresa_form = EmpresaFulbergForm(request.POST) if request.user.groups.filter(name="Dirección").exists() or request.user.groups.filter(name="Comex").exists(): all_contact = Contactos_Fulberg.objects.all() else: all_contact = Contactos_Fulberg.objects.filter(propietario=request.user) total_listado = all_contact.count() alerta_desde = date.today() - timedelta(days=90) if request.method == "POST" and 'filtro' in request.POST: filter_form = FilterEmpresaFulbergForm(request.POST) if filter_form.is_valid(): Nombre = filter_form.cleaned_data['Nombre'] if Nombre: all_contact = all_contact.filter(Nombre__icontains=Nombre) pais = filter_form.cleaned_data['pais'] if pais: all_contact = all_contact.filter(pais__icontains=pais) mis_clientes = filter_form.cleaned_data['mis_clientes'] if mis_clientes: all_contact = all_contact.filter(propietario=request.user) company_type = filter_form.cleaned_data['company_type'] if … -
How to perform a post request on django restframework viewset.ViewSet
I am trying to perform a post request using axios to my django backend. It's giving me an error 401 Unauthorized. JavaScript Frontend saveArticle(){ let that = this; axios .post("http://localhost:8000/api/articles/", { headers: { Authorization: `Bearer ${that.$store.getters.accessToken}` }, title: that.title, content: that.content }) .then(response => { console.log(response) }); } Python Backend class ArticleViewSet(viewsets.ViewSet): """ API endpoint that allows articles to be viewed or edited """ def list(self, request): queryset = Article.objects.all().order_by('-date') serializer = ArticleSerializer(queryset, many=True) return Response(serializer.data) #Getting one article by providing it's id def retrieve(self, request, pk=None): queryset = Article.objects.all() article = get_object_or_404(queryset, pk=pk) serializer = ArticleSerializer(article) return Response(serializer.data) #Create new article def create(self, request): print(request.user) return Response({"message": "Article saved"}) #Edit article def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): queryset = Article.objects.all() article = get_object_or_404(queryset,pk=pk) article.delete() return Response({"message": "Deleted"}) def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires """ if self.action == 'list': permission_classes = [permissions.IsAuthenticated,] if self.action == 'create': permission_classes = [permissions.IsAuthenticated,] else: permission_classes = [permissions.IsAdminUser,] return [permission() for permission in permission_classes] I am using JWT tokens to authenticate. Listing the articles is working but posting data to create one is not working. I am not really … -
Passing a dictionnary in a template in Django
I need to pass a dictionnary which I generate in my views.py to my template in Django. template {% for server in servers %} <div class="hs-item set-bg" data-setbg="{% static 'img/slider-1.jpg' %}"> <div class="hs-text"> <div class="container"> <h2>The Best <span>Games</span> Out There</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada <br> lorem maximus mauris scelerisque, at rutrum nulla dictum. Ut ac ligula sapien. <br>Suspendisse cursus faucibus finibus.</p> <a href="#" class="site-btn">Read More</a> </div> </div> </div> {% endfor %} views.py def get_data(request, server_name): server=Server.objects.get(Name=server_name) address = (server.IP, server.Port) connect = "steam://connect/"+str(server.IP)+":"+str(server.Port) queryset=a2s.info(address, timeout=3.0, encoding=None) max_player=queryset.max_players current_player=queryset.player_count current_map=queryset.map_name playerdata={ 'map': current_map, 'players': current_player, 'adress': connect, 'max': max_player, } return HttpResponse(playerdata) models.py class Server(models.Model): Name = models.CharField(max_length=100) IP = models.TextField() Port = models.IntegerField() Image = models.ImageField(default='default.jpg', upload_to='server_pics') def __str__(self): return str(self.Name) if self.Name else '' What I'm trying to do here, is to loop over all the servers in my template, then, for each server, query said server using a python script, putting the value in a dictionnary, i.e player_count, current_map, etc, then displaying those informations in my template. My problem is that, i don't know how to return said dictionnary to the template. I've already done something similar by using ChartJS, using JsonResponse … -
I'm suddently not able to run server manage.py django since I upgrade my PyCharm
I can run server to test my webapp. Since I upgrade my PyCharm I cant run it. I dont know how to do Bellow is the error output Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop next(ticker) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 347, in tick for filepath, mtime in self.snapshot_files(): File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 363, in snapshot_files for file in self.watched_files(): File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 262, in watched_files yield from iter_all_python_module_files() File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\migue\PycharmProjects\research4medjango\venv\lib\site-packages\django\utils\autoreload.py", line 139, in iter_modules_and_files if not path.exists(): File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 1291, in exists self.stat() File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 1111, in stat return self._accessor.stat(self) File "C:\Users\migue\AppData\Local\Programs\Python\Python35-32\lib\pathlib.py", line 371, in wrapped return strfunc(str(pathobj), *args) OSError: [WinError 123] … -
How to convert Python List of numbers to json object
I want to convert python list of numbers to a json object. input: my_list = [22,30,44,55] output: { "budget" : 22, "budget" : 30, "budget" : 44, "budget" : 55 } -
Django Rest Framework populating data in template from API endpoint
Is there some specific way to populate data in django template from api endpoint? So i have a ajax call that calls a specific endpoint i technically could populate that data with js in success response, but are there any better ways of doing it? Even if no, is the approach of populating that data with js in success response even a decent approach? -
How can I attached title, content and date on the template
I am beginner in programming world. As for now I am following a video to create a blog with django. But, I have problem attaching the title, content, author and date on the template which I had downloaded from colorlib. I used the method below in the index.html file but they do now show: ''' {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="row"> <div class="col-12"> <div class="section-title"> <h2>Editor's Pick</h2> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="post-entry-1"> <a href="#"><img src="{% static 'images/img_h_1.jpg' %}" alt="Image" class="img-fluid"></a> <h2><a href="{{ obj.title }}"></a></h2> <p>{{ obj.overview }}</p> <div class="post-meta"> <span class="d-block"> <a href="#">{{ obj.author.user.username }}</a> in <a href="#">{{ cat }}</a></span> <span class="date-read">{{ obj.timestamp|timesince }} ago<span class="mx-1">&bullet;</span> 3 min read <span class="icon-star2"></span></span> </div> </div> </div> {% endfor %} ''' -
Listing answers for question(get_object_or_404) in for loop. How can I get each answer also as an object in one def?
I am sorry if my title doesn't make much sense for you. I have a problem and I have a problem with describing it. I will be very grateful if you could help me. I have small voting system for my question objects. My questions have many answers that I am listing in "question_details" in for loop. I can of course access question model and therefore get informations about votes for question but I am unable to do the same for each answer. Maybe some code to better illustrate: views.py: def questiondetails(request, question_pk): question = get_object_or_404(Question, pk=question_pk) question_form_id = question total_voteup = question.total_voteup() total_votedown = question.total_votedown() is_voteup = False is_votedown = False if question.voteup.filter(id=request.user.id).exists(): is_voteup = True if question.votedown.filter(id=request.user.id).exists(): is_votedown = True I can check about of votes, and I can check if user vote up or down. in templates of questiondetails I am doing something like that: {% for answer in question.answer_set.all %} {{ answer }}<br> <div id="answer_voting_section"> {% include 'main/partials/answer_voting_section.html' %} </div> {% endfor %} And with that. I can click on my question, it will trigger "questiondetails" and bring me to it's page with question and answers coming from this for loop. And my problem is, that … -
Not possible to connect with http://127.0.0.1:8000/
I am trying to connect with the server http://127.0.0.1:8000/ (Django) but the only result is like below...: see print screen any ideas what went wrong? -
Generate automatic records in a table in Django even if the system is not being used
Does anyone know a way to generate a record in a table without the system being used by the user? I need to generate something similar to a notification or reminder, with various data obtained from other tables, something similar to a report Thank you -
Django contact form not working. GMAIL not recieving message
*****Hi Folks, I am a new Django. please help me to solve this issue. I am trying to use a simple contact form using Gmail configuration. When users click sends message button it reloads to should reload to the home page and should send messages to hosted email. I don't get any email with this process. I don't understand where I am going wrong.***** Forms.html {% extends 'base.html' %} {% block content %} <form action="{% url 'home' %}" method="post" id="contactForm" name="sentMessage" novalidate="novalidate"> <!-- --> {% csrf_token %} <div class="row align-items-stretch mb-5"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" type="text" name="message_name" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name." /> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="message_email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address." /> <p class="help-block text-danger"></p> </div> <div class="form-group mb-md-0"> <input class="form-control" id="phone" type="tel" name="message_phone" placeholder="Your Phone *" required="required"/> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group form-group-textarea mb-md-0"> <textarea class="form-control" id="message" name="message_text" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea> <p class="help-block text-danger"></p> </div> </div> </div> <div class="text-center form-group"> <div id="success"></div> <button class="btn btn-primary btn-xl text-uppercase" id="sendMessageButton" type="submit">Send Message</button> </div> </form> {% endblock content %} view.py File from django.shortcuts import render … -
How to Implement Image recognition system in Website using Django?
I have made an image recognition system using python and I am trying to implement that in website. I have have a system that recognizes the fruit images built using CNN. Now, I have built a website which is of a Fruit-blog. I want a section or a page in in that website in which a user can upload an image and the website can recognize which fruit is the given image of but I have no idea how to implement my recognition system in the website. Can you please help me explaining what to do and how can I implement the AI from python to Django website? -
Reverse Accessor for "CustomPAM.groups' clashes with reverse accessor for 'CustomUser.groups
I'm working on a django project for school. We pretty much have to build a program that allows users to answer peer assessments. In my django project, I currently have two models in separate apps. One model is to save user info, and the other is to save the peer assessments. Both the Models are below. mysite/PAM/models.py from django.db import models from django.contrib.auth.models import AbstractUser from datetime import datetime # Create your models here. class CustomPAM(AbstractUser): date_created=models.DateField(auto_now_add=True) starting_date=models.DateField(default=datetime.now, editable=True) deadline_date=models.DateField(null=True, editable=True) question1=models.TextField() question2=models.TextField() question3=models.TextField() question4=models.TextField() question5=models.TextField() question6=models.TextField() question7=models.TextField() question8=models.TextField() question9=models.TextField() question10=models.TextField() answer1=models.PositiveIntegerField(max_length=1, null=True, editable=True) answer2=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer3=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer4=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer5=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer6=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer7=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer8=models.PositiveIntegerField(max_length=1,null=True, editable=True) answer9=models.TextField(null=True, editable=True) answer10=models.TextField(null=True, editable=True) assessmentFrom = models.EmailField(unique=False) assessmentFor=models.EmailField(unique=False) def __unicode__(self): return self.assessmentFrom and mysite/myusers/models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class CustomUser(AbstractUser): username=models.CharField(max_length=50, unique=True) name=models.CharField(max_length=150) eagle_id=models.PositiveIntegerField(unique=True, null=True) email=models.EmailField(max_length=150, unique=True) password=models.CharField(max_length=80) is_student=models.BooleanField(default=False) is_professor=models.BooleanField(default=False) is_TA=models.BooleanField(default=False) team_number=models.PositiveIntegerField(default=0,null=False, editable=True) def __str__(self): return self.name #the next four lines are for generating tokens @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.get_or_create(user=instance) the users model is one I made a few weeks ago, the Peer Assessment Model is the … -
What tools do I need to use for a web application [closed]
So I'm teaching my self how to create web applications, like a blog. I'm currently just learning and have built some pages with HTML and CSS(with bootstrap), and I'm using Django. I'm wondering where do tools like React, MongoDB, Node.js come into play. Does Django cover all these things? To sum things up, I'm confused as to what tools you need. It would be great if you guys could break it up into categories, like the front-end framework, explain what it does, and give some examples of tools. I know there are groups of tools people use like the ones in MEAN stack, but I really don't get what they do. -
How to pass the request object on to setup(request, *args, **kwargs) of a FormView through Url
The url: path('signup/', SignUp.as_view()(request), name='signup'), the class whose request attribute i want to initialze with setup : class Login(FormView): template_name = 'products_app/login.html' form_class = UserLoginForm success_url = reverse_lazy('index') -
Django Rest Framework, getting error : 'NoneType' object has no attribute
I created a blog where people can do Post,comment and likes to post. When I POST new posts I get error AttributeError at /api/posts/ 'NoneType' object has no attribute 'user' ,error occur at serializers.py in get_user_has_voted, line 20. even though I get error , I am able to POST data and all other functionalities works fine. Why does the error happens ? How can I debug it ? SERIALIZER.PY class PostSerializers(serializers.ModelSerializer): comments = serializers.HyperlinkedRelatedField(many=True,read_only=True,view_name = 'comment_details') likes_count = serializers.SerializerMethodField() user_has_voted = serializers.SerializerMethodField() class Meta: model = Post fields = '__all__' #exclude=('voters',) def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() # line 20 MODELS.PY class Post(models.Model): title = models.CharField(max_length=60) body = models.CharField(max_length=60) file = models.FileField(null=True,blank=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="votes",null=True,blank=True) There are duplicate questions in Stack overflow but with different scenarios, as a begginer I couldn't grasp the idea.