Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Unknown column 'old_model.new_field' in 'field list'" AWS Elastic Beanstalk Django RDS
Background I created a website using Django and have it deployed on AWS EBS with a MySQL Amazon RDS database. Recently I added a new field to one of the existing models in my models.py file. Everything worked fine on my local server, but when I deployed the new update to EBS I get the following error when I visit any page: OperationalError at / (1054, "Unknown column 'old_model.new_field' in 'field list'") Question What did I do wrong to get the error above and what can I do to fix it? db-migrate.config: container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: app.settings -
why i don't see all parts in html using django
I wrote the following code: {% extends "base.html" %} {% block content %} {% if all_site %} <ul> <h3>Here all my site:</h3> {% for site in all_site %} <li><a href="/site/{{ site.id }}/"> {{ site.name }}</a></li> {% endfor %} </ul> {% else %} <h3> You don't have any Site.</h3> {% endif %} {% endblock content %} when, I run. I not see "Here all my site", but I only see the one contained in the for. -
Use the url as a variable in my jinja2 template?
Is a way to use the slug in my template? I have in my urls: path("cats/check/<int:pk>/lista", ObjetoListView.as_view(), name='posesiones_consulta'), How can I access int:pk as a variable? I want to evaluate this: {% if cat.mom.id == pk %} -
django centos 8 AH01276: Cannot serve directory on plesk
i have trying to deploy django on plesk using this tutorial https://www.plesk.com/blog/guides/django-hosting-latest-plesk-onyx/ I have installed all the steps while checking the logs i am receiving following error. AH01276: Cannot serve directory /var/www/vhosts/mrcric.com/httpdocs/djangoProject/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive Apache error these are the server hosting settings which i have made on plesk -
How to handle data from two forms in one view?
So I have two forms.ModelForm for my two models First: class TranslatorChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(TranslatorChoice, self).__init__(*args, **kwargs) self.fields['owner'].queryset = Translator.objects.all().filter(owner_id = self.user_id) owner = forms.ModelChoiceField(queryset = None) class Meta: model = Translator fields = ('owner',) Second: class ProfileChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(ProfileChoice, self).__init__(*args, **kwargs) self.fields['login'].queryset = Profile.objects.all().filter(created_by_id = self.user_id) login = forms.ModelChoiceField(queryset= None, label='Profile') class Meta: model = Profile fields = ('login',) I've tried writing a view for them but it doesn't work, seems like it just won't save because whenever I hit submit button it just refreshes the page and cleans the fields without redirecting me to needed URL. The model instances in my DB aren't updated either. Here's the view: def link_profile(request): context = { 'form': ProfileChoice(user_id=request.user.id), 'form2': TranslatorChoice(user_id=request.user.id) } if request.method == 'POST': form = ProfileChoice(request.POST) form2 = TranslatorChoice(request.POST) if form.is_valid(): login = form.cleaned_data.get('login') translator = form.cleaned_data.get('owner') link = Profile.objects.get(login=login) link.owner = login link.save(['owner']) form.save() form2.save() return redirect('dashboard') return render(request, 'registration/link.html', context) I know also something is wrong is because I am using to many save functions. I just don't have any experience in creating views like that... -
ImportError: DLL load failed while importing _psycopg: The specified module could not be found
I have a django project that I am trying to connect with a postgres database. However when I try to run the command python manage.py makemigrations I get the following error: (card_crate_venv) G:\Shared drives\Card Crate\Software Development\card_crate_admin\website>python manage.py makemigrations Traceback (most recent call last): File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\website\manage.py", line 22, in <module> main() File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\website\manage.py", line 18, in main execute_from_command_line(sys.argv) File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Ross Waston\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "G:\Shared drives\Card Crate\Software Development\card_crate_admin\card_crate_venv\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. settings.py: … -
Passing validated_data with source attribute on field back into nested serializer
Scenario: I have a serializer containing a nested serializer and I want to use the create function on that nested serializer in order to keep my business logic in one place. Problem: Because the nested serializer uses the source attribute for a field, the validated_data on the parent serializer contains the model field as opposed to the serializer field name. When I go to pass this back in, it fails validation Example: class FooSerializer(): foo_amount = serializers.IntegerField(source='foo_quantity') class Meta: class = Foo fields = ('foo_amount') def create(self, validated_data): # Some business logic class BarSerializer(): foo = FooSerializer() class Meta: class = Bar fields = ('foo') def create(self, validated_data): foo_serializer = FooSerializer(validated_data.pop('foo')) # Always going to fail because validated_data has 'foo_quantity' as a key if foo_serializer.is_valid(): foo = foo_serializer.save() -
Django Models. Undefined variable
Does anyone know why the itembided__currentbid is identify as an undefined variable? My models are: class AuctionListing(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") title = models.CharField(max_length=64) description = models.CharField(max_length=1000) startingbid = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField(max_length=64, blank=True) imgurl = models.URLField(max_length=300, blank=True) status = models.BooleanField(default=True) class Bid(models.Model): usernameb = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userb") auctionitem = models.ForeignKey("AuctionListing", on_delete=models.CASCADE, related_name="itembided") currentbid = models.DecimalField(max_digits=6, decimal_places=2, default=0) And the code from views.py where the issue is: ... from .models import User, AuctionListing, Bid def index(request): q = AuctionListing.objects.filter(status=True).annotate(max_bid=Coalesce(V(0),Max(itembided__currentbid))) return render(request, "auctions/index.html", { "q":q, }) Any suggestions? My original Bid model had no quotes for the AuctionListing parameter, It looked like this: auctionitem = models.ForeignKey(AuctionListing, on_delete=models.CASCADE, related_name="itembided") However, after reading a disscution from StackOverflow Undefined variable in django I tried adding the quotes to the AuctionListing parameter... sadly, it didn't work. -
How can i set custom pagination in Django Rest Framework?
I'm trying to set a custom pagination for my API endpoint, where if there is a filter in the URL, Django must return a specific amount of records, and another amount of records if there isn't any filter. I have the following code: valid_filters = {'Name', 'Date'} def _has_valid_filters(iterable): return not valid_filters.isdisjoint(iterable) class MyPagination(LimitOffsetPagination): def get_page_size(self, request): if _has_valid_filters(request.query_params.items()): return 15 else: return 30 class MyView(viewsets.ModelViewSet): pagination_class = MyPagination http_method_names = ['get'] serializer_class = My_Serializer def get_queryset(self): valid_filters = { 'Name': 'Name', 'Date': 'Date__gte', } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} queryset = Model.objects.filter(**filters) return queryset The problem with this code is that the pagination is always the same. While MyPagination is called, it looks like get_page_size is never called for some reason. Can anyone help me out on this? -
Problem running a Django program on VS Code
I just started working on a project that runs on Python Django. I cloned the repository from GitHub and am running python 3.9 on my computer. I set up a virtual environment on the VS Code terminal and installed Django (this is my first time using Django). I selected the interpreter for my virtual environment, however when I try to run the code (which should show a local webpage) I get the error ModuleNotFoundError: No module named 'matplotlib'. Then I tried installing maplotlib with pip install matplotlib however that gives me the error ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I know there are already questions about this specific error on here but I can't seem to fix it. Would there have been an easier way to do this or did I do something wrong during my setup? I would appreciate any help! I was also told there should be a .git file when cloning the project, but that isn't there either, does that change anything? -
How can I get csrf_token for my form in JS fi?
How can I get csrf_token for my form in a js file. I found this code in the documentation, but it won't work with jQuery or with a regular JS? // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); -
How to upload an image from a react native app (Expo) to a django server
So I am using the expo image picker to let users upload a picture to a Django server but I have run into an error where the image I upload is always null. The post request goes through but the image is never stored but seems to be sent. From what I have read I need to upload the image as base64 so I have set the picker to take the image in base64, whereas I had been using a uri for the upload but I still get a null image field in the database record. upload url path('feed/', views.ListCreatePost.as_view(), name="post_feed"), const [image, setImage] = useState(null); useEffect(() => { (async () => { if (Platform.OS !== 'web') { const { status } = await ImagePicker.requestCameraRollPermissionsAsync(); if (status !== 'granted') { alert('Sorry, we need camera roll permissions in order to make a post!'); } } })(); }, []); let postForm = new FormData(); const makePost = async () => { try{ console.log('salvo'); console.log(image); let photo = { uri: image.uri, type: 'image/*', }; console.log('photo'); console.log(photo); postForm.append('user_id', user); postForm.append('content', content); postForm.append("image", photo); let response = await fetch('https://mdrn02.herokuapp.com/api/v1/feed/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data' }, body: postForm }); console.log('response'); console.log(response); let … -
How to execute code from database in Django
I created a blog with Django and my model post is like this: class Post(models.Model): title = models.CharField(max_length=255, unique=True, db_index=True) content = RichTextField() # ... In my template, I display the content of posts like this: {{ post.content|safe }} What I want is to execute code that is in the content of the post. Let say I want to add a link to the "about me" page, so logically I would add this in the content of the post: # some text here <a href="{% url 'about' %}">about me</a> # another text here This doesn't work. if I hover the URL I can see the URL 127.0.0.1:8000/post/21/{% url 'about' %}. How can I do that. -
get_or_create() fails with model with uniqueness constraint
In Django I have a model Subreddits with a many-to-many-relationship to another model User, with a uniqueness constraint on the subreddit_name column of Subreddits. If a Subreddit with the exact name already exists I want to grab it and add the currently logged-in user to the relationship list. If no Subreddit exists, I want to create it and also add the user. That is the relevant view code: def create(request): user = request.user form = SubredditForm(request.POST) if form.is_valid(): subreddit_name = form.cleaned_data["subreddit_name"] s, _ = Subreddit.objects.get_or_create(subreddit_name=subreddit_name) s.user.add(user) And this is the model: class Subreddit(models.Model): subreddit_name = models.CharField(max_length=200, unique=True) user = models.ManyToManyField(settings.AUTH_USER_MODEL) If I test it (in a unit test) the Subreddit won't be added to the list of Subreddits of the user and if I test it in person, I get an error "Subreddit with this Subreddit name already exists." Any idea why this happens? -
Django fixtures.json with ManyToMany Relationships
Let's say you have to create a database where you store all the books from a library and all the authors from the world. You have every book in file named books.json and every author in a file named authors.json Then you want to create a link between those to tables where a book can have one or more authors. What I did is I created needed models, then I loaded authors.json and then when I try to load books.json I got the error: django.core.serializers.base.DeserializationError: Problem installing fixture '/workspace/libray/books/fixtures/books.json': class book(models.Model): name =models.CharField(max_length=254, blank=True, null=True, on_delete=SET_NULL) authors = models.ManyToManyField(author) class authors(models.Model): name = models.Charfield(max_length=100, blank=True, null=True, on_delete=SET_NULL) books.json [ { "pk":1, "model":books.book, "fields":{ "name":"Book1", "authors":[1,2,3] } }, ... ] authors.json [ { "pk":1, "model":books.author, "fields":{ "name":"Author1", } }, ... ] How to load properly some fixtures when there are M2M relationships between models. -
DRF variety Create, Update methods
I am new to django. As I am learning, I found two ways to write (create, update ...) functions. One in the view and the other in the serializer class. When do I do the first method and when is the other ? Question2: How do I handle the post data which is for example json object in both the url and in the post function ? I read the django tutorial and for beginners I found it a little bit ambiguous. Thanks for helping .. -
Ajax call takes too much more time to be resolved
The waiting (TTFB) takes many seconds as we can see below enter image description here and actually, I doubt in an external directory I have added to my django's view because when I don't use it, everything goes well, and here my project structure. . ├── app | |_ init | |_ oop(.py) | ├── conjug_app │ |_ init | |_ admin | |_ apps | |_ models | |tests | |views │ ├── my_conjugaison │ | init | | asgi | | settings | |_ urls | |wsgi ├── templates │ | "some files here" │ ├── manage(.py) and here is the settings: from pathlib import Path import os, sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EXTERNAL_LIBS_PATH = os.path.join(BASE_DIR, "app") sys.path = ["", EXTERNAL_LIBS_PATH] + sys.path -
Django password_reset with appname
I'm using auth views for for resetting password in django. Since I've declared this views inside my users app and used appname for the URLs I'm getting an error. I know that I should change the URL inside the django pre-built templates but I don't know the best way of overriding this kind of stuff. this is URL.py of my user application: app_name = 'users' urlpatterns = [ path('register/', views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='users/password_reset_complete.html' ), name='password_reset_complete'),] this is the error: NoReverseMatch at /users/password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. this is the line it's referring: {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} -
TypeError at /project_members/ must be str, not Post
i recived errors in this line project_id=form.cleaned_data['project_id'] response =requests.post('http://172.16.0.111/api/v4/projects/'+project_id+'/members', headers=headers, data=data) please how to convert this in type string -
pass value from template to view in Django
I am new to django.I need to send id of clicked button to my function pdf_view that pdf view use id of that button for filtering and returning some data. Here is my template : (regions[i].id is a number between 1 to 10, it is the thing that I need to send to views.py) <h5 class="card-title">regions[i].id </h5> <a href="{% url 'app:pdf-data' %}"> export pdf </a> part of views.py: def pdf_view(request): reg = **********************here i need to get region from template*********************** data = Model.objects.filter(region=reg) context = {'data':data } If I put region equal to a number , every thing goes well.I just need to get region from template.Please help me with this problem. -
In Django, how to rename user model?
I trying to rename my user model CustomUser => User Here what I've done: Rename Python class and all references makemigrations Did you rename the accounts.CustomUser model to User? [y/N] y Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 168, in handle migration_name=self.migration_name, File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 186, in _detect_changes self.generate_altered_fields() File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 959, in generate_altered_fields dependencies.extend(self._get_dependencies_for_foreign_key(new_field)) File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 1086, in _get_dependencies_for_foreign_key dep_app_label = field.remote_field.model._meta.app_label AttributeError: 'SettingsReference' object has no attribute '_meta' So I'm stuck with this exception, any help appreciated :) -
UI for Django based chatbot
I am currently working on a django based chatbot but I can't get to integrate it with any UI available on net or articles . It would be of much help if I can get guidance to make a simple UI based on javascript to integrate with my bot. -
What is the root directory of a site deployed on heroku?
The Root page of the site is: amaze2020.herokuapp.com I need to save a verification .txt file into the root directory of amaze2020.herokuapp.com. -
Django .values() on field name with '%' sign: "ValueError: unsupported format character '_' (0x5f) at index 83"
I have a model with a field called %_Coverage, and when I try to pass this to .values on a QuerySet, Django throws an error saying "ValueError: unsupported format character '_' (0x5f)". How can I escape the percent sign that it runs correctly? My_Message = type('My_Message', (models.Model,), { '__module__': __name__, 'id': models.AutoField(primary_key=True), 'name': 'My_Message', '%_Coverage': models.IntegerField }) class Message: My_Message = models.ForeignKey(My_Message, on_delete=models.CASCADE, null=True, blank=True) messages = Message.objects.filter(message_name='My_Message').values('My_Message__%_Coverage') print(messages) # throws an error # This works: messages = Message.objects.filter(message_name='My_Message') print(messages) # prints: <QuerySet []> Using f'My_Message__%_Coverage' throws the same error, and 'My_Message__%%_Coverage' complains that the field is not found. Here is the traceback. Traceback (most recent call last): File "python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "python3.8/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "python3.8/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "views/message_viewer.py", line 220, in my_view print(messages) File "python3.8/site-packages/django/db/models/query.py", line 263, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) … -
How can I get csrftoken for the form?
How can I get csrf_token for a form in JS without using jQuery? I found this code in the documentation, but it uses jQuery. // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken');