Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep track of users' hobbies/interests in semi-structured way?
Sorry in advance for the long question. I'm not sure the best way to ask it. I am building a social networking platform with the Django/Python web framework. On it, users can create a profile and list their interests or hobbies. I want to match users together based on the number of exact matches and similar matches of their hobbies to create a "compatibility score". For example, there might be a Music category with Jazz, Rock, and Hip Hop genres as well as a Sports category with Football, Basketball, and Soccer, etc. I want there to be a somewhat "standard" list of interests/hobbies so I can analyze them to create a compatibility score. Should I create a standard set of interests and set True/False for every hobby for every user? Or could I only store the hobbies that each user is interested in, but use auto-complete so when a user starts typing their interests, they get prompted to input them in a standard way? Or should I allow them to store their interests/hobbies as free text and use some NLP analyzer to create a compatibility score? If so, what should I use for that? -
How to put "active" class on multiple carousel 's on the same page in Bootstrap
I am trying to add the active class to my first carousel element. But I cannot add it as apparently my selector is wrong. I am using Django templates which have a for loop and I have already added a unique id to each carousel but the script does not work: this is my for loop: {% for post in posts %} {% if post.images %} <div id="carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" class="carousel slide" data-interval="false" data-ride="carousel"> <ol class="carousel-indicators"> {% for i in post.image_count_as_list %} <li data-target="#carousel-{{ post.title|cut:' ' }}" data-slide-to="{{ forloop.counter0 }}" class="active"></li> {% endfor %} </ol> <div class="carousel-inner"> {% for pic in post.images.all %} <div class="carousel-item"> <img class="d-block img-fluid" src="{{ pic.image.url}}" alt="Content not available"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }}" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> <script type="text/javascript"> $("#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }} .carousel .carousel-item:first").addClass("active"); </script> </div> {% endif %} {% endfor %} and as you can see I am using this script: <script type="text/javascript"> $("#carousel-{{ post.title|cut:' ' }}-{{ post.author.username }} .carousel .carousel-item:first").addClass("active"); </script> But the "active" class I s not being … -
Django-filter How to write filters with DjangoFilterBackend in a POST request?
I have written a custom filter using django-filter package as mentioned in DRF docs here: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend Here is my code: class GeoFilter(filters.FilterSet): village_name = filters.CharFilter(field_name='village_name', lookup_expr='icontains', label = 'village_name') country_id = filters.NumberFilter(field_name='block__district__state__country', lookup_expr='exact', label = 'country_id') country_name = filters.CharFilter(field_name='block__district__state__country__country_name', lookup_expr='icontains', label = 'country_name') class Meta: model = Village fields = ['village_name', 'country_id', 'country_name'] class VillagesViewSet(viewsets.ModelViewSet): ''' Villages list with django-filters ''' authentication_classes = [TokenAuthentication] permissions_classes =[IsAuthenticated] serializer_class = VillageSerializer queryset = Village.objects.get_queryset().order_by('id') filter_backends = [filters.DjangoFilterBackend] filterset_class = GeoFilter This is a GET request. I want to write only POST requests with filtering using DjangoFilterBackend. I am trying to find whether it is possible. I am using ORM filter currently but I want to use django-filter as I find it better for filtering. -
Django If statement String Comparison
code.code_type has a string value "mel" and it outputs the same value in the webpage. when i just run {{code.code_type}} But when I compare it in if statement with a string {% if code.code_type == "mel" %} Nothing is happening. {% for code in codes%} {% if code.code_type == "mel" %} <div class="snippet"> <div class="snippet-container"> <div class="snippet-heading"> <a href="#">{{code.code_type}}</a> </div> <div class="snippet-code"> {{code.code_snippet}} </div> <div class="snippet-note"> {{code.code_note}} </div> </div> </div> {% endif %} {%endfor%} -
nginx looking for staticfiles in the wrong place
my Django deployment with ec2, nginx and gunicorn went well beside that my staticfiles are not loading, browser show a 404 error. And this is because nginx looks in a completely different place than statics. At this point I have tried a lot of configurations and nothing does the trick. I am wondering if a pair of fresh eyes can spot a mistake here that I do not. /sites-enabled/django.conf: server { server_name site.net www.site.net; location /static/ { autoindex on; alias /home/ubuntu/saas/static/; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/saas/app.sock; } location ~ \.css { add_header Content-Type text/css; } location ~ \.js { add_header Content-Type application/x-javascript; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/site.net/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/site.net/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.site.net) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = site.net) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name site.net www.site.net; return 404; # managed by Certbot } and my django settings.py look like this and collectstatics works fine. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_ROOT = … -
Request from HttpResponseRedirect is called with old URL
I have a template that renders this url: /game/<game_name>/task/<task_id> The idea is render the same template but changing content based on task_id I have this URL path('<str:slug_id>/task/<int:task_id>/', task_page,name='task') that comes from path('game/', include(('game.urls','game'),namespace='game')), And this is the view: def task_page(request,slug_id,task_id): if request.method == 'POST': form = TaskPlayForm(request.POST) if form.is_valid(): task = get_object_or_404(Task,task_id=task_id) puzzle_resultado = task.result puzzle_respuesta = form.cleaned_data['resultTask'] if puzzle_respuesta.upper() == puzzle_resultado.upper(): next_puzzle = task.task_next next_puzzle_id = next_puzzle.task_id return HttpResponsePermanentRedirect(reverse('game:task',args=(slug_id,next_puzzle_id,))) else: return HttpResponseRedirect('/no-resuelto/') return HttpResponse(form.cleaned_data) else: form = TaskPlayForm() template_name = "game_task.html" game = get_object_or_404(Game,slug=slug_id) task = get_object_or_404(Task,task_id=task_id) [..redacted..] context = {"form":form,"game":game,"task":task, "display_items":temp} return render(request,template_name, context) Rendering templates and redirects work fine I'm rendering the same template using the same view from task1 to task2 in this way: /game/example/task/1 --submit form-->/game/example/task/2 But the problem is that rendering /game/example/task/1, then submitting the form redirect to /game/example/task/2 successfully but the task_id request parameter is from previous request (1 in this case). I have tested permanent vs temporary redirects but there is no difference and debugging shows previous task_id value My question is, how can be possible that redirecting to /game/example/task/2, the request parameter task_id is 1? -
Modifying django-filter queryset with callable
I'm trying to modify the queryset of one of my ModelChoiceFilters to depend on the user accessing them. My callable function looks like: (filters.py) def is_client(request): if request is None: return Project.objects.none() return Project.objects.all() This function is being called in the filter class looks like: (filters.py) class ReportFilter(django_filters.FilterSet): project = django_filters.ModelChoiceFilter(field_name='project_name', label='Project', queryset=is_client) class Meta: model = Report fields = ['project'] When coded like this, it always triggers the first condition in is_client. When I try and play around with it and do things with request.user..., I get the error: 'NoneType' object has no attribute 'user'. I have made it so that the queryset which the filter is instantiated with in the view limits what certain users can access, however they can still see the options which are not available to them in the filter (even if when they select it nothing would be returned): (views.py) @login_required def home(request): if is_employee(request.user): reports = ConcreteReport.objects.all() else: client = request.user.id reports = ConcreteReport.objects.filter(project_name__company__user__id=client) myFilter = ReportFilter(request.GET, queryset=reports) context = {'reports':reports, 'myFilter':myFilter} return render(request, 'dashboard/home.html', context) I can't figure out why the request is a NoneType, as I use it in the view for other things and it has attributes. Any help is … -
Store a non-JSON serializable object in session
I have object of type OAuth1 oauth = OAuth1(CLIENT_ID, client_secret=CLIENT_SECRET, resource_owner_key=request.session.get('resource_owner_key'), resource_owner_secret=request.session.get('resource_owner_secret')) I do not want to have to create this object every-time an API is hit so I would rather store it in a session. It isn't JSONSerializable though What are my alternatives? I realize it isn't allowed to store objects in sessions since Django 1.6 . Creating the same object repeatedly does not look like a good option to me. For reference, The decorator that looks like this : def oauth_verify(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.session.get('oauth'): if (request.session.get('resource_owner_key') and request.session.get('resource_owner_secret')): oauth = OAuth1(CLIENT_ID, client_secret=CLIENT_SECRET, resource_owner_key=request.session.get('resource_owner_key'), resource_owner_secret=request.session.get('resource_owner_secret')) request.session['oauth'] = oauth else: return JSONResponse(result=json.dumps({ "Exception": "NotAuthorized", "Error" : "You are not authorized, please log on" }), message='failure') return view_func(request, *args, **kwargs) return _wrapped_view_func -
Django Whitenoise not serving static files sometimes in ECS with debug False
My static files are not being served nicely in production with Whitenoise and Debug=False . Sometimes it serves, sometimes it doesn't find the static. I have the following settings: # Static / Media MEDIA_URL = os.environ.get('MEDIA_URL', '/media/') MEDIA_ROOT = os.path.join(BASE_DIR, '.media') STATIC_URL = os.environ.get('STATIC_URL', '/staticfiles/') STATIC_ROOT = os.path.join(BASE_DIR, '.static') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/static'), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... On deploying to AWS ECS, I'm collecting static normally on docker. If I run python manage.py collectstatic locally I can find the files on my STATIC_ROOT. On production if I access via browser sometimes it returns the static correct, sometimes it gives a 404 error. What it could be? Any help please. -
Django OperationalError 'no such column:' sqlite
For my basic, rudimentary Django CMS, in my effort to add a toggle feature to publish / unpublish a blog post (I’ve called my app ‘essays’ and the class object inside my models is is_published), I’ve encountered an OperationalError when trying to use the Admin Dashboard to add essay content. I’m expecting to be able to switch a tick box to publish/unpublish but now I can’t even access the Dashboard. Here is part of the traceback from my Django server: File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: essays_essayarticle.is_published The debug traceback reinforces the OperationalError above: OperationalError at /admin/essays/essayarticle/ no such column: essays_essayarticle.is_published Request Method: GET Request URL: http://<DN>.ngrok.io/admin/essays/essayarticle/ Django Version:2.2.11 Exception Type: OperationalError Exception Value: no such column: essays_essayarticle.is_published Exception Location: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /home/<user>/dev/projects/python/2018-and-2020/<projectdir>/venv/bin/python `Fri, 1 May 2020 19:37:31 +0000 Exception Value indicates ‘no such column’ which is a reference to my db. I’m running SQlite3 for test purposes. Prior to this OperationalError, I was troubleshooting issues with a DummyNode and "isinstance django.db.migrations.exceptions.NodeNotFoundError: Migration". The previous solution I arrived at was to delete my migrations in two of my … -
Optimize ORM queries in Flask using Flask-SQLAlchemy
I have written the same project using Django and Flask. The entire code is available on my Github account. The website is a small question-answer based quiz website (in CTF format with very easy questions). Here are the links: Django Project Flask Project My question is regarding optimizing ORM queries in SQLAlchemy or Flask-SQLAlchemy. I'll try to write the schema of the tables as well as I can for better understanding. Teams (id, team_name, email, phone, password) Questions (id, name, body, hint, answer, points, visible) Submissions (id, team(fk), question(fk), timestamp) In case any of you want to see the actual code, here they are: For Django - Question & Submission, Team For Flask - Question, Team, Submission For two of the routes, /submissions and /leaderboard, I had to write certain queries using the ORM. This is how the pages look like: For Django, the queries look pretty good (or at least I think so :P ) def submissions(request): all_submissions = Question.objects \ .values('id', 'name') \ .order_by('id') \ .annotate(submissions=Count('submission')) print(all_submissions.query) return render(request, 'questions/submissions.html', { 'submissions': all_submissions }) def leaderboard(request): team_scores = Team.objects \ .values('team_name') \ .order_by('team_name') \ .annotate(score=Coalesce(Sum('submission__question__points'), 0)) \ .order_by('-score') print(team_scores.query) return render(request, 'questions/leaderboard.html', { 'team_scores': team_scores, }) And the … -
Django queryset ordering by fields
i'm using django 2 and in my list view i want to oder the queryset by likecount and datetime field. The main goal is to odering the post with mostlikes for today. Like, i want to show the most liked posts for today. It's like todays top 10 post(mostliked). i have tried many ways but can't figure it out. I hope you guys can help me. My models.py: class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) restrict_comments = models.BooleanField(default=False) watchlist = models.ManyToManyField(User, related_name='watchlist', blank=True) def __str__(self): return self.content class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() My views.py: @login_required def most_likes(request): posts = post.objects.annotate(like_count=Count('likes')).order_by('-like_count', '-date_posted') context = {'posts': posts} return render(request, 'blog/most_likes.html', context) -
What environment variables do I need to include in a bash script in order to run a Django migration?
I'm running Python 3.7, Django 2, on Mac OS X. When I run the following commands from the command line, they work seamlessly ... localhost:web davea$ source ./venv/bin/activate (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: No migrations to apply. However, when I create a bash script containing the commands !#/bin/bash source ./venv/bin/activate python manage.py migrate maps The script dies localhost:web davea$ sh test.sh test.sh: line 1: !#/bin/bash: No such file or directory Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found 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 … -
Python, Django3 error 'QuerySet' object has no attribute 'patterns'
I am very new in Python and Django. I have problem with request in my app. I want to get the value for pattern in part model (reletionship M2M) And i have django error: 'QuerySet' object has no attribute 'patterns' What is the error and how to fix it? Thanks for help Models.py from django.db import models class Pattern(models.Model): patternName = models.CharField(max_length=64) def __str__(self): return self.patternName class Part(models.Model): unitsList = ( ('szt', "szt"), ('m', "m"), ('komp', "komp") ) partName = models.CharField(unique=False, max_length=128) code = models.CharField(unique=True, max_length=15) units = models.CharField(max_length=10, choices=unitsList, default='szt') description = models.TextField() pattern = models.ManyToManyField(Pattern, related_name='patterns) def __str__(self): return self.partName views.py from django.shortcuts import render, from .models import Part, Pattern def partList(request): allParts = Part.objects.all() allPatterns = allParts.patterns.objects.all() return render(request, 'partList.html', {'parts': allParts, 'patterns': allPatterns}) partList.html {% for part in parts %} <tr> <td>{{part.partName}}</td> <td>{{part.code}}</td> <td>{{part.units}}</td> <td>{{part.description}}</td> <td>{{part.producer}}</td> <td>{{part.pattern}} </td> <td> <!-- <a href="../editPart/{{part.id}}">EDYTUJ</a> <a href="../deletePart/{{part.id}}">USUN</a> --> <a href="{% url 'editPart' part.id %}">EDYTUJ</a> <a href="{% url 'deletePart' part.id %}">USUN</a> </td> </tr> {% endfor %} -
How to keep the page paginated using django-filters when no filter is applied?
I'm using django-filters to filter categories and price. My problem is that, when I'm filtering results, it's paginated, but when there are no filters applied, there is no pagination. How can I add pagination when there are no filters applied? Thanks in advance! My filters.py: import django_filters from .models import Item class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'category': ['exact'], 'price': ['lte'] } My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 8 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My home.html: <div class="card"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1 class="mb-4">List Of Items</h1> <div class="row"> {% for item in filter.qs %} .... {% endfor %} -
Django Testing Package Installed by PIP Locally
When developing in Django, we can use the following command (or its variations) to run tests on all the apps written by us: python manage.py test. This will make Django look for test directories, as well as files with names along the lines of test_*. What I am wondering about is whether there is a way to include into the testing a package that was installed via pip install -e /path/to/package/here. I am trying to do this because I want to change some code in this package to make it compatible with a latter Django version. The package does have unit-tests in the test directory. However, it seems that it needs a virtual environment with Django to run those tests. Upon creating one, it is discovered that one needs to set up a project with settings to get it to work. Hence, my thought was: if we already have a project that is using this package, can we not run its tests from the project itself? If there is a better way of doing it, I am happy to hear it. -
access cpanel Database from my django website
so i am building a custom dashboard for my clients (using Django) whose websites are hosted using cpanel. i wanted to access their databases from my django app. is this possible in the first place? and if yes where do i start? -
Nuxtjs authentification
Does Google auth via gmail somehow relate to back end in nuxt js? I mean , when we work with tokens. After logging in , should I send the token to back end or nuxt js tackles it instead? -
Post button isn't adding the data to the back end database
I want the user to be able to add comments to the posts. I can add comments on the back end, I am having issues allowing users to add them via the front end. When I click Post, I want the comment to be added to the back end. And I want the page the user is currently on to be refreshed. Unfortunately the comments are not currently being added to the back end. And I am being directed to http://localhost:8000/your-name/. I made a page on my site called your-name as a test. And once I did this, the test page did load. But the comments were still not being added to the back end. The comments have a many to one relationship with the posts. Each comment can only have one post linked to it. Each post can have many comments linked to it. I think one problem is that the posts have individual URLs. But the comments don't have their own URLs. When I refresh the page, I need to take the URL of the active post. I tried doing comment_form.save(commit=True). I wanted to see if I could get any thing (valid or invalid data) to be added … -
Event listener from js static file pointing to incorrect path in Django
This is the first time I am trying to integrate front-end with backend in Django. I currently have the following file structure: my_project | +-- my_app | | | +-- ... | +-- static | | | | | +--my_app | | | +--app.js | | | +--style.css | | | +--back.png | | | +--dice-1.png | | | +--dice-2.png | | | +--dice-3.png | | | +--dice-4.png | | | +--dice-5.png | | | +--dice-6.png | +-- templates | | | | | +--my_app | | | +--index.html | | +-- manage.py The problem is my css file from my_app/static is loading just fine - including the initial image file on the page, but when I try doing a click event on the app.js file to load an image from the static folder, i am getting an error on the console: GET http://localhost:8000/js_dom/dice-1.png 404 (Not Found) From my js file: // setter: change dice img var diceDOM = document.querySelector('.dice'); // select dice DOM diceDOM.src = `dice-${dice}.png`; // use correct png based on roll <-- this is where I am getting the error }); The initial image loads from my html file: <img src="{% static 'js_dom/dice-5.png' %}" alt="Dice" class="dice"> And … -
Django: widthratio but in views.py
In my template I have the following code which multiplies data.quantity with data.price. {% widthratio data.quantity 1 data.price as foo %} {% if foo > "10000" %} <td>{{ foo }} test1</td> {% else %} <td>{{ foo }} test2</td> {% endif %} I would like to use something similar in my views.py since I want to create a filter for my queryset, is there some smooth solution for this such as widthratio in the templates? -
Django import export - How to skip the new rows, and only update the existed ones
When importing a file I want to skip all of the new rows that exists, and only update and change the ones that already exists, I've been trying for days to solve this problem, any ideas will help. also the file type is ".xls" or ".xlsx" here's my code: models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name admin.py: class BookResource(resources.ModelResource): class Meta: model = Book import_id_field = 'id' import_id_fields = ('id',) fields = ('id', 'name', 'price',) skip_unchanged = True report_skipped = True dry_run = True class CustomBookAdmin(ImportMixin, admin.ModelAdmin): resource_class = BookResource # tried to override it like so but it didn't work def skip_row(self, instance, original): original_id_value = getattr(original, self._meta.import_id_field) instance_id_value = getattr(instance, self._meta.import_id_field) if original_id_value != instance_id_value: return True if not self._meta.skip_unchanged: return False for field in self.get_fields(): try: if list(field.get_value(instance).all()) != list(field.get_value(original).all()): return False except AttributeError: if field.get_value(instance) != field.get_value(original): return False return True -
Django - The current path did not match any of url pattern
Getting Request URL: http://127.0.0.1:8000/picture/7/pic/31/delete/None instead of http://127.0.0.1:8000/picture/7/pic/31/delete/ Why it's adding /None at the end? #html action="{% url 'picture:item-delete' pic.album_id pic.pk %}" #views.py class ItemDelete(DeleteView): model = Pic def get_success_url(self): reverse_lazy('picture:detail', kwargs={'pk': self.object.album_id}) #urls.py urlpatterns = [ # /picture/<album_id>/pic/<pic_id>/delete/ url(r'^(?P<id>[0-9]+)/pic/(?P<pk>[0-9]+)/delete/$', views.ItemDelete.as_view(), name='item-delete'), ] Though, it deleted the model(pic). -
Django Form Validation not working on a field
I am doing a simple form validation. But not sure where i'm missing. Here I have put a validation of the field company_name which will validate if my company name is equal to "BFR". However I am not getting any validationerror after submitting the form. Could you please help me on this? forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Button from django.forms import ValidationError from .models import Company class CompanyForm(forms.ModelForm): compname = forms.CharField(label='Name : ', required=True) class Meta: model = Company fields = ['compname'] labels = { 'compname': 'Name : ', } def clean_compname(self): company_name = self.clean_data.get('compname') if (company_name == "BFR"): raise forms.ValidationError('company name cant be empty') return company_name def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs['autocomplete'] = 'off' self.helper.layout = Layout( 'compname', Submit('save', 'Save changes'), Button('Reset', 'Reset', css_class='btn btn-info'), Button('cancel', 'Cancel' , css_class='btn btn-secondary'), ) models.py from django.db import models # Create your models here. class Company(models.Model): compname = models.CharField(max_length=20) def __str__(self): return self.compname views.py from django.shortcuts import render from django.contrib import messages from .forms import CompanyForm from .models import Company def company_form(request, id=0): if request.method == 'GET': if id == 0: form = CompanyForm() else: company = Company.objects.get(pk=id) … -
Custom Django Password Reset - Link does not get invalidated
I know that the one time link for the password reset should be invalidated following the email password change procedure as given here enter link description here. Yet, with my below implementation, although the link can reset the password each time, it does not get invalidated. The link works each time. What could be the reason for this ? (I also see the last login timestamp is also updated in admin pages for the particular user that I am changing the password for) (forms.py) from django.contrib.auth.forms import UserCreationForm, SetPasswordForm from django.contrib.auth import get_user_model class ResetPasswordForm(SetPasswordForm): class Meta: model = get_user_model() fields = ('password1', 'password2') (tokens.py) from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() (views.py) def activate_forgot_password(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = get_user_model() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): if request.method == 'POST': form = ResetPasswordForm(user, request.POST) if form.is_valid(): user = form.save(commit=False) print(user.password) user.save() login(request, user, backend='mysite.signup.views.EmailBackend') return redirect('home') else: form = ResetPasswordForm(user) return render(request, 'change_password.html', {'form': form, 'uidb64': uidb64, 'token': token}) return render(request, 'account_forgot_password_token_invalid.html') (template.html) <form id="ResetPasswordForm" method="post" action="{% …