Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call function on button click in Django without using url action
I want to call a function in django with a dynamic form without changing the form action. In my template: <div class="specform"> {% for field in form1 %} <form method='GET' action="remove"> {% csrf_token %} <button type="submit">Remove</button> </form> {% endfor %} </div> Is there a way to customize the GET request so that the request includes {{field.name}}, so that one view can call a function with {{field.name}} as the argument? views.py def myView(request): remove(field.name) ex: GET: /website/page?Remove=field1 -
Errno 71: Protocol Error when trying to save Django Model on Vagrant server
I'm currently trying to save a Django model on Vagrant that has a PhotoField. I overwrote the save function per below: def save(self, **kwargs): if self.logo_url and not self.logo: response = requests.get('https://logo.clearbit.com/{}'.format(self.logo_url), stream=True) self.logo = ContentFile(response.content) self.logo.name = self.logo_url + '.png' super().save(**kwargs) Those fields in the model are defined like this: logo_url = models.URLField(blank=True, null=True) logo = models.ImageField(blank=True, null=True) When I try to save an instance of this model, I get the following error: OSError: [Errno 71] Protocol error: '/vagrant/media/http:' I checked the permissions and they are all 777. Does anybody know why this would be happening? The error occurs on the super().save(**kwargs) line. -
Dropdown not appearing in Modal
Basically the title. On clicking the dropdown button, the html updates to the dropdowns expanded form, but nothing is happening within the modal. This along with other issues (modal works but modal fade doesn't appear at all), has been plaguing my project. I've been using these scripts <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <!-- Additonal Scripts--> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> I am using this bootstrap template and due to the need to resolve other jquery issues, have been loading the scripts above after the ones included with the template - but testing has shown that this isn't the problem. Any suggestions at this point? The modal code (Django backend) <div class="modal" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header align-content-md-stretch"> <h4 class="modal-title" id="myModalLabel">Image preview</h4> </div> <div class="modal-body"> <div class="container-fluid"> <div class="row"> <img src="" id="imagepreview" style="height: auto; width: auto; max-width: 800px;"> </div> </div> </div> <div class="modal-footer"> <div class="btn-group"> {% if package %} <button class="btn btn-success">Add to package</button> {% endif %} <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Add Item </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for product in products %} <a class="dropdown-item" href="#">{{ product }}</a> {% endfor %} </div> </div> … -
Unable to import 'dj_database_url'
I'm uploading a basic application made with Django to Heroku and I'm installing the package dj-database-url with pip3 install dj-database-url and then doing pip3 freeze > requirements.txt. But Django is not able to detect this package, in fact the code editor is not able to detect it either. That suggests that it's installing badly but I've tried everything and I don't know what to do. This is my requirements.txt: asgiref==3.2.10 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 cliapp==1.20180812.1 click==7.1.2 dj-database-url==0.5.0 Django==3.1 django-cors-headers==3.4.0 djangorestframework==3.11.0 djangorestframework-jwt==1.11.0 gTTS==2.1.1 gTTS-token==1.1.3 gunicorn==20.0.4 idna==2.10 Markdown==3.1.1 packaging==20.3 psycopg2==2.8.5 Pygments==2.3.1 PyJWT==1.7.1 pyparsing==2.4.6 python-dotenv==0.14.0 pytz==2020.1 PyYAML==5.3.1 requests==2.24.0 six==1.15.0 soupsieve==2.0.1 SpeechRecognition==3.8.1 sqlparse==0.3.1 ttystatus==0.38 urllib3==1.25.10 whitenoise==5.2.0 The error is Unable to import 'dj_database_url' -
Django: Cleaning SQLite d/b for obsolete apps/models
I'm new to Django and wanted to clean some invalid d/b objects that were created as part of some model creation which is no more valid. Is there a script to remove unused d/b objects from SQlite? -
Styling Django Model forms
I was just wondering how do you style django model forms? I already made the css file but I don't know how to put classes in Model Form tags.' Regards -
is it possible to use django with flutter for a ios and android mobile apps?
i want to build a mobile app. i only know Django and am currently learning flutter. after learning flutter would it be possible to use Django and flutter to build a mobile app on ios and android. maybe also desktop? if no what can be an alternative to Django for mobile app development? i don't have a lot of experience in mobile app development. -
OperationalError at /cart/add-to-cart/newlife/ no such column: shopping_cart_order.user_id
models.py from django.conf import settings from django.db.models import Sum from django.db import models from books.models import Book class OrderItem(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return self.book.title class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) ref_code = models.CharField(max_length=50) def __str__(self): return self.user.username def get_total(self): return self.items.all().aggregate(order_total=Sum('book__price'))['order_total'] class Payment(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) amount = models.FloatField() date_paid = models.DateTimeField(auto_now_add=True) stripe_charge_id = models.CharField(max_length=100) def __str__(self): return self.stripe_charge_id template {% extends 'base.html' %} {% block breadcrumb %} <li class="breadcrumb-item" aria-current="page"> <a href="{% url 'books:book-list' %}">Book List</a></li> <li class="breadcrumb-item active" aria-current="page">{{ book.title }}</li> {% endblock %} {% block content %} <div class='row'> <main class='col-md-4'> <div class="card"> <div class='card-header'>{{ book.title }}</div> <img src="{{ book.cover.url }}" class="card-img-top" > <div class="card-body"> <p class="card-text">Published: {{ book.publication_date }}</p> </div> <div class='card-footer'> {% if in_cart %} <a href="{% url 'cart:remove-from-cart' %}" class='btn btn-default btn-block'> Remove from Cart </a> {% else %} <a href="{% url 'cart:add-to-cart' book.slug %}"class="btn btn-warning btn-block"> Add to Cart </a> {% endif %} </div> </div> </main> <aside class='col-md-8'> <div class="card" style="width: 18rem;"> <div class="card-header"> Chapters </div> <ul class="list-group list-group-flush"> {% for chapter in book.chapter_set.all %} <li class="list-group-item"> <a href="{{ chapter.get_absolute_url }}"> {{ chapter.chapter_number }}.{{ chapter.title }} </a></li> {% endfor %} </ul> </div> </aside> … -
Running Python Scripts in Django and displaying responses
I am creating a Django site that integrates into the UniFi controller, I have managed to get a script working that uses the pyunifi package, what I want to do is be able to execute this script from within Django and display the responses on a page within the site. Currently the script can run on it's own and can output the data I want into the terminal. Thank you -
massive error when trying to install psycopg2 on mac os catalina
I am trying to intall the packages needed for a django project. It uses postgres as the database. so far I tried intalling postgres via homebrew and exported the bath to my bin path. When I run the commant pip install -r requirements.txt I get a massive error when it wants to install psycopg2. ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 -
Template caching stopped working in Django
I am using Django 1.5.2. Yes, it's old. I'm also using Python 2.7. I'm on CentOS 7. Years ago I set it up such that it used cached templates. That made a huge difference in performance. However, at some point, it has stopped working, and I don't know why. I noticed that rendering was slow. I test the cache by changing an HTML file (that is rendered) and seeing if the change goes through. It used to be that I had to restart Apache before the change took effect, but now the new template is rendered and displayed right away. I have tried restarting the server, but that didn't fix anything. These are my settings: DEBUG = False TEMPLATE_DEBUG = False TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', )), ) -
Migrating models to their corresponding database in django
I want to migrate Model1 into database1 and model2 into database2 -
Unable to deploy django app which uses rpy2 on Heroku
I want to deploy a django application which uses rpy2 on heroku. However I am getting the following error when I use the git push heroku master: remote: Collecting rpy2==3.3.5 remote: Downloading rpy2-3.3.5.tar.gz (174 kB) remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-jnk6jcjm/rpy2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-jnk6jcjm/rpy2/setup.py'"'"'; f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"'); f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-w_5evtsp remote: cwd: /tmp/pip-install-jnk6jcjm/rpy2/ remote: Complete output (2 lines): remote: cffi mode: CFFI_MODE.ANY remote: Error: rpy2 in API mode cannot be built without R in the PATH or R_HOME defined. Correct this or force ABI mode-only by defining the environment variable RPY2_CFFI_MODE=ABI remote: ---------------------------------------- remote: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to hla-algorithm. remote: To https://git.heroku.com/hla-algorithm.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/hla-algorithm.git' After reading the solution on Heroku RPy RHOME discovery, I set the following as my config variables but still get the same error - PATH - /app/vendor/R/bin:/app/vendor/gcc-4.3/bin:/app/.heroku/python/bin:/usr/local/bin:/usr/bin:/bin LD_LIBRARAY_PATH … -
Order object not iterable in python error in django
This is my models.py: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False,null=True,blank=False) transaction_id=models.CharField(max_length=100,null=True) This is my views.py: def lobby(request): customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) shippingddress=ShippingAddress.objects.filter(customer=customer) context={ 'order':order, 'ship':shippingddress } return render(request,"lobby.html",context) and this is my html: {% for ord in order %} <div class="single_confirmation_details"> <h4>Order Info</h4> <ul> <li> <p>Order Number</p><span>: {{ord.id}}</span> </li> </ul> </div> {% endfor %} I am getting this error:'Order' object is not iterable I dont know why this error is coming. I have passed shippingaddress in context which is working fine but for Order it is showing error. Please help me with this. -
django save() takes 1 positional argument but 2 were given
I'm producing django rest auth custom user. After implementing and testing the serializer and view for membership registration, the following error appears after pressing post: TypeError at /signUp save() takes 1 positional argument but 2 were given I think it's a problem with serializer, but I don't know the exact cause. Can you help me? Here is my code. serializers.py from rest_framework_simplejwt.serializers import TokenObtainSerializer from .models import User from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from django.utils.translation import ugettext_lazy as _ class CustomRegisterSerializer(RegisterSerializer): nickname = serializers.CharField(required=True) profile = serializers.ImageField(use_url=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password1(self, password): return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'email': self.validated_data.get('email', ''), 'password': self.validated_data.get('password', ''), 'nickname': self.validated_data.get('nickname', ''), 'profile': self.validated_data.get('profile', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user class userSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email','password', 'nickname','profile') views.py class customSignUpView (RegisterView) : serializer_class = userSerializer models.py class UserManager(BaseUserManager): use_in_migrations = … -
Django using a ModelForm to update certain fields of model where the instance depends on dropdown list
I have the following model: class Medicine(models.Model): Medicine_Name = models.CharField(max_length=100) User_Associated = models.ForeignKey(User, on_delete=models.CASCADE) Tablets_In_Box = models.IntegerField() Dose_in_mg = models.IntegerField() Dose_Tablets = models.IntegerField() Number_Of_Boxes = models.IntegerField() Last_Collected = models.DateField() def __str__(self): return self.Medicine_Name def get_absolute_url(self): return reverse('tracker-home') I have created a modelform based on this model, and I want to be able to the user to be able to select one of their medicines from a dropdown list, and then update the existing 'Number_Of_Boxes' and 'Last_Collected' fields of my Medicine model. Here is my modelform: class CollectionForm(forms.ModelForm): Medicine_Name = forms.ModelChoiceField(queryset=Medicine.objects.all()) class Meta: model = Medicine fields = ['Medicine_Name', 'Number_Of_Boxes', 'Last_Collected'] def __init__(self, user = None, *args, **kwargs): super().__init__(*args, **kwargs) if user: self.fields['Medicine_Name'].queryset=Medicine.objects.filter(User_Associated=user) I am struggling to create a view for this form. In particular, I don't understand how to pass in the instance argument into my form. My problem is the instance, of course, depends on whatever the user chooses from the dropdown menu, but I fail to see where I can get the primary key of the instance from. Do I need to handle this from within the form, or the view? The solutions I have found online seem to have a static primary key, so there is no … -
How to fix error of dependencies in Django app deployment to heroku
I'm trying to upload a simple Django project to Heroku using Heroku CLI and using WSL on Windows. However, when I try to git push heroku master I get the following error Enumerating objects: 41, done. Counting objects: 100% (41/41), done. Delta compression using up to 8 threads Compressing objects: 100% (37/37), done. Writing objects: 100% (41/41), 15.68 KiB | 86.00 KiB/s, done. Total 41 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.11 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.10 remote: Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) remote: Collecting beautifulsoup4==4.9.1 remote: Downloading beautifulsoup4-4.9.1-py3-none-any.whl (115 kB) remote: Collecting certifi==2020.6.20 remote: Downloading certifi-2020.6.20-py2.py3-none-any.whl (156 kB) remote: Collecting chardet==3.0.4 remote: Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) remote: ERROR: Could not find a version that satisfies the requirement cliapp==1.20180812.1 (from -r /tmp/build_eb2023b0/requirements.txt (line 5)) (from versions: 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6, 1.0.7, 1.0.8, 1.0.9) remote: ERROR: No matching distribution found for cliapp==1.20180812.1 (from -r /tmp/build_eb2023b0/requirements.txt (line 5)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: … -
How to change the queryset of a filter based on another filter in Django?
I have a filter such as this: class SubmissionsFilter(FilterUserMixin): submission_status = django_filters.ChoiceFilter(choices=CONTEST_STATUS_CHOICES, empty_label="---Status---", method='filter_submission_status') place__region = django_filters.ModelChoiceFilter(queryset=ContestRegion.objects.all().order_by('name'), empty_label='---Región---') place = django_filters.ModelChoiceFilter(queryset=ContestMunicipality.objects.all().filter().order_by('name'), empty_label='---Municipio o Estado---') category = django_filters.ModelChoiceFilter(queryset=ContestCategory.objects.all(), empty_label='---Categoría---') def filter_submission_status(self, queryset, name, value): queryset = queryset.filter(submission_status=value) return queryset class Meta: model = ContestSubmission fields = ("submission_status", "category", "place", "place__region") And I want the user to be able to filter by its Place object, or by the Region parameter in the Place object. For example, one of the Region registers is 'USA', and some places, like 'California', 'Oregon', etc., have the 'USA' Region object as one of its parameters. I want the users to be able to filter the submissions either by the whole region, or by each Place. This works fine, and both filters display. The thing is, to make it faster to use, I want to know if I can change the queryset of the filter 'place' when the user has changed the 'place__region' filter. For example, when the user selects the object 'USA' in the place__region filter, I want to change the queryset of the place filter to only show the options whose Place are in that Region that was selected, is there a way to do that, … -
Django ManyToMany overwritten when saving CustomUser model
Overview I'm in the process of creating a friendship model to track users who follow each other. I've created a CustomUser model that extends AbstractUser and a separate UserRelationship model which is used to create/track the interaction. I also have a signal.py file that handles the actual saving between the two models (CustomUser & UserRelationship). The Issue When creating a friendship (User with PK=1 follows user with PK=2), the Following ManyToMany field for user with PK=1 is updated correctly, however if user with PK=1 updates their profile, all ManyToMany fields are wiped. Models CustomUser class CustomUser(AbstractUser): # Model manager objects = CustomUserManager() # Local email = models.CharField(max_length=80, blank=True) biography = models.CharField(max_length=100, blank=True) photo = models.ImageField( upload_to="users/%Y/%m/%d/", blank=True, default="static/images/default_profile_pic.png", ) hidden = models.BooleanField(default=False) # ForeignKey following = models.ManyToManyField( "CustomUser", related_name="followings", blank=True ) follower = models.ManyToManyField( "CustomUser", related_name="followers", blank=True ) blocked = models.ManyToManyField("CustomUser", related_name="blocks", blank=True) blocked_user_visible = models.ManyToManyField( "CustomUser", related_name="block_user_visible", blank=True ) hidden_request = models.ManyToManyField( "CustomUser", related_name="hidden_requests", blank=True ) def get_relationships(self): return self.relationship.all() def get_following(self): return self.followings.all() def get_relationships_number(self): return self.relationship.all().count() def __str__(self): return self.username def get_absolute_url(self): return f"/users/{self.username}" UserRelationships Model class UserRelationship(models.Model): STATUS_CHOICES = ( ("sent", "sent"), ("accepted", "accepted"), ("deleted", "deleted"), ("blocked", "blocked"), ) # Local status = models.CharField(max_length=8, choices=STATUS_CHOICES, blank=True) … -
Django migrations aren't working on Heroku
I have a Django app and the migrations works only locally. I added the migrations folder to source control, I put release: python manage.py migrate in Procfile, I run the migration with makemigrations and migrate on bash, deleted the app then added again, none of these worked. Only in the first push seems to work but any model change after that is not considered. Every time I run on heroku bash makemigrations command works like I deleted the migrate folder but when I run migrate I get "No migrations to apply.". -
django annotate count return none or null instead of 0
Is it possible that when you annotate a count queryset in django, we can condition it to return a value of none/null instead of 0? Or is there another way to do it? -
How to check if the model is empty for the current logged user?
I'm trying to check if the model is empty or not to display a message in the blog, for example, if you have no posts yet, I want a message to appear that says "No posts yet", but I don't know how to tell django when the user is logged in and the model is empty, here's the code. class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') class MyPostsView(ListView): model = Post template_name = 'app1/my_posts.html' def post_list(request): var = False exists = Post.body.filter(user=request.user).exists() if exists: var = True else: var = False context = {'var':var} return render(request, 'app1/my_posts.html', context) -
CommandError: An error occurred during rendering "export" is not recognized
I'm trying to connect django with node.js following the installation steps from this repository Everything goes well until I execute the command: $ python manage.py compress I get the following error: CommandError: An error occurred during rendering C:\Users\Vicente\Desktop\prueba\testeando\templates\index.html: "export" is not recognized as an internal or external command, operable program or batch file. Compressing... (myvenv) If I try: python manage.py runserver I got the following localhost error: OfflineGenerationError at / You have offline compression enabled but key "b77....." is missing from offline manifest. You may need to run "python manage.py compress". Here is the original content: <link rel="stylesheet" type="text/css" href="/static/main.css"> -
IN Javascript, I want to maintain my scroll location after refreshing the page
In Javascript , Is there any method to maintain current's scroll location after refreshing the page? It usually show the top of the page after refreshing.. I don't want it.. -
Deploying to AWS failed, requirement.txt returned non-zero exit status 1
I'm very new to AWS and I didn't do the deployment myself. Can anyone give me an idea on what's happening here and what could be wrong? This is a Django project and it's running locally just fine. I'd really appreciate any insight on where to start looking for a solution or what to keep an eye for. enter image description here