Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reason for filter(admin_approved=True,valid_from__lte=now, valid_to__gte=now) not working immediately?
I have a project where there are posts that I want to be displayed for a certain period of time valid_from and valid_to so the issue here is that I have added the correct filters and choosen the time but the posts keep displaying although the time valid_to has passed. I was in doubt until I added a countdown which became negative and exceeded the time valid_to value. I am trying to understand the reason behind this issue and how to fix it? here is the models: class Post(models.Model): valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) Here is the veiws: class PostListView(ListView): model = Post template_name = "post.html" context_object_name = 'posts' now = timezone.now() queryset = Post.objects.filter(valid_from__lte=now, valid_to__gte=now) -
Why doesn't a django sqlite3 database work the same on one machine vs the other?
I'm working on learning Django, but I've run into to a problem with my database not transferring correctly (or it's transferring correctly and I'm missing something, which is what I think is happening). I have a Django model Link in models.py class Link(models.Model): title = models.CharField(max_length=100) alt = models.CharField(max_length=100) dest = models.CharField(max_length=100) image = models.FilePathField(path='static/misc/link_in_bio/img/') def __str__(self): title = self.title + ' Link' return self.title class Meta: ordering = ('title', ) Then I made instances of this model and confirmed they are entered into the database correctly. They are then referenced in a page's html like so: {% for link in links %} <div id="space"> <div class="w3-container"> <div class="w3-panel" style="padding: 0.06em"> <button class="block" type="button" title="{{link.title}}" onclick="window.open('{{link.dest}}')"> <img src="../{{link.image}}" alt="{{link.alt}}" style="max-height: 7em"> </button> </div> </div> </div> {% endfor %} On my development machine everything works exactly as expected and shows this: Then, when I deploy it on Heroku, everything builds correctly, python manage.py makemigrations and python manage.py migrate run correctly, but when I view the page it simply shows this: I also can't login to the admin page with the superuser I already created on the first machine, and I know this is related but I'm not sure how to approach … -
Is it possible to save a react Js rendered page to html and / or pdf server side?
This is more of a general question, hence I'm not including any code. I've looked at quite a few options for both pdf and html, but haven't figured out a good solution. I'm trying to take the output of what would be rendered by reactJs in a browser and save it to the hosting server instead of (or as well as) displaying it in the browser. Specifically I'm generating a report using a pretty standard React functions, styled with css, and want to save that report upon rendering to the server. The API which I also control is Django based. I've looked at react-pdf/renderer, react-pdf, pdfkit on the Django side (w/wkhtmltopdf), reactdomserver to generate static html files, but can't quite piece together a solution. Would love some feedback if anyone's done something like this before. -
Django postgres SplitArrayField throws error when submitting form
I'm new to django and finding myself a bit stuck on some stuff. I'm trying to implement a page which provides a table like this: +--------+-+-+-+ +--+--+ |Employee|1|2|3| |30|31| +--------+-+-+-+ +--+--+----------+ |Name1 |0|0|8|....| 8| 8|SAVEBUTTON| +--------+-+-+-+ +--+--+----------+ with each cell as an input field. Feel free to suggest a better implementation too, I'm a django (and in general) newbie and learning as I'm using it. This is the error I get when trying to save data from my view: File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 443, in changed_data initial_value = field.to_python(hidden_widget.value_from_datadict( File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 195, in to_python return [self.base_field.to_python(item) for item in value] File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 195, in <listcomp> return [self.base_field.to_python(item) for item in value] TypeError: to_python() missing 1 required positional argument: 'value' A different but similar error on the django admin page: File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 374, in full_clean self._clean_fields() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 392, in _clean_fields value = field.clean(value) File "/usr/local/lib/python3.8/site-packages/django/contrib/postgres/forms/array.py", line 206, in clean cleaned_data.append(self.base_field.clean(item)) TypeError: clean() missing 1 required positional argument: 'value' Relevant models.py parts: class DayField(forms.IntegerField): widget=forms.NumberInput(attrs={'max': 24, 'min':0, 'size':2, 'maxlength':2, 'style':'width: 40px; -webkit-appearance: none; -moz-appearance: textfield;', 'oninput':"this.value=this.value.replace(/[^0-9]/g,''); if (this.value.length > this.maxLength) … -
Created a web service using Flask. But getting the output in HTML tags
Result image My aim is to display 'Hello inputname' web.py from flask import Flask,jsonify import requests app = Flask(__name__) @app.route('/<name>',methods=['GET']) def index(name): return jsonify({'out' : "Hello "+str(name)}) if __name__ == '__main__': app.run(debug=True) -
Django + Vuejs Not Able to Get Csrftoken from response header
I have an issue regarding setting up Django and Vuejs in order to make them work together. My issue is regarding csrftoken and how this it is passed between Django and Vuejs. Therefore, my setup is as follow: Django is running on http://localhost:8000 Vuejs is running on http://localhost8080 I am using django rest framework and SessionAuthentication. settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "8g+_gwm=s^kw69y3q55_p&n(_y^^fa!8a^(f7c)#d&md2617o9" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Cors setup # CORS_ORIGIN_ALLOW_ALL = False # For CSRF CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", ] CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", ] # For Cookie CORS_ORIGIN_WHITELIST = ("http://localhost:8080", "http://127.0.0.1:8080") CORS_ALLOW_CREDENTIALS = True # CSRF_USE_SESSIONS = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SAMESITE = "None" CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_HTTPONLY = False # Application … -
Django - get model in navbar
I have a class in models: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) which also has a unique id in database. I want to somehow access the "Customer" from template. I know that first i have to get the object in "views.py" and the access it by {{ }} tag. But is there a different way? My point is that i want to access the Customer and then the related order etc. in navbar which is "included" in every template on the site - so i can't make a view for it. Or maybe I'm understanding it wrong. If so - please correct me. I would like to access similarly to {{ request.user.id }}. -
Django REST Framework multi token per user
I want to use Django REST Framework in my project, As you know by default DRF allow us to have just one token per a user but I have to allow users to login from some different devices and give them independent token for any device. Question: how I can use multi token per a user in my project and manage them in admin panel? -
"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