Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change boolean value and refresh page Wagtail
i added a custom button to my page list in my wagtail admin. Now i want to add a function that sets a boolean in that specific page from false to true and vice versa once the admin clicks the new custom button as well as reload the page. #admin.py class ProductButtonHelper(ButtonHelper): # Define classes for our button, here we can set an icon for example view_button_classnames = ['button-small', 'icon', 'icon-site'] def view_button(self, obj): # Define a label for our button text = 'Objavi na Vojvodjanski' return { 'url': obj,#here i think the url should be the same page that you're on 'label': text, 'classname': self.finalise_classname(self.view_button_classnames), 'title': text, } def get_buttons_for_obj(self, obj, exclude=None, classnames_add=None, classnames_exclude=None): """ This function is used to gather all available buttons. We append our custom button to the btns list. """ btns = super().get_buttons_for_obj(obj, exclude, classnames_add, classnames_exclude) if 'view' not in (exclude or []): btns.append( self.view_button(obj) ) return btns Thanks -
Django superuser not having all permissions
While trying to create a Django Rest Framework endpoint for displaying a users permissions, I encountered a problem when it comes to superusers. I thought superusers had all permissions by default, but when I tried to get all permissions for any user through the Permission-model, I got a length difference between the lists. # User is a superuser > len(user.get_all_permissions()) 516 > len(Permission.objects.all().distinct()) 519 Since get_all_permissions() returns a list instead of a QuerySet, I am unable to see exactly which permissions the superuser lacks. Am I wrong in my impression that a superuser has all permissions? Are there other ways to get all permissions for a user in the form of a Permission QuerySet? I could always just return the list given by user.get_all_permissions() instead of a QuerySet, but this confuses DRF-Swagger when it comes to the format of possible responses. -
Create multiple related objects in form, Django template
I'm new to Django and im trying to create a recipebook. I want to create a recipe and in the same form add a variable number of ingredients. In the form the user should be able to fill in one ingredient and click a button to add another as needed. Here are my models: class Recipe(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=128, blank=False) image = models.ImageField(upload_to='recipe_images/', null=True, blank=True) instructions = models.TextField(blank=False) tips = models.TextField(blank=True) cooking_time = models.IntegerField(blank=False, null=False) course = models.ForeignKey("Course", on_delete=models.CASCADE, null=False) category = models.ForeignKey("Category", on_delete=models.CASCADE, null=True, blank=True) tags = models.ManyToManyField("Tag", related_name='recipes', null=True, blank=True) def __str__(self): return self.title class Unit(models.Model): unit = models.CharField(max_length=128, blank=False) def __str__(self): return self.unit class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredients") name = models.CharField(max_length=128, blank=False) quantity = models.DecimalField(max_digits=8, decimal_places=2) unit = models.ForeignKey(Unit, on_delete=models.CASCADE) def __str__(self): return self.name class Course(models.Model): course = models.CharField(max_length=128) def __str__(self): return self.course class Category(models.Model): category = models.CharField(max_length=128, blank=False) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=64, blank=False) def __str__(self): return self.tag I'm breaking my head over how to do this in the template. I could create a form for the recipe with a modelform and create a seperate list with javascript for the ingredients and send in in json … -
Good practice to implement a ThreadPool of intensive processing inside a Django App
I'm working with Django using Daphne (so, It's an async app). In my site users can run expensive experiments. I'd like the users not to wait, so I decided to implement a "global" ThreadPool running in background. These are the steps I followed: I made a Singleton service: class TaskQueue(object): def __new__(cls): if cls.instance is not None: return cls.instance else: # Creates the instance cls.instance = super(TaskQueue, cls).__new__(cls) cls.instance.executor = ThreadPoolExecutor(max_workers=settings.THREAD_POOL_SIZE) # Gets the pending experiments cls.instance.get_not_computed_experiments() return cls.instance def eval_mrna_gem_experiment(self, experiment: Experiment) -> None: # Some long code... def add_experiment(self, experiment: Experiment): self.executor.submit(self.eval_mrna_gem_experiment, experiment) @lru_cache(maxsize=None) def get_queue(): """ Caches the TaskQueue instantiation """ return TaskQueue() Every time a user makes a request to execute an experiment I do: get_queue().add_experiment(new_experiment) I think this way there's a global queue which computes the experiments in order. The questions are: Is there a correct way to implement that? Keep in mind that in eval_mrna_gem_experiment I make several call to R apis in the SO using rpy2, so I don't know if It's a bad practice as there is a Main Thread (the app) deploying a ThreadPool which calls R code which has several threads running to compute expensive stuff. Does Singleton pattern apply … -
Django 'function' object has no attribute '_meta'
I have a simple Django app where I want to display and save some data from a model. This is my model class Curr(models.Model): name=models.TextField(default='USD') value=models.DecimalField(max_digits=10, decimal_places=5, default=0) My Model Form class CurrForm(forms.ModelForm): class Meta: model = Curr fields = '__all__' My View currency = Curr.objects.all() if request.method == "POST": post_values = request.POST.copy() form = CurrForm(post_values, instance=currency) This gives the error 'function' object has no attribute '_meta' Reading the other similar posts did not clear my doubts. Any help is appreciated. -
Class based view Django
how convert this code to class based code def detail_article(request, slug): context = { "article": get_object_or_404(Articles, slug=slug, state="p") "slider" : Articles.objects.filter(state="p").order_by('-publish')[:20] } return render(request, "blogApp/detail_article.html", context) I tried this : class ArticleDetail(DetailView): context_object_name = 'slider' def get_queryset(self): return Articles.objects.filter(state="p").order_by('-publish')[:6] def get_object(self): slug = self.kwargs.get("slug") return get_object_or_404(Articles, slug=slug, state="p") but I got this error : 'Articles' object is not iterable and also i have for loop in my template on slider -
Django No WSGI daemon process has been configured
I have a Django project loaded up with Lightsail. I'm looking to get it to run with Apache. I've followed the tutorial located here, but for some reason, it is throwing the following site error and apache error when trying to connect to the server by just it's IP. Getting the following error when hitting my site: 500 Internal Server Error When looking at my Apache Logs No WSGI daemon process called 'smp_api' has been configured: /home/ubuntu/test/smp_api/wsgi.py, WSGI.py File import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smp_api.settings") application = get_wsgi_application() Apache Conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/test/static <Directory /home/ubuntu/test/static> Require all granted </Directory> <Directory /home/ubuntu/test/smp_api> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /test> Require all granted </Directory> WSGIDaemonProcess python-path=/home/ubuntu/test WSGIProcessGroup smp_api WSGIScriptAlias / /home/ubuntu/test/smp_api/wsgi.py </VirtualHost> -
unable display variables on webpage in Django
I am unable to show data from the database to HTML. I am getting ordered dict from the serializer. views.py material_class = Material.objects.filter(material_class=user_class.user_class) data = MaterialSerializer(material_class, many=True) content = {'material':data.data} # In *data.data* I am getting this [OrderedDict([('id', '123'),('material','456')]), OrderedDict([('id','345'),('material','789')])] return render(request, 'dashboard/dashboard.html',content) dashboard.html {% load static %} {% csrf_token %} <!DOCTYPE html> <html lang="en"> <head> {% block content %} {% for a in content %} <p>{{ a }}</p> {% endfor %} {% endblock %} </head> </html> -
token authentication POST method
I have an api(DRF based) for my project which needs token based authentication for POST Method and in my project I use REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } As for frontend , for every POST method I am using const config = { headers: { "Content-type": "application/json", Authorization : `JWT ${localStorage.getItem("access")}`, Accept: "application/json", }, }; axios.post( `...................................`, config, ) This is working fine for POST Methods in my project.But it will expire in 5 min.Which token should I use for authentication. -
Django Login form Using AD
I'm trying to create an App which has a log in page where user should be authenticated using azure AD. Basically the App has a log in form where user puts his id and password from ad and django should check with ad and allow him in or not. Later on ofc would like to add permission depending on AD group. So far I searched a lot on the internet and found nothing. Could you guys help with some example or link to documentation what I could use. -
Django login form not keeping input after bad submit
I have a login form and if a user enters an invalid username or password, the page refreshes and removes the Username value they entered. I would like it so that the username field doesn't empty on failed submit. views.py def login_page(request): if request.user.is_authenticated: return redirect('dashboard:dashboard') elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: messages.info(request, 'Username or Password is invalid.') return render(request, 'main/login.html', {}) login.html: <form id="login-form" action="" method="post" role="form"> {% csrf_token %} <div class="form-group"> <input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value=""> </div> <div class="form-group"> <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 center" style="border-radius: 16px;"> <input type="submit" name="login-submit" id="login-submit" tabindex="5" class="form-control btn btn-login" value="Login"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-lg-12"> <div class="center"> <a href="#" tabindex="5" class="forgot-password">Forgot Password?</a> </div> </div> </div> </div> </form> -
how avoid reinitilizing AXES_COOLOFF_TIME when user tray again during lock out time?
I integrated django-axes to my django application whith the following configs : 15 minutes (as timedelta object for minutes) AXES_COOLOFF_TIME = timedelta(minutes=15) Here are the spteps : 1 - I tried 3 time to connect with correct user and wrongs password --> result : the user is locked out (i see the messsage : user locked out during 15 min) 2 - after 10 minutes, i try again to connect with correct user and password --> result : the user is locked out again and have to wait another 15 minites ! in total i lost 25 mintes waiting instead to 15 ! Is there a way to avoid this probleme ? I want to use the first duration and not account the second Appreciate you help -
django data migrations: how to manage INSERT with related models?
I have a Django project with Postgresql database. I want to run data migration when deploying my app to create account, etc... I try to write a data migrations files but have an error "NOT NULL constraint failed" on second insert below I understand the error: as RunSQL is atomic, when I try to run the second INSERT INTO auth_user, SELECT id FROM auth_user WHERE username='user' return null because RunSQL is atomic so user is not yet created and commit in database. Django documentation about data migration mentionned possibility to run non-atomic transactions but not sure it is the best way to proceed migration_files class Migration(migrations.Migration): dependencies = [ ('parameters', '0010_auto_20200327_1508'), ] operations = [ migrations.RunSQL( sql = [ "INSERT INTO auth_user (password,is_superuser,username,first_name,last_name,email,is_staff,is_active,date_joined) VALUES ('pbkdf2_sha256$150000$qe1v2XJKkik8$jF6iFZ+4GpK1JzBdHzRG0H3XsYY+YphYpxc9Cbgg+7Y=',False,'user','','','jerome.le-carrou@u-bordeaux.fr',False,True,'2020-10-15 10:00');", "INSERT INTO auth_user_user_permissions (user_id,permission_id) VALUES ((SELECT id FROM auth_user WHERE username='user'),(SELECT id FROM auth_permission WHERE codename='can_manage_randomization'));", ] ) ] -
django: pasting text of a pdf file gathered using choose file button in a textarea
I am new to Django and currently, I am working on a website where I have a choose file button and a text area. I want that when I click on the choose file button and choose a .txt or .pdf file, all the text from that file has to show in the textarea alongside it. here is the GUI here is the look but this thing is not working. I have tried a lot of solutions but nothing is working for me. I am using python version 3.8 and Django version 3.1 here is the models.py class text_file(models.Model): txtfile = models.FileField() text = models.TextField(max_length=10000) date = models.DateTimeField(auto_now=True) #data saved into db def __str__(self): return self.text_file here is my fileactions.py file. It's a model form. from PyPDF2 import pdf, PdfFileReader from django import forms from .models import text_file class filetext(forms.ModelForm): text_file = forms.FileField(required=True, widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'text_file...', 'id': 'input1' } )) class Meta: model = text_file #import text_file model from home models.py fields = {'text_file'} def save(self, commit=True): filename = input('file') textfile = open(filename, 'rb') pdf_reader = pdf.PdfFileReader(textfile) page_numbers = pdf_reader.getNumPages() title = pdf_reader.documentInfo.title print("the document title is: ", title) print("there are total: ", page_numbers, "pages") count = … -
Django CMS Dashboard Customize by React.js
Hope you all are doing well ! I would like to convert my Django CMS Dashboard Customize by React.js .. Is that possible to use React.js only in Dashboard, not in the whole Front-end -
Django Report Builder - invalid literal for int() with base 10: ''
I am trying to use Django-Report Builder to create reports. But after creating the reports when I click on XLSX or CSV it gives me this error Request Method: GET Request URL: https://something.pythonanywhere.com/report_builder/api/report/1/download_file/xlsx/ Django Version: 2.2.7 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /home/something/.virtualenvs/quizdemo/lib/python3.8/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 972 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.0 Python Path: ['/var/www', '.', '', '/var/www', '/home/hrtest/.virtualenvs/quizdemo/lib/python38.zip', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8/site-packages', '/home/hrtest/quizdemo'] Server time: Tue, 20 Oct 2020 11:49:17 +0000 This works perfectly in my local host. I am not sure what is missing. When I click on Preview I get javascript error: polyfills-es2015.js:1 GET https://something.pythonanywhere.com/report_builder/api/report/1/generate/ 500 (Internal Server Error) This seems to be specific problem to pythonanywhere. How could I get more details for this issue ? Any help from users who have used Report Builder -
Restricted access for different user categories in Django app
I am somewhat new to the django framework so excuse me if this question isn't appropriate. I have a django app wherein I am using the built-in User model which django provides to store user details. I need to give access to some features of the app only to paid users. I have another Activation model which stores a boolean flag which indicates whether this is a free user or a paid user. This Activation model has user as a foreign key. Now, I need access to this boolean flag in my template context. The approach which I don't think is appropriate is to add this in every context response where it would be needed. But this would be a bad design perhaps and would require significant changes in existing code. Is there a way to access this without have to send this flag in every context where it's needed, similar to the way user model is accessed to check if user is authenticated ? Perhaps the most appropriate way would have been to create a custom user model by sub-classing the django user model and add this flag in there. But since this would require significant changes in design, … -
how to pass object id from template to a view upon the click of a button in django
so I am trying to make a website that has different products and that has an add to cart button. what I am trying to do is pass the object id from the template to django view so I can make an instance of the product in the database. but I don't know how. I tried ajax but I don't really know how to use it so it didn't work and I don't know the problem. here is my ajax code : homepage/index.html : {% for product in products %} <li> <figure> <a class="aa-product-img" href="{% url 'home:productdetail' product.id%}"><img src="{{ product.picture.url }}" alt="polo shirt img"></a> #This is the button <a class="aa-add-card-btn" href="#" data-objid="{{product.pk}}"><span class="fa fa-shopping-cart"></span>Add To Cart</a> <figcaption> <h4 class="aa-product-title"><a href="{% url 'home:productdetail' product.id %}">{{product.title}}</a></h4> <span class="aa-product-price">${{product.price}}</span><span class="aa-product-price"></span> </figcaption> </figure> </li> {% endfor %} <script type="text/javascript"> $('.aa-add-card-btn').click(function(){ var objid; objid = $(this).attr("data-objid"); $.ajax( { type:"POST", url: "{% url 'home:cart' %}", data:{ product_id: objid }, success: function( data ) }) }); homepage/views.py : def addtocart(request): if request.method == 'POST': print('it worked') current_user = request.user user = User.objects.get(id=current_user.id) product_id = request.POST['product_id'] cartproduct = CartModel(products=product_id, customer=user) cartproduct.save() ctx = { 'products': CartModel.objects.all() } return render(request, 'homepage/index.html', ctx) homepage/models.py : class CartModel(models.Model): customer = models.ForeignKey(User, … -
Celery periodic task for deleting expired database objects running successfully but the object is not getting deleted from the database
I have a periodic task to delete expired files which is running every 1 minute(just for testing), the task is showing successful everytime, but the object is not getting deleted from the database. I used print to see whether it is getting the correct data and it seems it does receive everything correctly. I also restarted it few times, still doesn't work. Is is because of any time difference problem? But if that's the case, will the task run successfully? @periodic_task(run_every=crontab(minute='*/1')) def delete_expired_files(): files= Post.objects.all() # Iterate through them for file in files: expiry_date = file.created_date + datetime.timedelta(seconds=30) # for testing print(expiry_date) if file.created_date > expiry_date: file.delete() return "Deleted the file at {}".format(timezone.now()) Is there something wrong with the code regarding the expiry date? Thanks -
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I try to install mysqlclient in fedora
I want to connect mysql to my django project I try to install mysqlclient and got error I use Linux fedora os and I want to connect myq to my django project for which I have to install mysqlclient I run command pip install mysqlclient ,then try pip install mysqlclient==1.3.12 I also try that commands in virtual env and got the same error I installed python-devel by using yum install python3-devel inside root after that i try for installing libmysqlclient by using yum install mysql-devel i gives me an error and then I try dnf install libmysqlclient-dev got the error after running pip install mysqlclient i got this error shown in image in the link below -
How can I erase and send a field that is not null from json in django rest framework?
I am going to send an image to the django rest framework. When we try not to put the data in the image field, we are now putting it in the following way: { .... "image": null } By the way, I would like to send you a field called image, instead of sending null like this, delete it from Json as follows. { .... } How can you do this? Here's my code. serializers.py class customRegisterSerializer (serializers.ModelSerializer) : email = serializers.CharField(allow_null=True) password = serializers.CharField(max_length=999, min_length=8, write_only=True, allow_null=True) username = serializers.CharField(allow_null=True) image = serializers.ImageField(allow_null=True, use_url=True) class Meta : model = User fields = ['email', 'username', 'image', 'password'] def validate (self, attrs) : email = attrs.get('email', '') password = attrs.get('password', '') username = attrs.get('username', '') error = {} if email is None and password is None and username is None : error['message'] = '이메일, 비밀번호 그리고 이름을 입력해주세요' raise serializers.ValidationError(error) if email is None and password is None : error['message'] = '이메일과 비밀번호를 입력해주세요.' raise serializers.ValidationError(error) if email is None and username is None : error['message'] = '이메일과 이름 입력해주세요.' raise serializers.ValidationError(error) if email is None and password is None : error['message'] = '이메일과 비밀번호를 입력해주세요.' raise serializers.ValidationError(error) if email is … -
Error: Reverse for 'coach_profile' with arguments '('',)' not found. 1 pattern(s) tried: - Unable to resolve
I am trying to create a directory-based website. I have created a list view, and I have created a detail view that populates when you click on an item in the list view. But, I also want to use a similar detail view to serve the user's own data to them on a profile page. I have done this by creating a queryset in a separate view. The problem is, is that I don't seem to be able to configure the urls and template tag correctly to get it to show on the page, and I am just getting the following error. Reverse for 'coach_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['coach/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/profile$'] I am trying to access this page from a link on the navbar called your profile. The template tags I am trying are as follows href="{% 'coach_profile' %}">Your Coach Profile</a> href="{% 'coach_profile' coach.id %}">Your Coach Profile</a> href="{% 'coach_profile' coach.pk %}">Your Coach Profile</a> ulrs.py from django.urls import path from .views import CoachListView, CoachDetailView, CoachProfileView urlpatterns = [ path('', CoachListView.as_view(), name='coach_list'), path('<uuid:pk>', CoachDetailView.as_view(), name='coach_detail'), path('<uuid:pk>/profile/', CoachProfileView.as_view(), name='coach_profile'), ] views.py from django.views.generic import ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Profile class CoachListView(LoginRequiredMixin, ListView): model = Profile … -
How can i publish a django project on IIS?
Question is quite simple. I've a project that i wrote in PyCharm IDE. This is going to be my first deployment and i couldn't find any source to follow. I am grateful for any help or tip. -
ModuleNotFoundError: No module named 'app.wsgi'; 'app' is not a package
sudo systemctl status gunicorn outputs ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-10-19 15:24:42 UTC; 19h ago TriggeredBy: ● gunicorn.socket Main PID: 133699 (code=exited, status=3) Oct 19 15:24:42 django-domainname gunicorn[133714]: return _bootstrap._gcd_import(name[level:], package, level) Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked Oct 19 15:24:42 django-domainname gunicorn[133714]: ModuleNotFoundError: No module named 'app.wsgi'; 'app' is not a package Oct 19 15:24:42 django-domainname gunicorn[133714]: [2020-10-19 15:24:42 +0000] [133714] [INFO] Worker exiting (pid: 133714) Oct 19 15:24:42 django-domainname gunicorn[133699]: [2020-10-19 15:24:42 +0000] [133699] [INFO] Shutting down: Master Oct 19 15:24:42 django-domainname gunicorn[133699]: [2020-10-19 15:24:42 +0000] [133699] [INFO] Reason: Worker failed to boot. Oct 19 15:24:42 django-domainname systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Oct 19 15:24:42 django-domainname systemd[1]: gunicorn.service: Failed with result 'exit-code'. My directories are as follows My-Project - ./ - ../ - .DS_Store - .git/ - .idea/ - .travis.yml - Dockerfile - docker-compose.yml - env/ ( ./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) - requirements.txt - My-Project/ ( ./ … -
How to compare created time to 24 hours to delete a file in django/python?
I am trying to implement a function where a file will be deleted after 24 hours and I have celery doing this task. I don't want to have another field as an expiration_date in the model, so is there a way to compare the created time to 24 hours and delete the file? if file.created_time > 24 hours (# here how can I change this to check with real time): file.delete() and created_time is a DateTimeField(). Thanks