Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch not ordering properly
I have this Model class Profile(User): rg = models.CharField(max_length=20, null=True,blank=True) cpf = models.CharField(max_length=15, unique=True, null=True) about = models.TextField(_('about'),max_length = 10000, null=True, blank=True) knowledge = models.ManyToManyField(SubCategory, related_name="profile_knowledge") class Meta: verbose_name = _('profile') verbose_name_plural = _('profiles') db_table = 'pd_profile' permissions = ( ("view_all_users", "Can view user details"), ("edit_all_users", "Can edit user details"), ("search_profile", "Can search talents"), ("user_config", "Can access user config page "), ("add_users_permissions", "Can add global permissions to user"), ("export_user_data", _("Can export users data")), ) def __str__(self): return self.full_name And I Want to do a query through this Profiles like that: query = SearchQuerySet().all().models(Profile) t = query.filter(content=data.get('value')) if not t: suggestion = query.spelling_suggestion(data.get('value')) t = query.filter(content=suggestion) query = t query = query.order_by("full_name") My problem is, the order_by simples doesn't work... My query should return in alphabetical order but it doesn't. Am I doing something wrong? Thanks django-haystack==2.5.0 djangorestframework==3.3.2 elasticsearch==1.5.2 -
Django: manage.py makemigrations --> django.db.utils.OperationalError: no such table
What i did: - deleted the complete db. - deleted the content of the migrations folder then i did: python manage.py makemigrations. I get the above error message. I also did: - Pulled the github repo freshly - created venv - activated the venv - run python manage.py migrate it looks like as if the migrate command checks the complete sourcefiles for references to the non existing tables. I am out of ideas here. Error: python manage.py makemigrations Traceback (most recent call last): File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: newshows_setting The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/harald/Projects/newshows/.venv/lib/python3.6/site-packages/django/core/checks/urls.py", … -
Pass request to django inherited classes
I am overriding some methods of a popular package, django-activity-stream (I think the package is mostly irrelevant to this question). from app/urls.py I call TeamJSONActivityFeed urlpatterns = [ ... url(_(r'^feeds/organization/(?P<organization_id>.+)$'), TeamJSONActivityFeed.as_view(name='organization_stream')), ... ] TeamJSONactivityFeed then calls 'pass', which I am not too familiar with, and inherits from two other classes, OrganizationStreamMixin and JSONActivityFeed. class TeamJSONActivityFeed(OrganizationStreamMixin, JSONActivityFeed): """ JSON feed of Activity for a custom stream. self.name should be the name of the custom stream as defined in the Manager and arguments may be passed either in the url or when calling as_view(...) """ pass My issue is that I cannot seem to access/pass the request object in/to these inherited classes. How would I go about passing this in? Right now, self.request.user and request.user are AnonymousUser objects. class OrganizationStreamMixin(object): name = None def get_object(self,request): # this is printing Anonymous User pprint(str(self.request.user)) pprint(str(request.user)) return def get_stream(self): return getattr(Action.objects, self.name) def items(self, request, *args, **kwargs): return self.get_stream()(*args[1:], **kwargs) class JSONActivityFeed(AbstractActivityStream, View): """ Feed that generates feeds compatible with the v1.0 JSON Activity Stream spec """ def dispatch(self, request, *args, **kwargs): for i, v in kwargs.items(): print (" ", i, ": ", v) return HttpResponse(self.serialize(request, *args, **kwargs), content_type='application/json') def serialize(self, request, *args, **kwargs): pprint(str(self.request.user)) … -
Empty form doesn't show on the page
I am building custom user authentification logic on my site. I created MyUsermodel than created form from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm from .models import MyUser classCustomUserCreationForm(UserCreationForm): class Meta: model = MyUser fields = ('email',) Than in project level urls.py file i added the following path urlpatterns =[ path('login/',include('authorization.urls'),] Than in authorization/urls.py i created from django.urls import path from .views import login_form urlpatterns = [path(' ',login_form,name='login_form'),] In my view file i have the following method which if request == GET should return empty form and if form is_valid() it's redirect to another page from django.http import HttpResponseRedirect from django.shortcuts import render from .form import UserCreationForm def login_form(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): email = form.cleaned_data('email') password = form.cleaned_data('password') return HttpResponseRedirect('/thank/') else: form = UserCreationForm() return render(request,'registration/log.html',{'form':form}) And last piece is log.html {% extends 'main/base.html' %} <form action="{% url 'login_form' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> But when i run server and open http://127.0.0.1:8000/login/ I haven't anything no exceptions and haven't empty form itself -
How to paginate category
How do i paginate men_clothing_shirt, it is under Category. This is my code. def men_shirt(request): queryset_list = Category.objects.filter(name='man_clothing_shirt') paginator = Paginator(queryset_list, 1) page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { 'menshirtpaginator': queryset, } return render(request,'men_shirt.html', context) -
How do I get the number of flags and upvotes based on the models?
class PinViewSet(viewsets.ModelViewSet): queryset = pin.objects.annotate( flagscore=Sum(Case( When(flaggerstory__flagged=True, then=1), default=Value(0), output_field=IntegerField() )), upvotescore=Sum(Case( When(upvotestory__upvote=True, then=1), default=Value(0), output_field=IntegerField() )), ) permission_classes = [ permissions.AllowAny # permissions.IsAuthenticated, ] serializer_class = PinSerializer class PinSerializer(DynamicFieldsMixin, serializers.ModelSerializer): flagscore = serializers.IntegerField(read_only=True) upvotescore = upVoteStorySerializer(many=True, read_only=True) class Meta: model = pin fields = '__all__' class upVoteStory(models.Model): pin = models.ForeignKey( "pin", on_delete=models.CASCADE, null=True, related_name='upvotestory') upVoter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) upvote = models.BooleanField(default=False) class flagStory(models.Model): pin = models.ForeignKey( "pin", on_delete=models.CASCADE, null=True, related_name='flaggerstory') flagger = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) flagged = models.BooleanField(default=False) I want to get the number of people who has flagged the pin and number of people who upvote. The value of upvotescore = flagscore for some reason. If I add data to the model upvotestory while flagscore = 3 and upvotescore = 0, upvotescore would = 3 also -
How can i fix a GeoDjango OSError: undefined Symbol?
I have the following error with my Django project after doing yum upgrade a few days ago Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/joincic/GeoRouting/GeoRouting_2/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/home/joincic/GeoRouting/GeoRouting_2/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File … -
setting up form wizard in django
I've been following this stackoverflow solution to use Form Wizard, as this is my first time using form wizard. All of the below code belongs to app 'funds'. When trying to view the form in browser, i get the following error: KeyError at /funds/raise/medical/ '0' MODELS.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # this is many to one relationship, on_deleting user, campaign will also be deleted funds_for = models.CharField(max_length=200) relationship = models.CharField(max_length=200, blank=True) benefiary_name = models.CharField(max_length=200, blank=True) illness = models.CharField(max_length=200, blank=True) undergoing_treatment = models.CharField(max_length=200, blank=True) hospital = models.CharField(max_length=200, blank=True) campaign_title = models.CharField(max_length=200, blank=True) amount_required = models.IntegerField(null=True, blank=True) amount_desc = models.TextField( blank=True) campaign_duration = models.IntegerField(null=True, blank=True) mobile = models.CharField(max_length=10, blank=True) campaign_image = models.ImageField(default="profilepic.jpg",upload_to="campaign_pictures") campaign_desc = models.TextField( blank=True) terms = models.BooleanField(default=False) def __str__(self): return f'{self.user.username} campaign' FROMS.PY from django import forms from .models import Campaign class RaiseFundsFrom1(forms.ModelForm): class Meta: model = Campaign fields = ['funds_for','relationship','benefiary_name','illness','undergoing_treatment','hospital'] class RaiseFundsFrom2(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_title','amount_required','amount_desc','illness','campaign_duration','mobile'] class RaiseFundsFrom3(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_image'] class RaiseFundsFrom4(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_desc','terms'] VIEWS.PY from django.core.files.storage import DefaultStorage FORMS = [("form1", RaiseFundsFrom1), ("form2", RaiseFundsFrom2), ("form3", RaiseFundsFrom3), ("form4", … -
What's next: after successful token created for django all-auth; how to sync google calendars?
Ok, I hope I don't get too beat up here for this question as it is kind of complex. At least in my view, with what I know so far. So the details first: I built a nice app with django that brings in event data for users, utilizes that data for many things (not relevant to this question) but one of the things is that it syncs these events to the users Google calendar. I made the google app within the developer console, and it uses the provided credentials.json file to allow users to authenticate the app, thus creating individual user token.json files per user, then I have another script (not within django, just a custom python file) that runs from a cron job to automatically sync/ update the calendar info from the database to the google calendars. Now, the new problem is having this work without my help. IE: a new user logs in and creates a profile, then if they should choose to sync to their Google calendars I have to be there, running the authentication process from my personal server. So I did that, by moving the whole app to a hosted platform and brought it … -
Django alternative to streamfield
Need help please. Is there an alternative way to implement django-streamfield? I am trying to use the package but it will not work with Django's latest version 3.0.2. -
How to pass the model from a CBV to a ModelForm
I have a view which I want to use with a custom form_class: class CustomCreateView(CreateView): form_class = CustomCreateForm I want to use this view repeatedly so I can use it with different models, such as: class CreateBook(CustomCreateView) model = Books class CreateCar(CustomCreateView) model = Cars Because I want to reuse it, I need a way to pass the model from the CreateView to the form class. I can't specify it in the form class because then I can't reuse the view between different models. Is there a way to do this? E.g. class CustomCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): model = kwargs.pop('model') self._meta.model = model super(CustomCreateForm, self).__init__(*args, **kwargs) class Meta: fields = '__all__' -
SMTPSenderRefused at /password-reset/ "Cannot understand "
from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html' ), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), path('', include('blog.urls')),`enter code here I cannot understand behind the scene of SMTPSenderRefused so guys help me with that? -
Django django.db.utils.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections
File "/usr/local/lib/python3.7/dist-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections According to the Postgres documentation, this error occurs when Django makes more connections to the Postgres DB then it's default connection limit. I would like to know what could be the reasons for Django to be initiating/an opening lot of connections to the DB. I would like to know what are the best practices we can do to prevent it from the exception. How to increase the default connection limit for Postgres? #settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxxxx', 'USER': 'xxxxx', 'PASSWORD':'xxxxx', 'HOST':'localhost', 'PORT':'5432', } -
How do you create a Django Rest Framework serializer with many to many field?
I have a model(Project) that contains ManyToManyField to another model(Screenshot). I want to create a view inheriting CreateAPIView such that it is able to serialize data for creating an instance of project model including the Screenshot model from the same view. models.py class Screenshot(models.Model): image = models.ImageField(default='screenshots.jpg',upload_to='screenshots') class Project(models.Model): team=models.ForeignKey(Team,on_delete=models.CASCADE) name=models.CharField(max_length=100,null=True,blank=True) theme = models.ForeignKey(Theme,on_delete=models.CASCADE,null=True,blank=True) desc=models.TextField() accepted = models.BooleanField(default=False) git_url=models.URLField(null=True,blank=True) youtube_url=models.URLField(null=True,blank=True) screenshots=models.ManyToManyField(Screenshot) serializers.py class ScreenshotCreateSerializer(serializers.ModelSerializer): class Meta: model = Screenshot fields=['image'] class ProjectCreateSerializer(serializers.ModelSerializer): image_1 = ScreenshotCreateSerializer() image_2 = ScreenshotCreateSerializer() image_3 = ScreenshotCreateSerializer() image_4 = ScreenshotCreateSerializer() image_5 = ScreenshotCreateSerializer() class Meta: model = Project fields = ['name','theme','desc','git_url','youtube_url','image_1','image_2','image_3','image_4','image_5'] def create(self,validated_data): try: image1 = validated_data.pop('image_1') image2 = validated_data.pop('image_2') image3 = validated_data.pop('image_3') image4 = validated_data.pop('image_4') image5 = validated_data.pop('image_5') except: pass print(validated_data) test_team_obj = Team.objects.all()[0] project_obj = Project(**validated_data) project_obj.team = test_team_obj project_obj.save() if (image1): project_obj.screenshots.create(image=image1.get('image')) if (image2): project_obj.screenshots.create(image=image2.get('image')) if (image3): project_obj.screenshots.create(image=image3.get('image')) if (image3): project_obj.screenshots.create(image=image4.get('image')) if (image4): project_obj.screenshots.create(image=image5.get('image')) return project_obj The form is displayed as expected with 5 image fields. After submitting the form, the required project instance is created, screenshot instances are created as well and the just created screenshot instances are linked to that just created project instance. Everything runs well. But an error arises saying: Got AttributeError when attempting to get a value for … -
How to extract a geometry from PostGIS using a view and then add it to a leaflet map in a template using Django
I want to extract polygon geometry data from a PostGIS database using python within a view and add it to my leaflet map within a template. The easiest way seemed to be to extract the data and convert it to GeoJSON using the postgis function ST_AsGeoJSON in my Django view and then render it to the template as context within the L.geoJSON(GEOJSON).addTo(map) function. This does not work. On requesting the map page, the map is now blank and as it seems the GeoJSON is not recognised. I have been able to pass a hard-coded polygon from a view and add it to a map but the geometry data in my postgis database simply isn't valid. Here is a view with a hardcoded polygon that is successfully printed on the map: from django.shortcuts import render def map_view(request, *args, **kwargs): geo_json={ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ -0.10746002197265625, 51.505537109466715 ], [ -0.11466979980468751, 51.498377681772325 ], [ -0.0968170166015625, 51.493568479510415 ], [ -0.09080886840820312, 51.502438390761164 ], [ -0.10746002197265625, 51.505537109466715 ] ] ] } } ] } return render(request ,'map.html', {'geo_json': geo_json}) The map template looks as follows: <!DOCTYPE html> <html> <head> <title>Map Page</title> <link rel="stylesheet" … -
Django , i want to make like and disklike Button with count user authenticated
i want to make like and dislike button if it clicked by a user count the like button after that user have only the option of dislike.Google it a lot but dont getting correct manner with django.Want Help -
Writing a multiple schema in a single database
I have an issue How to connect multiple schema in Django using PostgreSQL. Need to create 2 schemas in one database only. We have 20 tables that 10 tables have to move to the 1 schema and another 10 have to move to the 2nd schema. Please rectify it as soon as possible Thank you in advance -
django prefetch_related across mutliple one-to-many relations with filtering conditions
I would like to to a prefetch_related query to get my models and all related models by following one-to-many relations, but with a filtering condition. My goal is to use prefetch_related to obtain all my models and related models in one django query (thus not hitting the database when iterating through related models). I need to go in the one-to-many direction. Say I have the following simple models of Library having many Books having many Pages. from django.db import models class Library(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=50) genre = models.CharField(max_length=50) library = models.ForeignKey(Library) class Page(models.Model): content = models.TextField() book = models.ForeignKey(Book) I know I can do models.Library.objects.prefetch_related('book_set__page_set') to get everything one-shot, but what if I want to restrict to book with genre='fantasy'? How can I add this filter condition in my relation-spanning prefetch query? -
How can I avoid request timeout error in django app hosted in a docker container?
I would like to create a button in django admin site that would run a process which could take a few minutes to complete. I have the app hosted in a docker container. It would be nice to receive a notification as well if the process was completed successfully or not. -
crash when trying to download pdf file
It was working on django 1.8, and python 2.7 When I upgraded libraries and app to django 2.2 and python 3.6.8 I am getting the error below. Which is in libraries, rather than my code [08/Jan/2020 16:46:33] "GET /policy/download/ HTTP/1.1" 200 0 Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 179, in finish_response for data in self.result: File "/usr/lib/python3.6/wsgiref/util.py", line 30, in __next__ data = self.filelike.read(self.blksize) File "/usr/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 11: invalid start byte [08/Jan/2020 16:46:33] "GET /policy/download/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 33210) Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 179, in finish_response for data in self.result: File "/usr/lib/python3.6/wsgiref/util.py", line 30, in __next__ data = self.filelike.read(self.blksize) File "/usr/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 11: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 141, in run self.handle_error() File "/home/bsd/.local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 116, in handle_error super().handle_error() File … -
•Select a valid choice. That choice is not one of the available choices
**after writing author name and text and clicking on add comment, on web i get the error: •Select a valid choice. That choice is not one of the available choices.after righting author name and text and clicking on add comment, on web i get the error: •Select a valid choice. That choice is not one of the available choices.** in models.py: class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse("post_list") def __str__(self): return self.text in forms.py: class CommentForm(forms.ModelForm): class Meta: model = Post fields = ('author','text',) widgets = { 'author': forms.TextInput(attrs={'class': 'textinputclass'}), 'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea'}), } in views.py: @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form': form}) -
Django Test Case gets diffrent redirect than Firefox or Chrome
Trying to work on a project and get my head around unit Testing. I'm confused why client.get is getting a diffrent redirect than both Firefox and Chrome. Details below, but can someone give me an idea this is occuring. Django Version 3 Python verson 3.8 Running on Ubuntu in WSL in windows. My View Function. class UserDashboardView(View): def get(self, request, *args, **kwargs): return HttpResponseRedirect('/accounts/login') My Test Case import unittest from django.test import TestCase class DashboardPageTest(TestCase): def test_unauthenticated_user_redirected_to_login(self): response = self.client.get('/dashboard') print(response) What occurs. 1 - If I go to /dashboard in Chrome and Firefox the debug shows a 302 with a location key of /accounts/login, and so the browser follows to /accounts/login 2 - If I run the unit test (python manage.py test) the print of the response returns <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/dashboard/"> I have a feeling their is something I just don't get about the way the browsers vs the TestCase does redirects. Can someone please explain it? -
Using tablespaces to optimise performance
How do i use tablespaces defined for my Django application to optimise for performance? If i were to use tablespaces for my database and grouped database tables and indexes, how would i configure the use of tablespaces to optimise performance? -
Unable to get Reverse for 'userprofile' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<user_id>[0-9]+)$']
I am trying to make an html page in my django project. Here threre is some error, reverse not found for 'userprofile' is not found i am not able to have any trace of error in my code kindly help the line containing 'userprofile' is marked by $$$ {% extends 'auth_base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col-8"> {% for post in posts.all %} <div class="container" style="border-width: 20px; border-color: grey;margin: 10px;"> {% if post.image %} <img src="{{ post.image.url }}" height="50vh" /> {% endif%} <!--display the title --> <p> {{ post.title }} </p> <p> {{ post.abstract }} </p> </div> {% endfor %} </div> <div class="col-2"> <h5>Other Users</h5> {% for other_user in other_users %} {% if followed_users %} {% if other_user not in followed_users %} $$$ <a href="{% url 'userprofile' other_user.id %}"> <h4> {{ other_user }}</h4> <a href="{% url 'change_friends' 'add' other_user.user_id %}"> <button type="button" class="btn btn-success">Add Friend</button> </a> </a> {% endif %} {% else %} $$$ <a href="{% url 'userprofile' other_user.user_id %}"> <h4> {{ other_user.user_name }}</h4> <a href="{% url 'change_friends' 'add' other_user.user_id %}"> <button type="button" class="btn btn-success">Add Friend</button> </a> </a> {% endif %} {% endfor%} <h2>Following</h2> {% for followed in followed_users %} $$$ <a href="{% url 'userprofile' … -
Best method to do a reminder system
i am not sure if this is considered a vague post but i would love to get some input from our experienced coders here regarding this project that im working on. I wish to build a reminder system for my django app. The app im building is a sales tracker , which tracks where the sales project current is at in the sales pipeline. I broke up this sales pipelines into a series of task that should be completed in a sequence , this activities comes in the form of updating my django model with data . Due to the nature of the business, certain tasks will be left uncompleted until new information is made to the sales person to enter into our system , therefore i wish to create a prompt that generates after a certain threshhold (time) has been crossed . The idea im having in mind is to add in indicator fields which will allow me to query out parts of the projects (models) if they breach the threshhold i set , and return that value as a prompt in my html . However , this seems to over complicate my code base with super complex queries. …