Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I am trying to use django-newsletter, I have error while trying to install according to docs
I was trying to create a subscription app in django, so I try to use the django-newsletter. But I have some error and I don't know why. ./manage.py runserver It was giving me error like this: File "./manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax My urls.py code: urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), url(r'^newsletter/', include('newsletter.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newsletter', ] -
How to save all students grade to the database using Django?
i hope the title is enough to know what is my problem This is my code in html when I tried to save this to my database only the "6" is save just like in the picture I use jquery to generate the date and textbox to input the grade this is my html <table id="blacklistgrid" border="2px"> <tr> <th id="th">Students Name</th> <th data-id='headers' id='header'>Average</th> </tr> {% for student in teacherStudents %} <tr class="tr2"> <td class="td" ><input type="text" name="students" value="{{student.id}}" id="student" >{{student.Students_Enrollment_Records.Student_Users}}</td> <td data-id='row' id="ans"><input type='number' class='averages' readonly/></td> </tr> {% endfor %} </table> <script> var counter = 0; function doTheInsert(){ let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#th').after("<th data-id='headers' id='header'><input type='date' name='date'></th>"); var rows=$(".tr2"); $("<td data-id='row' ><input type='number' name='gradeko' class='average' /></td>").insertAfter(".td"); counter++; } </script> this is my views.py for gradeko in request.POST.get('gradeko'): pass for students in request.POST.getlist('students'): studentss = StudentsEnrolledSubject(id=students) date = request.POST.get('date') V_insert_data = studentsEnrolledSubjectsGrade( Teacher=teacher, Students_Enrollment_Records=studentss, Date=date, Grade=gradeko ) V_insert_data.save() -
from django.urls import ( # noqa ModuleNotFoundError: No module named 'django.urls'
I am getting error "No module named 'django.urls'" in django 1.9 The problem is with urls.py in the application urlpatterns = [ ... url(r'^', include("posts.urls", namespace='posts')), url(r'^api/posts/', include("posts.api.urls", namespace='posts-api')), ... ] The only url code specified below causes error. After commenting this line of code, django server runs fine. url(r'^api/posts/', include("posts.api.urls", namespace='posts-api')), -
How to write view in django to display friend_request which are sent from logged in user?
my view to display friendlist: def friend_list(request): context = { 'results_from_user': Friend.objects.filter(from_user=request.user), 'results_to_user': Friend.to_user } # print(context) return render(request, 'friend/friend_list.html', context) -
i want import my file in python but can't import
first, i typed 'from awsdjp.boardapp.views' import * ' but error occured. error is 'ModuleNotFoundError: No module named 'awsdjp.boardapp'' i was googling about this issue . next, i tpyed import sys sys.path.insert(0,"C:\Users\USER\PycharmProjects\djangoProj\") that path is my directory's absolute path and run but don't work .... 'from awsdjp.boardapp.views import *' part is not recognized. enter image description here -
Unable to get url_parts from the website
I am trying to get the url_parts from a website that is sending oauth_signature which will further give me query_string such as : query_string= url_parts.query I used the following url_parts = urlparse(request.build_absolute_uri()) But it returned the localhost address. ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/lti11/', params='', query='', fragment='') How can I get the url of the website that sent the POST request ? -
Django ModelForm saying image field is required while submitting even when a valid image is provided
I am trying to use a ModelForm to save objects to the database. I have also added an ImageField. Through the admin panel, I am easily able to add objects with an image but every time I submit the ModelForm with the same image it doesn't get saved and returns an error saying "This field is required" (screenshot and code attached). How do I fix this? Here's a screenshot of the error: The models file: from django.db import models from django.conf import settings class Book(models.Model): rel_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Posted By") image = models.ImageField(verbose_name="Image", upload_to="static/Books/img") title = models.CharField(max_length=256, verbose_name="Title") description = models.TextField(verbose_name="Description") price = models.IntegerField(verbose_name="Price") state = models.CharField(max_length=256, verbose_name="State") city = models.CharField(max_length=256, verbose_name="City") neighbourhood = models.CharField(max_length=256, verbose_name="Neighbourhood") phone = models.IntegerField(verbose_name="Phone Number") def __str__(self): return self.title + f" ({self.rel_user.username})" The forms file: from django.forms import ModelForm from Books.models import Book class BookForm(ModelForm): class Meta: model = Book fields = ['image', 'title', 'description', 'price', 'state', 'city', 'neighbourhood', 'phone'] The views file: from django.shortcuts import render, redirect from Books.forms import BookForm from django.contrib import messages from Books.models import Book def sell(request): if request.method == "GET": form = BookForm() else: form = BookForm(request.POST) form.instance.rel_user = request.user if form.is_valid(): form.save() messages.success(request, "Successfully added!") return redirect('sell') … -
How to aggregate with prefetch related and prefetch
I Have two models clinic and ClinicCredits: I want a list of clinics withsum of available balance The Problem is if i use annotate i have to loop for avalibale alance with queryset of cliniccredits : class Clinic(models.Model): """ clinic model """ user = models.OneToOneField(User, related_name="clinic", primary_key=True, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: db_table = 'clinic' class ClinicCredits(models.Model): """ credit details for clinic """ clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, related_name='c_credits') credits = models.FloatField('credits', default=0.0) balance = models.FloatField('balance', default=0.0, help_text="balance after deduction of credits") def __str__(self): return self.clinic.name class Meta: db_table = 'clinic_credits' here is my query to fetch clinic: clinics = Clinic.objects.filter(practice_id__in=user.dietitian.practiceid).order_by( 'user__date_joined').prefetch_related(Prefetch('c_credits',ClinicCredits.objects.filter(balance__gt=0),'credit_')) and how can i use aggregate in this condition or is there some oter way to retreive clinic list with their available credits. -
django.db.utils.OperationalError: no such table Django 2
what I did 1.I deleted the database 2.deleted the pycache files and the migrations files 3.python manage.py makemigrations app_name and python manage.py migrate app_name 4.close the server several times But this is the error I received enter image description here settings.py INSTALLED_APPS = [ 'blog', 'users', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) blog/models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) -
How to create datetime filter using Django Rest Framework Filters
I am trying to create the datetime filter but my class is not working as expected. I have used this package to do so. I am not getting any error but also I am not getting any error also, Here is my filter class : import rest_framework_filters as filters from core import models class FeedFilter(filters.FilterSet): timestamp_gte = filters.DateFromToRangeFilter() class Meta: model = models.MQTTFeedWeather fields = { 'created_at': ('lte', 'gte') } Model Class : class MQTTFeedWeather(models.Model): sensor = models.ForeignKey( 'SensorDevice', on_delete = models.CASCADE ) feed = models.TextField() created_at = models.DateTimeField(auto_now_add=True) And my views as : class DeviceFeedListAPI(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAuthenticated,) queryset = models.MQTTFeedWeather.objects.all() serializer_class = serializers.WeatherFeedSerializer pagination_class = pagination.PostLimitOffsetPagination filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filter_class = filters.FeedFilter search_fields = ('feed',) I want to create a datetime filter on created_at table. When I am running the url : http://172.61.25.51:8080/api/admin/application_feed/?created_at__range=2019-12-01,2020-01-08 Its not filtering the data. Can any body help me what i am doing wrong here!! Thanks! -
Django Storing "State" and Objects for Use Across Several Views
I am new to OOP and web development and am getting used to the definition of objects and such to hold data. I also have a bit of experience with creating basic html websites and doing some state management using React and JS. However, currently I am currently creating a Django website to practice both my OOP skills and Django skills, and I have hit a bit of a snag. When the homepage of my website loads, a fetch is made to an API that fetches JSON from a server with details such as title, author, and published date. I iterate over the JSON and create a series of Post() objects that contain that information. The Post objects (which are contained in a list at this point) are then passed into the render method in a function in my views.py and then iterated over and the title property is displayed on the html page as a link. I want to store the other properties (author and published date) as metadata somehow in the background. The information always comes from the API, and I do not want to store it in a model on the db. I want to use that … -
Python List into Django model
I want to add an ip list (ex. ['192.168.0.1','...',]) into Django Model TextField. I don't know the serializer and validator well, so I keep getting the error 'not a valid string'. How can I change it? -
Django Full Text SearchVectorField obsolete in PostgreSQL
I'm using Django's inbuilt full text search with PostgreSQL. The Django docs say that performance can be improved by using a SearchVectorField. That field keeps a pre-generated ts_vector column with all the relevant lexemes alongside the model, rather than generating it on the fly during every search. However, with this approach the ts_vector must be updated whenever the model is updated. To keep it synchronised, the Django docs suggest using "triggers", and refer us to the PostgreSQL documentation for more details. However, the PostgreSQL docs themselves say that the trigger approach is now obsolete. Instead of manually updating the ts_vector column, it is better to keep the column automatically up-to-date by using a stored generated column. The question is: How can I use PostgreSQL's recommended approach with Django? My current solution is not ideal: use the SearchVectorField to create the column, and then manually go into PostgreSQL and replace the Django-generated column with a stored generated column. Is there a better way? -
How to save all students name in the database using Django?
I have this code from my html {% for student in teacherStudents %} <tr class="tr2"> <td class="td" ><input type="text" name="student" value="{{ student.id }}" hidden>{{student.Students_Enrollment_Records.Student_Users}}</td> <td data-id='row' id="ans"><input type='number' class='averages' value="{{student.id}}" readonly/></td> </tr> {% endfor %} this is my code in my views.py def grade(request): id = request.POST.get('teacher') teacher = EmployeeUser(id=id) students = request.POST.get('student') studentsKo = StudentsEnrolledSubject(id=students) V_insert_data = studentsEnrolledSubjectsGrade( Teacher=teacher, Students_Enrollment_Records=studentsKo, ) V_insert_data.save() return render(request, 'accounts/pending.html') my problem is only one students name save in my database, just like the picture below -
Django view doesn't contain a HTTP_REFERRER header
I'm testing a view that is accessing request.META where I want to get the HTTP_REFERRER header. The purpose being that I want to redirect to a previous page in case the queryset within the search_list view returns empty. A referring page happens to contain a form which is submitted through a GET request. The cleaned data is then passed to search_list as a query string. When testing the view, all test assertions pass. However when I python manage.py runserver and simulate the test case I get an error: KeyError at /minerals/search; 'HTTP_REFERRER'. I'm trying to understand why I'm getting a KeyError when running the server? test_views.py class SearchFormResults(TestCase): def test_user_search_query_fail(self): response = self.client.get( reverse("minerals:search_list"), data={'query': 'Kryptonite'}, HTTP_REFERRER=reverse( "minerals:letter_list", kwargs={'query': 'N'} ), follow=True ) self.assertRedirects(response, reverse( "minerals:letter_list", kwargs={'query': 'N'} ) ) self.assertTemplateUsed("minerals/list.html") self.assertEqual(response.status_code, 200) self.assertContains(response, "No minerals exist with the provided search.") views.py def search_list(request): search_query = request.GET.get('query') matched_minerals = Mineral.objects.filter( Q(name__icontains=search_query)| Q(image_caption__icontains=search_query)| Q(category__icontains=search_query)| Q(formula__icontains=search_query)| Q(strunz_classification__icontains=search_query)| Q(crystal_system__icontains=search_query)| Q(unit_cell__icontains=search_query)| Q(color__icontains=search_query)| Q(crystal_symmetry__icontains=search_query)| Q(cleavage__icontains=search_query)| Q(mohs_scale_hardness__icontains=search_query)| Q(luster__icontains=search_query)| Q(streak__icontains=search_query)| Q(diaphaneity__icontains=search_query)| Q(optical_properties__icontains=search_query)| Q(group__icontains=search_query) ) if not matched_minerals: messages.info(request, "No minerals exist with the provided search.") previous_page = request.META["HTTP_REFERRER"] return HttpResponseRedirect(previous_page) else: search_form = SearchForm() return render( request, 'minerals/list.html', {'minerals': matched_minerals, 'form': search_form} ) -
django UniqueConstraint inherited tables
I have the following: class Parent(models.Model): field1 = models.CharField(max_length=20) field2 = models.CharField(max_length=20) field3 = models.CharField(max_length=20) class Meta: abstract = True constraints = [ models.UniqueConstraint(fields=("field1", "field2", "field3"), name='unique_stuff'), ] class Child1(Parent): pass class Child2(Parent): pass This will do a makemigrations ok but then fail to migrate, at least in Django 2.2. You have to provide a name (Django doesn't seem to want to auto-generate one). Is the only way to achieve this to have a Meta class in each child class and have a separately named constraint in each? Could I try and use some kind of name based on the type of the child class? What would be the most DRY way to do this? -
Django: when using selected_related, exclude some tables
I wonder if I can exclude specific tables when I use selecte_related. -
easy way to build django recommendation
Please i am new to machine learning,done with more than 11 hours of video tutorials but still not clear yet, please how can i build a recommendation system with django because i need to deliver a project before the end of this month.Please help me. i have already study django-recommends but still not clear. class Loopnote(models.Model): user=models.ForeignKey(AUTH_USER_MODEL,on_delete=models.CASCADE) body=models.TextField() created=models.DateTimeField(auto_now_add=True) like=models.ManyToManyField(AUTH_USER_MODEL,related_name='like') share = models.PositiveIntegerField(default=0) loop=models.IntegerField(null=True,blank=True) # comments = GenericRelation(Comment) # comments=models.ManyToManyField('Comment',null=True,blank=True) video=models.FileField(upload_to='Videos/',null=True, blank=True) photo=models.ImageField(upload_to='LoopPhotos/',null=True, blank=True) class Meta: verbose_name_plural = 'Loopnotes' ordering= ['-created'] get_latest_by = "-created" def __str__(self): return "%s loopnote" % self.user def get_absolute_url(self): return reverse('loopnote_detail', args=[str(self.pk)]) That is the model table that i will like to use recommendation for. Thanks in advance. -
How can I allow a user to only access a view once every 30 minutes in Django?
I am building an app that lets users update a webpage, but I want to restrict any user from being able to make updates every 20-30 minutes. Would I be able to simply add this logic to a view definition? @login_required def update_options(request): ... # logic to determine how much time passed since the user visited ... return render(request, 'main/update-options.html') -
ImportError raised when try to load crispy_forms
ImportError raised when trying to load ‘crispy_forms.templatetags.crispy_forms_field’: No module named ‘django.utils.lru_cache’ I get that error ^^ when i try to run the command below: heroku run python manage.py migrate I have checked that my crispy forms version = 1.8.1 Please help! -
What am I missing setting up channel layers?
I followed the django channel tutorial # channels redis_host = os.environ.get('REDIS_HOST', 'localhost') CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, }, } in my code it gives me this error. 2020-01-10 00:29:22,045 ERROR Exception inside application: [Errno 111] Connect call failed ('0.0.0.0', 6379) Am I supposed to set up my server somewhere? my procfile has this: web: daphne APbackend.asgi:application --port $PORT --bind 0.0.0.0 Do I change the port 6379 to $PORT? -
Trying to pass URL parameter to CBV to filter & return queryset
Your time is very much appreciated! I've spent all day on this, got past most errors except this ValueError: ValueError at /products/ invalid literal for int() with base 10: 'Protein' So somewhere along the line its trying to convert 'Protein' to an integer and obviously thats not cool. Please enlighten me! I just want to sort the products by category field to display as list. db traceback... def get_prep_value(self, value): from django.db.models.expressions import OuterRef value = super().get_prep_value(value) if value is None or isinstance(value, OuterRef): return value return int(value) … def contribute_to_class(self, cls, name, **kwargs): assert not cls._meta.auto_field, "Model %s can't have more than one AutoField." % cls._meta.label super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self views.py (category is ManytoMany relation with Item model) class BrowseProductsView(ListView): model = Item template_name = 'products.html' def get_queryset(self, **kwargs): queryset = Item.objects.filter(category__exact='Protein') return queryset urls.py... path('products/<str:category>/', BrowseProductsView.as_view(), name='browse-products') template... <a class="dropdown-item" href="{% url 'store:products' category='Protein' %}">Protein</a> -
Django login method gives recursion error
I tried making a custom authentication view that saves the user in the session using login(request, user) but it gives me maximum recursion depth exceeded while calling a Python object I tried importing the login method with from django.contrib.auth import login as django_login as to not confuse methods, but it still did not work. Authentication works just fine without the login method, but it doesn't save the user in the session, so it's no use. Here is the full views.py file: from django.utils.translation import ugettext as _ from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.views import APIView from rest_framework.response import Response from rest.models import User from .serializers import UserSerializer from django.contrib.auth import get_user_model from django.contrib.auth import authenticate as django_authenticate from django.contrib.auth import login as django_login from django.contrib.auth.hashers import check_password import json class UserCreateAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) class Authentication(authentication.BaseAuthentication): def authenticate(self, request): email = request.POST.get('email', None) password = request.POST.get('password', None) if not email or not password: raise exceptions.AuthenticationFailed(_('No credentials provided.')) credentials = { get_user_model().USERNAME_FIELD: email, 'password': password } user = django_authenticate(**credentials) if user is None: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) django_login(request, user) return (user, None) … -
How to parse an input value from django form to a python script that runs in the backend side of the server?
In a few words, I want the user to give a text input at a frontend form in order to define the dataset that wants to examine, for instance 'data.csv'. This 'data.csv' is passed as a string variable to a python function that needs to open the dataframe with the specific name. The error is: FileNotFoundError at / [Errno 2] File b'data.csv' does not exist: b'data.csv' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] File b'data.csv' does not exist: b'data.csv' The file data.csv is in the same directory with the file beta.py that calls the file in order to read it. Moreover, if I don't pass any value from the frontend side, but I just trigger the script, and instead of dataframe = pd.read_csv(file), I have dataframe = pd.read_csv('data.csv'), it gives me the same error, but if i execute the script from the command line, then everything runs just fine. So I can't figure why the script cannot locate data.csv if the trigger comes from the frontend. These are the codes. PS: Thank you all in advance so much for the help views.py def get_name(request): if request.method == 'POST': form = NameForm(request.POST) … -
modify .form-group attributes in django forms using cripsy
I noticed there is a margin in the .form-group class when uding django crispy forms. This creates an extra margin that I want to remove, how can I change that? When I inspect the element I find out that the cripsy field I am using is rendered in the browser like this: <div id="div_id_assurance" class="form-group"> And this form-group class has these attributes: .form-group { margin-bottom: 1rem; } I want to get rid of this margin-bottom, can I do it using self.fields['assurance'].widget.attrs.update({'SOMETHING' : 'SOMETHING'})?