Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python avoiding using for loop or need shorten the code base
I have write python code and it has too many for loop, as a result, my code readability is too low and pylint star too low. I am finding a way to solve same with fewer line of code. here you go for my snippet: numberlist = [1,3,5] stringlist = ['a', 'b', 'c'] id = '458' numbered_string = [] for n, s in numberlist, stringlist: num_str = "{}{}".format( n, s, id, ) numbered_string.append(num_str) codes = [] for n,s, sn in numberlist, stringlist, numbered_string: code = make_code( n, s, sn ) codes.append(code) print(codes) Ignore the function make_code() , or let's assume the make_code() is def make_code(n,s, sn): return str(n) + str(s) + str(sn) Can anyone help me shorten the snippet?, please ignore the function. I want to improve this code much better and high readability, too many instance is not a solution. -
form not submitting on click register django
On click register button it no posting data to database. def register(request): if request.method =="POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.clearned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("/") form = UserCreationForm return render(request, 'register.html', {"form":form}) it refresh and still open register.html. instead to redirect to home page. pls i need help i expect it to redirect to home, return to home page. -
Django/Python caching solution that I can access with complex keys rather than only strings
It is my understanding that all caching solutions for Django/Python are essentially based on key/value dictionaries. cache.store(“key”, “value”) cache.get(“key”) # <- “value” I understand there are decorators and other abstractions that allow you to store in cache based on the view function, but they’re agnostic towards the inputs of this function (POST/GET parameters, for example). Here’s my problem: I need to cache results of computations of complex sets of inputs, including (but not limited to), the user that’s performing the request, dictionaries, booleans, ecc... I could, in theory, serialize these inputs into a string and use this string as the key for caching but I was wondering if there are some pre-made solutions to solve this problem. Something like this: def my_view(request): output = cache.get(request, None) if output is None: output = complex_stuff(request) cache.store(request, output) Or, even better, where I can use an arbitrary dictionary as a key, instead of a string. -
Django: view formatted sql in console
I want to see formated sql queries in the console of Django while developing I have tried adding the below code to settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console', ], }, }, } Now whenever there is any sql query it shows in the django console. But its not well formatted. So how can i see the formatted sql queries instead of single line -
how to read source code of django-rest-framework, or any other python library
I am learning django-rest-framework. trying to figure out what's the diffrent bettwen update and partial update in modelviewset,so I decided to read source code, but source code in github with a lot of inherit relationships are difficult to read. I found a website http://ccbv.co.uk/ when I learning about django,that really helpful to read source code, and now I found http://www.cdrf.co/ although this website pretty much the same as first one, but seems got a issue,no __init__. anyway, I am just wanna know how experienced programmer learning about new library. and read and understand those source code efficiently? -
How to order Django queryset by an encrypted field and use the result in ModelForm
I'm using django-encrypted-model-fields to encrypt selected model fields. As described in the documentation (https://pypi.org/project/django-encrypted-model-fields/) sorting and filtering by values contained in encrypted fields is not supported. And yet, I would like to provide to users the possibility to select from an ordered drop-down list in the admin ModelForm as the following example attempts to do, although the the values are stored in encrypted form: models.py class ProjectActivity (models.Model): abbreviation = EncryptedCharField(max_length=20) project = models.ForeignKey("Project", on_delete=models.CASCADE) class Rule (models.Model): name = EncryptedCharField(max_length=100) activities = models.ManyToManyField('ProjectActivity', related_name="rules") admin.py class RuleAdmin(admin.ModelAdmin): form = RuleForm forms.py class RuleForm(forms.ModelForm): class Meta: model = Rule fields = '__all__' def __init__(self, *args, **kwargs): super(RuleForm, self).__init__(*args, **kwargs) activities_queryset = ProjectActivity.objects.filter(project=current_project) # activities should be decrypted by now self.fields['activities'].queryset = activities_queryset.order_by('abbreviation') The above code loads and decrypts the activities first and then tries to sort them but the result is not correct. sorted(), as in the following code orders correctly self.fields['activities'].queryset = sorted(activities_queryset , key=lambda o: o.abbreviation) however the result is a list and not a dataset and thus the templating system runs into the following AttributeError: 'list' object has no attribute 'all' Any ideas how to solve or bypass the problem? -
How to mark task as complete using JavaScript, AJAX in a Django App
I am trying to implement a todo(goal) list within my Django App. I am able to add steps to my todo list, however I cannot figure out how to mark the step as complete (set the 'done' boolean field true). The step model I have includes a boolean field which I am trying to set to true when submitting the checkmark form. I've tried to use a variation of my new step form mark the step as complete but I've been unsuccessful so far. <form class='check_Mark' method='post' data-goal={{goal.pk}} data-step={{step.pk}} action="{% url 'check_mark' goal.pk %}">{% csrf_token %} <button type="submit"> Mark Complete </button> </form> function qAll (selector) { return document.querySelectorAll(selector) } const checkMark = qAll('.check_Mark') checkMark.forEach(item => { item.addEventListener('submit', function (e) { e.preventDefault(); console.log(item.dataset.step) console.log(item.dataset.goal) $.ajax({ type: 'POST', url: item.action, data: { 'goal': item.dataset.goal, 'step': item.dataset.step, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', success: function (data) { console.log('Success') location.reload(); } }); }); }) path('goal/', core_views.goal_list_view, name='user-profile'), path('goal/add', core_views.add_new_goal, name='add_goal'), path('goal/add_step/<int:pk>', core_views.add_new_step, name='add_step'), path('step/<int:pk>/', core_views.check_mark, name='check_mark'), @login_required def check_mark(request, pk): from core.forms import CheckListForm from django.views.generic.edit import CreateView if request.method == "POST": form = CheckListForm(request.POST) if form.is_valid(): done = form.save(commit=False) done.person = Person.objects.get(user=request.user) done.goal = get_object_or_404(Goal, pk=pk) done.step = get_object_or_404(Step, pk=pk) done.done = True form.save() … -
What can be done to fix Heroku's H10 error?
I am trying to launch a simple portfolio website using Heroku but everytime I run the app I get the H10 error. What can I do to fix it? I've had various errors throughout the process, which I've managed to fix. But this recent error, H10, I can't seem to figure out what's going on. In the logs, I can see where the app is asking to me apply the migration for 17 files. I run python manage.py migration and it says there's nothing to update. I then try to do heroku run python manage.py migration and it runs succesfully. Then, I do the git add ., git commit -m "comment" and lastly git push heroku master. This what happens when it runs. Enumerating objects: 35, done. Counting objects: 100% (35/35), done. Delta compression using up to 8 threads Compressing objects: 100% (24/24), done. Writing objects: 100% (26/26), 3.76 KiB | 961.00 KiB/s, done. Total 26 (delta 16), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Found python-3.6.8, removing remote: -----> … -
Multiple image upload in django using multiupload
I have been working on this for a while. I am trying to set-up a listing site where users can upload multiple images per post and are limited on the number of images they can upload and so-far this package seems to be perfect for my use-case. I did have to create a fork to get it to work with the newer version of django, where I added renderer=None to line 23 of field.py in the def render. That fixes the error and allows me to view the form, but on submission I get a 'list' object has no attribute 'name' error. I used this answer to get to this point. Any help would be appreciated! models.py class Listing(models.Model): description = mdoels.TextField(blank=True) track_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Photo(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) file=models.FileField(upload_to='images', verbose_name = 'Photos') forms.py class ListingForm(forms.ModelForm): photos = MultiImageField(min_num=1, max_num=4) class Meta: model = Listing fields = ['description',] def save(self, commit=True): photos = self.cleaned_data('photos') instance = Super(ListingForm, self).save(commit) for each in photos: Photo.objects.create(file = each, listing = instance) return instance views.py class AddForm(CreateView): model = Listing template_name = 'marketplace/listing_create.html' form_class = ListingForm success_url = 'index' def form_valid(self, form): instance = form.save(commit = False) instance.user = self.request.user … -
Creating a view using CookieCutter
How am I supposed to code a corresponding view for a URL while using the cookiecutter add-ins? django is new to me, and I learned how to create views with a basic install, but now that I'm using cookiecutter I'm unsure how to properly code the view. I'm sorry this is probably a very noob question. I'm just not used to how it's using 'template views' etc.. urlpatterns = [ path("", TemplateView.as_view(template_name="pages/home.html"), name="home"), path( "about/", TemplateView.as_view(template_name="pages/about.html"), name="about" ), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path("users/", include("pctn.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path("payment/", TemplateView.as_view(template_name="pages/Payment.html"), name="Payment"), what is my class supposed to look like in my views.py? I'm trying to make one for the last url "payment/". Thank you all :) -
Trying to compare date time from query set with a date time object
This maybe very obvious, but I'm new to Python and Django. I'm writing middleware and need to compare two user time points. Basically if a user is on the site over 24 hours, I want to remove their permissions. class PremiumMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) user = request.user datetime_done = Purchase.objects.filter(user=user).values_list("datetime_completed") if datetime_completed != "": if datetime_completed > datetime.datetime.now(): remove_perm('add_permission', user, Purchase) return response This is the error I get: TypeError: '>' not supported between instances of 'str' and 'datetime.datetime' I also had a secondary question. Can I put the permissions in the purchase model directly or must it be in the user model? Everytime a user does an action, this model is updated with the datetime_done, date_action, id, new token, etc are all updated. Is this a bad way to set this up? class Purchase(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) datetime_action = models.DateTimeField(default=datetime.now, blank=True) datetime_completed = models.DateTimeField(default=datetime.now, blank=True) id = models.CharField(max_length=250, blank=True) success = models.BooleanField(default=False) class Meta: ordering = ['user'] permissions = (("add_permission", "Add Permission"),) def __str__(self): return f'{self.user}' -
Django many to many queryset - get list of items actively used by many to many object
I have following Django models: class Tag(models.Model): tag = models.CharField(max_length=100) class Photo(models.Model): photo = models.ImageField() tags = models.ManyToManyField(Tag, through = 'PhotoTag', related_name="tags") class PhotoTag(models.Model): photo = models.ForeignKey(Photo, blank=True, null=True, on_delete=models.CASCADE) tag = models.ForeignKey(Tag, blank=True, null=True, on_delete=models.CASCADE) I want to get queryset that has only tags that are currently assigned to any photo eg only those tags that have a PhotoTag record. What is the queryset for that? -
Can you return data from multiple models as a response from a class that derives ListApiView in django?
I'd like to present to the requester data(get request) from multiple models using foreign keys, but the delimiting factor is the required serializer_class property, which only allows me to return data from a single model. Is there an approach that works for this derivation, or do I need to try something else altogether to accomplish this? Using django 1.11 Below I have some code that merely shows an example of the method, get_queryset, that I'm using in order to present the user data to give an idea of what tools I'm working with to try and return data. import json from rest_framework.views import APIView from rest_framework.authentication import SessionAuthentication from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.response import Response from rest_framework import generics, mixins, permissions from .serializers import UserProfileSerializer from customApp__UserProfile.models import UserProfile from django.shortcuts import get_object_or_404 ##################################################################################### # Helper Function : is_json # Purpose : determines if input is valid json data # ##################################################################################### def is_json(json_data): try: real_json = json.loads(json_data) is_valid = True except ValueError: is_valid = False return is_valid ##################################################################################### # Class : UserProfileAPIView # Purpose : Implements CRUD using a single endpoints # Workflow : Maps the incoming response (get, post, put, patch, delete) to a method # defined below. … -
Check if is in top value django queryset
I have a django model class City(models.Model): user = models.ForeignKey(User) name = models.CharField() assets = models.PositiveIntegerField() How can I get the first three rows by user? -
Django update_fields not ignoring foreign key on update
When providing the fields for the update_fields parameter I exclude foreign keys for an update. But django seems to include foreign keys causing a ValueError: Cannot assign "1": must be a instance. Take for instance a simple example #model.py class TagType(Model): tag_type = CharField(max_length=16) class Tag(Model): tag_name = CharField(max_length=16) type_fk = ForeignKey(TagType, on_delete=SET_NULL, null=True, related_name='type_fk') # views.py def foo(request): tag = Tag.objects.filter(pk=1) tag.tag_name = "Python" tag.save(update_fields=['tag_name']) I expected the update_fields to update the model with the provided fields, but instead it raises an error on 'type_fk'. ValueError cannot assign "1": 'Tag.type_fk' must be a 'TagType' instance. -
How to have django model utils Choices handle lowercase and uppercase
How can i use uppercase characters when adding a property with lowercase choices this is the payload im using Clover is capitalized but i want to know how i can have capitalized and lowercase Clover work at the same time using model_utils Choices "name": "Test", "pos_name": "Clover", class Tenant(TimeStampedModel): POS = Choices('square', 'clover', 'omnivore') pos_name = models.CharField(choices=POS, max_length=50, blank=True, default='') name = models.CharField(max_length=100) -
Filter Queryset on django-multiselectfield
I'm using django-multiselectfield since I have a legacy project, I need to do a Query about selected options, like I have 1-50 options that could be selected. I understand that since is a CharField I can lookup like this: from django.db.models import Q my_queryset.filter(Q(languages__icontains="0") | Q(languages__icontains="1")) But since there are 50 options, I don't think is a good approach to have 50 Q filters, maybe there is no other option since is just a library instead of a Django internal library, but maybe there is other approach about how to make Q filters dynamic, like counting the len of the Options and then put those values on the Q(languages__icontains="options") but I'm not sure if this is possible. -
how to fix __init__() takes 1 positional argument but 2 were given
i have a search form that return to the user the stored records. what i want is to be able to return the template name and based on the template name. if the template name == "create_folder_test.html" the query will filter on the class Folder if the template name == "blog/list.html" the query will filter on the class suspect what it happen is once the user submit the search form it display the below error : TypeError at /folder/search/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/folder/search/?q=121 Django Version: 2.1.3 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Environment: Request Method: GET Request URL: http://127.0.0.1:8000/folder/search/?q=121 Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'widget_tweaks', 'import_export'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /folder/search/ Exception Value: init() takes 1 … -
Is it possible to parse datetime from CharField within a Django query?
When I was setting up my Django app, I created a CharField instead of DateTimeField for when an account is created. Is it possible to write a Django query that first parses the datetime from my CharField and then uses it in the filter? I know that I could do a migration, but I'm wondering if it's possible to achieve the same result without changing the field to a datetime field. from dateutil.parser import parse from datetime import datetime, timedelta # How I parse datetime from string normally account = Account.objects.get(id=1) datetime_from_string = parse(account.created) # How to filter by datetime with a proper DateTimeField time = datetime.now() - timedelta(hours=5) accounts = Account.objects.filter(created__lt=time) -
Display likers username in html template
I have added a user liking system, where a user can like posts. I have added this successfully, however can't seem to display the usernames of the people who liked the post. This is my current implementation. models.py class Post(models.Model): likes = models.ManyToManyField(User, related_name='likes') @property def total_likes(self): return self.likes.count() views.py def likepost(request, pk): if request.method == 'POST': user = request.user post = get_object_or_404(Post, pk=pk) if post.likes.filter(id=user.id).exists(): post.is_liked = True post.likes.remove(user) post.save() else: post.is_liked = False post.likes.add(user) post.save() return redirect('home') home.html {% for post in posts.all %} <form id="like__post" method="POST" action="{% url 'likepost' post.id %}"> {% csrf_token%} <input type="hidden"> </form> <div style="position: absolute; bottom:80px; left: 85px;"> {% if post.is_liked == True %} <a href="javascript:{document.getElementById('like__post').submit()}"><img src="{% static 'heartred.png' %}" width="35px" height="35px"></a> {% else %} <a href="javascript:{document.getElementById('like__post').submit()}"><img src="{% static 'heart.png' %}" width="33px" height="33px"></a> {% endif %} {% endfor %} So far. In my template i get this: auth.User.None -
django-plotly-dash argument in template
I need to send initial data from my template to my dash script. I found demo of it here looks like this: {</span>% plotly_app name="simpleexample-1" initial_arguments='{"dropdown-color": {"value": "green"}}' %} I need to do the same and do it like this: {% plotly_app name="SimpleExample" initial_arguments='{"id": {"value": "2"}}' %} but how i get in my dash script? (Id should be like variable (i need to use this in all project) ) -
Python sorted() does not work Error: 'list' object has no attribute 'META'
I am getting an error:'list' object has no attribute 'META' when I tried to use sorted() function, and have no idea how to solve it... def sort_by(): data = ['a', 'c', 'b', 'a', 'n', 'j', 'r', 'p', 'x', 'l'] r = sorted(data) print(r) return r -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL
I have a problem when i deploy my django with wsgi, but not in dev mode, I use apache2 My user model is in authentification i've tried to migrate authentification first, but it doesn't work I've also already tried deleting the database, nothing's changed. Here is the stacktrace: AH00094: Command line: '/usr/sbin/apache2' AH00491: caught SIGTERM, shutting down AH00489: Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured -- resuming normal operations AH00094: Command line: '/usr/sbin/apache2' [remote ::1:57132] mod_wsgi (pid=8791): Failed to exec Python script file '/home/roo/myproject/Challenges/Challenges/wsgi.py'. [remote ::1:57132] mod_wsgi (pid=8791): Exception occurred processing WSGI script '/home/roo/myproject/Challenges/Challenges/wsgi.py'. [remote ::1:57132] Traceback (most recent call last): [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 178, in get_model [remote ::1:57132] return self.models[model_name.lower()] [remote ::1:57132] KeyError: 'users' [remote ::1:57132] [remote ::1:57132] During handling of the above exception, another exception occurred: [remote ::1:57132] [remote ::1:57132] Traceback (most recent call last): [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 165, in get_user_model [remote ::1:57132] return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/registry.py", line 210, in get_model [remote ::1:57132] return app_config.get_model(model_name, require_ready=require_ready) [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 181, in get_model [remote ::1:57132] "App '%s' doesn't have a '%s' model." % (self.label, model_name)) [remote ::1:57132] LookupError: App 'authentification' doesn't have a 'Users' model. [remote ::1:57132] [remote ::1:57132] During handling of … -
__init__() takes 1 positional argument but 2 were given | TypeError at /accounts/login/$
I am using Django 2.2 and python 3. When I log in I am getting TypeError at /accounts/login/$ init() takes 1 positional argument but 2 were given Please Find the code of my login.html {% extends 'blog/base.html' % } {% block content %} <div class="jumbotron"> <h2>Please Login:</h2> <h3>(Must be SuperUser, please check with the site admin)</h3> {% if form.errors %} <p>Your Username and password didn''t match! Please try again. </p> {% endif %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} {{% form.as_p %}} <input type="submit" class="btn btn-btn-primary" value="Login"> <input type="hidden" name="next" value="{{next}}"> </form> </div> {% endblock %} Code of Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('accounts/login/$',views.LoginView,name='login'), path('accounts/logout/$',views.LogoutView,name='logout',kwargs={'next_page':'/'}) ] Kindly help -
Plotly dash in Django with multiple users and same chart
I'm completely stuck and wasted so many hours of my life. I've been learning plotly dash in Django for about a week and I just can't find a way to get it to do what I want. I simply want to have a chart that multiple users can see and for it to update for all users when values change. The app will ask all users a question with a rating from 1 to 9. As each user votes a bar chart will show each user's score which they can all see. Can someone please point me in the right direction of a good example or tell me how it's done?