Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to search multiple classes in the model
i have a django project that include 1 model file consist of 2 classes class Folder class suspect Note these 2 classes are not related. i have a search form that allow user to filter in both classes. based on the answer of this question Django search fields in multiple models i used the itertools and import chain but i did not success in returning the correct result. views.py from django.db.models import Q from itertools import chain def searchFolder(request): print("search function") query = request.GET.get('q') folders = Folder.objects.filter(Q(FolderNum__icontains= query)) suspects = suspect.objects.filter( Q(suspect_name__icontains=query)| Q(suspect_father_name__icontains=query)| Q(suspect_mother_name__icontains=query)| Q(content__icontains=query)| Q(create_date__icontains=query) ).distinct() result = chain(folders,suspects) print(result) return render(request,'blog/update2.html',{"result":result}) the result displayed on the templates is <itertools.chain object at 0x000001ACF217DC88> -
Get current user in tasks.py Celery-Django
I'm using Celery in a Django project and I'm trying to get the current user in file tasks.py. I don't want to use "User.objects.get(id)" because I can't pass an argument (id) to the function. Is there something similar to "request.user" that I can use? Thanks a lot. -
django edit inline-formset data
i have a department form with inline formset for deparment's IP list. i'm trying to show the existing department and it's IPs and edit them if needed, but when i submit the form, change_data for form works fine but formset.has_changed always return true. I can add department using this form and formset in another template and everything works fine. but here i want to edit the form(add/remove or edit ips). models.py class Department(models.Model): name = models.CharField(unique=True, max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=200) class Meta: managed = False db_table = 'department' class DepartmentIps(models.Model): department = models.ForeignKey(Department, models.DO_NOTHING) department_ip_from = models.CharField(unique=True, max_length=15) department_ip_to = models.CharField(unique=True, max_length=15) class Meta: managed = False db_table = 'department_ips' forms.py class DepartmentForm(ModelForm): class Meta: model = Department DepartmentIPFormset = inlineformset_factory(Department, DepartmentIps, exclude=('department',), widgets={'department_ip_from': forms.TextInput( attrs={'size': '6', 'class': 'form-control'), 'department_ip_to': forms.TextInput( attrs={'size': '6', 'class': 'form-control'), }, extra=0, can_delete=True, validate_min=True, min_num=1) views.py def setting_department(request, department=1): currnet_d = Department.objects.get(id=department) if request.method == "POST": if 'add-department' in request.POST: department_form = DepartmentForm(request.POST) department_formset = DepartmentIPFormset(request.POST or None, instance=department_form.instance) if department_form.is_valid() and department_formset.is_valid(): new_department = department_form.save() department_formset.save() if 'edit-department' in request.POST: department_form = DepartmentForm(request.POST, prefix='edit', instance=currnet_d) department_formset = DepartmentIPFormset(request.POST or None, prefix='editips') print(department_formset.has_changed()) for formss in department_formset: print(formss.changed_data) print(department_form.has_changed()) department_form = DepartmentForm() … -
Pass JWT token as authorization header to url tag in django template
I want to send authorization header with djnago url template tag. But i am unable to find a solution I tried sending authorization header as query parameter but when i receive the token, i am unable to modify the request header in django views. It only allows to modify the custom header -
Django: IntegrityError when migrating after adding foreign key field
I have three models as follows in a Django app named markets: class Market(models.Model): title = models.CharField(max_length=50, default="") current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.50) description = models.TextField(default="") shares_yes = models.IntegerField(default=0) shares_no = models.IntegerField(default=0) b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open = models.BooleanField(default=True) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Price(models.Model): market = models.ForeignKey( Market, on_delete=models.CASCADE, related_name='prices', default=None) price = models.DecimalField( max_digits=5, decimal_places=2, default=0.50) price_date = models.DateTimeField( default=now, blank=True) def __str__(self): return str(self.price) def get_absolute_url(self): return reverse('market_list') class Share(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, related_name='user_shares', default=None) market = models.ForeignKey( Market, on_delete=models.CASCADE, related_name='market_shares', default=None) share = models.IntegerField(default=0) transaction_date = models.DateTimeField( default=now, blank=True) def __str__(self): return str(self.share) def get_absolute_url(self): return reverse('market_list') I would like to add the following foreign key field to the Price model: user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, related_name='user_prices', default=None) When I run makemigrations on markets, there's no issue. But when I try to actually migrate the database, I get the following error: django.db.utils.IntegrityError: column "user_id" contains null values Why is that? I had no issues adding a user field to the Share model, so am not clear on why I run into problems when also looking to add it to Price. -
Call callable function in django-ratelimit
I have code as follow: callables function def get_limited_num(group, request): if request.user.is_authenticated: qs = NumberOfLimitedLogin.objects.all() if qs is None: return '1/d' data = qs.first() return '{0}/{1}'.format(data.numer, data.unit) return '1/d' ratelimit function @ratelimit(key='post:email', rate=????, method=['POST']) def demo(request): return 'hello' I want to replace ? by the first function, but I don't know how to call. Help me, please. -
Django rest framework | Knox authentication password not hashed in database
I have created serializer for registering users in Django with djangorestframework. I am also using django-rest-knox for token authentication. Problem is that passwords are not hashed in database when creating users. Below is the code of serializer: class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): # user = User.objects.create_user( # validated_data['username'], validated_data['email'], validated_data['password']) user = User( username=validated_data['username'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user Please note that I have tried both commented and uncommented methods of creating user in the above code. In both cases, passwords are saved as raw in database. Below is the part of settings.py related to implementing knox token authentication: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',) } Any suggestions why password are not hashed? -
Test UpdateView for useraccounts application
Test doesn't give status_code 302 in user profile UpdateView and so there's no updates occurs on the object the model code class User(AbstractBaseUser, PermissionsMixin): ''' This a replaced user profile instead of the default django one ''' language_choices=[('en',_('English')),('se',_('Swedish'))] email=models.CharField(verbose_name=_('Email'), max_length=128, blank=False, unique=True) first_name=models.CharField(verbose_name=_('First Name'), max_length=128) last_name=models.CharField(verbose_name=_('Last Name'), max_length=128) joined_at=models.DateField( verbose_name=_('Joined at'), auto_now_add=True, blank=False ) language=models.CharField( verbose_name=_('Language'), max_length=2, choices=language_choices, default=language_choices[0][0] ) active=models.BooleanField(verbose_name=_('Active'), default=False) is_superuser=models.BooleanField(verbose_name=_('Is Superuser'), default=False) is_active=models.BooleanField(verbose_name=_('Is Active'), default=True) is_staff=models.BooleanField(verbose_name=_('Is Staff'), default=False) The form code class EditUserForm(UserChangeForm): ''' Profile form to update existing user information ''' # error message for email matches error_messages = { 'email_mismatch': _("The two email fields didn't match."), } # create field for email email1 = forms.EmailField( label=_("Email"), widget=forms.EmailInput, help_text=_("If you change your email your account will be inactive untill your reactivate by email link."), ) # get the email from confirmed email field email2 = forms.EmailField( label=_("Confirm Email"), widget=forms.EmailInput, help_text=_("Enter the same email as before, for verification."), ) # hide password field password = ReadOnlyPasswordHashField(label="Password") class Meta: ''' Initial fields and model for the form ''' model = models.User fields = ('first_name','last_name','email1','email2', 'language') def clean_email2(self): ''' Method for if email and confirmed email are the same This method works when confirmed email cleared ''' # get … -
Django MySQL REPEATABLE READ "data loss"
I'm looking for information about what is behind the entry in Django 2.0 release notes. Stating: MySQL’s default isolation level, repeatable read, may cause data loss in typical Django usage. To prevent that and for consistency with other databases, the default isolation level is now read committed. You can use the DATABASES setting to use a different isolation level, if needed. As I understand repeatable read is "stricter" than read commited, so what is Django doing to produce "data loss" is a question bugging me for sometime now. Is it stuff like prefetch_related? Or maybe in general making an UPDATE based on potentially stale (SELECTED earlier in a thread) is or can be considered data loos? Or even better - maybe there's something that only MySQL does or has a bug that makes it dangerous on repeatable read? Thank you. -
Django redirect with a custom error message
I'm new in using django templating/frontend and I would like to redirect to a page with a custom message in django. Here's what I've tried but I can't make It work. View return redirect("/login",custom_error="Try Again Later") Login.html {% if custom_error %} <p class="errornote"> {{ custom_error }} </p> {% endif %} Any suggestions on how to make this work? -
How to make all the contents visible in dropdown menu in django?
I have made a dropdown menu so that a user could select one option but whenever I click on dropdown menu, all the contents hide itself except the one I hover a mouse on it. How to make all the contents visible? I think the problem is in profile.html but not understanding how to deal with it? forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','payment_method','detail'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=10, choices=Paymet_choices) profile.html {{p_form|crispy}} -
How to convert an uploaded image to base64 and decode it back, and save the file as PNG?
I'm creating an image upload page which allows users to upload pages. When a user uploads an image, I want to convert that image using base64 and decode it back to a new image and save it in a PNG format extension. How do I do this? You can view my current models.py code: from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, default = 'media/sample.png', validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) -
how to filter a database table row and update a specific column in django?
i have a database table and i want to filter it by id and update a specific object (column) with an if condition that i have write. but it get an error: attributeError: 'int' object has no attribute 'save' if current_complete['current_complete'] == 65 and optimestic: optimestic_percentagex = current_complete['current_complete'] * weight['weight'] if probable or pessimistic: probable_percentage = current_complete['current_complete'] * weight['weight'] pessimistic_percentage = current_complete['current_complete'] * weight['weight'] obj = Forcast.objects.filter(id=id).update(optimestic_percentage=optimestic_percentagex).save() obj.save() i except that i can update optimestic_percentage with the if condition that i have created. -
Why doesn't the 'follow' button on django work?
I'm using Django 2.2 and PostgreSql. I'm trying to create a simple app that I want to follow neighboring users. 'Follow' button will increase the number of followed, 'Unfollow' button will decrease the number of followed. However, the 'Follow' button does not work. How can I solve this problem? following/models.py class Following(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='fallower', null=True) followed = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='fallowing') following/views.py def user_follow_unfollow(request): response = sub_user_follow_unfollow(request) data = response.get('data') followed = response.get('followed') numbers_followed_and_follower= Following.user_followed_and_follower(followed) context = {'user': followed, 'followers': numbers_followed_and_follower['followers'], 'followeds': numbers_followed_and_follower['followeds']} html = render_to_string('following/following_partion.html', context=context, request=request) data.update({'html': html}) return JsonResponse(data=data) templates.following_partion.html {% if request.neighbor_detail != user %} <div> <button followed='{{ neighbor_detail.username }}' followed='{{ request.neighbor_detail.username }}' url="{% url 'following:user_follow_and_unfollow' %}" id="follow_unfollow_button" class="btn btn-lg btn-success"> {% if does_follow_the_user%} <b>Unfollow</b> {% else %} <b>Follow</b> {% endif %} </button> </div> {% endif %} <div class="followers col-lg-offset-3 col-md-3 col-md-offset-3 col-lg-3 text-center"> <span><b>followers</b></span> <button url="{% url 'following:fallowed-or-fallowers-list' 'fallowers' %}" follow_type="followers" username="{{ neighbor_detail.username }}" class="follow_button btn-block btn btn-primary"> {{ followers}} </button> <div class="followeds col-lg-3 col-md-3 text-center"> <span><b>Followeds</b></span> <button url="{% url 'following:followed-or-followers-list' 'followed' %}" follow_type="followed" username="{{ neighbor_detail.username }}" class="follow_button btn-block btn btn-success"> {{ followeds}} </button> my script <script> $("#follow_unfollow_button").click(function () { var $this = $(this); var $url = $this.attr('url'); var $takip_eden = $this.attr('follower'); … -
Path to my media file won't work in django project
I've tried to put my site that I've designed into django, and I've encountered some problemes with paths to my media file in css and javascript but now my css paths work but my javascripts file don't. Thanks in advance for any help provided! I've tried to change my STATIC_URL and all but it didn't work. it seems like django is changing my path for no reason. My project tree: https://ibb.co/DbNB2Tr WORKING: How I wrote my Path into css (works.css in my project) @font-face { font-family: gameboy; src: url('media/font/gameboy.ttf'); } background-image: url('media/gif/drive3.gif'); NOT WORKING: How I wrote my Path into javascript (works.js in my project) var pic1 = 'media/picture/travis.jpg'; var pic2 = 'media/picture/snoop.jpg'; var pic3 = 'media/gif/vash.gif'; var pic4 = 'media/picture/snoop.jpg'; The http response: [07/Aug/2019 10:23:51] "GET /works/media/picture/snoop.jpg HTTP/1.1" 404 3066 My Settings file: Django settings for Music project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Pytest do endless collecting of tests and doesb`t start
When I am running pytest command it starts to collect all tests, but this process is endless without any errors or mistakes. I don't understand what is the reason. If you have any ideas, please could you share them? Also if it helps I run it on MacOS, on my Ubuntu computer it works perfect. This is what happened: Test session starts (platform: linux, Python 3.7.3, pytest 5.0.1, pytest-sugar 0.9.2) Django settings: settings (from ini file) rootdir: /home/roziukp/space11/backend, inifile: setup.cfg plugins: xdist-1.29.0, forked-1.0.2, pythonpath-0.7.3, env-0.6.2, django-3.5.1, sugar-0.9.2, celery-4.3.0, cov-2.7.1, mock-1.10.4 collecting ... -
Django-tables pagination per_page not working as expected
I have a django-tables2 table with pagination via the RequestConfig class. I am trying to limit the results per page to 250 at max, to reduce database load and to keep the table organized. This is my code to limit the per_page GET parameter. def overview(request): # limit results per page to 250 results_per_page = 25 try: results_per_page = int(request.GET.get('per_page')) if request.GET.get('per_page') is not None else 25 sanetized_results = results_per_page if results_per_page <= 250 else 250 results_per_page = sanetized_results except: results_per_page = 25 pass # Create the pagination # BREAKS HERE RequestConfig(request, paginate={'per_page': results_per_page }).configure(table) The first part of the code works. however, at the RequestConfig it still uses the old per_page from the URL. Am I missing something? -
Django detective spots POST requests
I installed django-detective last night and today there are many weird post requests in it. It looks like somebody is trying to post stuff like this on my website: /wp-admin/admin-post.phpnd_stats_value_import_settings=home[nd_stats_option_value]https://jackielovedogs.com/pret Please do not go to this link as I think it might be hosting malware !! What does this mean? How can I prevent this from happening? Thank you -
uwsgi with Django, why have a system wide installation of uwsgi, and how does it integrate with sourcecode?
PS, before someone says it should be posted in serverfault/superuser/swengineering/etc/etc... I just read the descriptions of the related stack exchange websites (https://stackexchange.com/sites), and Stack overflow bests describe me, a programmer, not server maintainer, nor a sw development lifecycle something or other. Additionally, all the related questions I have been reading to do with uwsgi I have been reading are her on SO. Yes this question does not have code, but is related to my codebase. I have tried asking a related question before, only to get told to put it on another site, then on the other side told to put it back on the other site. Sorry, now that is out the way... The question... I have followed the official uwsgi docs to successfully deploy a nginx/uwsgi/django stack. The step I don't understand why is: Install uWSGI system-wide Why does one need to install it system wide for deployment? Why cant the deployment just call my virtual env? If I need the system wide installation, why do I need the virtual env version of uwsgi (is it only for dev purposes)? I dev on a different machine, and use djangos dev server to test with, so I don't need … -
Django How to pass instance to view
I can't find out how to do this, I have a list view, that when you click on one of the list objects, it takes you to an update page, but I can't work out how you pass the instance so to it so that and data posted goes to that instance on the database. CBV do this automatically in a hidden black box way, and I can't see how it is done for a function based view. Model class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def __str__(self): return self.title Form class ProjectUpdateForm(forms.ModelForm): class Meta: model = Update fields = [ 'project', 'category', 'update' ] View def project_update_view(request, slug): obj = Project.objects.get(slug=slug) form = ProjectUpdateForm(request.POST or None) if form.is_valid(): form.save() context = { "form": form, "object": obj } return render(request, 'project_portal/project_update.html', context) url: path('<slug:slug>/update/', project_update_view, name='project-update'), So I want to be able to do away with the 'project' field in the Form because the user is already looking at that instance he shouldn't have to then pick it in the form. -
What do errors "init_1 marked as not fetchable", or "Tensor embedding_2_input:0 not found in graph" mean?
I am using CNNSequenceClassifier from sklearn-sequence-classifiers for sequence prediction. The problem is I have been running into these two errors in a weird kind of way: Tensor embedding_2_input:0, specified in either feed_devices or fetch_devices was not found in the Graph Operation 'init_1' has been marked as not fetchable. The second one happens when I refresh the page and execute the code again (by the way, the whole thing is within a django project) I say weird because my code has two prediction parts. When I run the first one and then the second, the errors do not arise. But when I do the opposite these errors show up. I have searched a lot and there are rare information on solutions people have suggested. And the ones that have been marked helpful are totally different from the structure of my code's prediction. Basically I have no clue what these errors are referring to. Here's what's happening inside the codes (they are functions inside the views.py): from django.http import JsonResponse from django.db.models import Max, Min, Sum, Avg, Q from datetime import timedelta, date import datetime import jdatetime import json import math import numpy as np import operator import shelve import os from … -
Intermittent 500 error when inserting into MySQL from Python Flask App
I keep getting a 500 issue when inserting data into MySql DB. I know when the issue occurs but can't figure out why. When I insert data (e.g. new user) into my DB, I can see it has been inserted correctly from MySql Workbench but about 50% of the time when I call the data thats just been inserted, it returns None After I restart uwsgi (service uwsgi restart) and use the app again, it works as expected until I add some more data then the issue occurs again but only for data inserted after the restart. The app works as expected when running on my local windows machine. Would really appreciate any help on this before my head explodes! This is for a new CentOS 7 Linux server using MySql 8, Python 3.7. I have tried this with 3 different databases with the same result. I have rebooted the server and uwsgi. To recreate, I made testuser@test.com which is correct when getby_email function is called. Basically when the query asks the database for a user with that email, its randomly returns 'None' even though I can see on MySql workbench that the user is in the database. Then when … -
Django: Peer authentication failed for user
I've already a functioning website that use sqlite3 but I prefer to restart my website project with an empty project that immediately use PostgreSQL/PostGIS. At the end of the configuration of settings.py I will make a dump for upload all the sqlite3 tables into the new DB. Nobody models of the old project will modify into this new project. The differece between the old and the new project is only the DBMS. This is settings.py: INSTALLED_APPS = [ ... 'django.contrib.gis', ] ... DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my_project_name', 'USER': 'db_user', 'PASSWORD': 'password_of_db_user', } } After this I've tried to test the server with python3 manage.py runserver but I see this error message: django.db.utils.OperationalError: FATAL: Peer authentication failed for user "db_user" I'm sure that NAME, USER and PASSWORD are correct, the db is in localhost. I've created, a couple of week ago, another simple project to learn GeoDjango with this same settings and that website run fine. -
ImageField not validating
Why isn't Django's ImageField throwing a validation error here? # field in model image_mobile = ImageField( upload_to='static/images/', blank=True, null=True ) # in test from django.core.files.uploadedfile import SimpleUploadedFile attachment = SimpleUploadedFile("file.mp4", b"file_content", content_type="text/plain") obj.image_mobile = attachment obj.save() self.assertEqual(obj.image_mobile, '') Outputs this: AssertionError: <ImageFieldFile: static/images/file_7wanB5P.mp4> != '' From the documentation: Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. -
GET ERROR 500 (Internal Server Error) AJAX DJANGO
I try to achieve a method that when I click the button, the webpage can show different views(based on which button I click). But after I run the server, I get this: jquery.min.js:4 GET http://127.0.0.1:8000/sheet/?Page_1=Page_1 500 (Internal Server Error) I created button divs and used ajax. So if I click Page_1/Page_2/Page_3, the webpage can show up different content. I initial variables Page_1/2/3 and sent them back to Django. In the Django, I will compare data. If they are matched, it will jump to the desired html file web.html .... <button id="Page_1">customer</div> <button id="Page_2">mobile</div> <button id="Page_3">meeting</div> <script type="text/javascript"> $(document).ready(function(){ var id="Page_1" $("#Page_1").click(function(){ $.ajax({ url:"{% url "sheet" %}", data:{Page_1:id}, success:function(result){$("#vizContainersk").html(result);} }); }); }); .... the rest of ajax are same as above one. view.py .... @api_view(['GET']) def get_tableau_url(request): return render(request, 'web.html') def sheet(request): url ='http://xx.xx.xxx.xx:8000/trusted?username=some_name&target_site=demo' result = requests.post(url, timeout=15) context={} context['token'] = result.text q1 = request.GET.get('Page_1') s1 = "Page_1" q2 = request.GET.get('Page_2') s2 = "Page_2" q3 = request.GET.get('Page_3') s3 = "Page_3" if (q1 == s1): return render(request, 'sheet0.html', context) if (q2 == s2): return render(request, 'sheet1.html', context) if (q3 == s3): return render(request, 'sheet2.html', context) I except to solve Internal Server Error