Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide column in model django?
My models: title = models.CharField(max_length = 100) text = models.TextField() text2 = models.TextField() Is it possible to hide columns (text2) in the admin dashboard, e.g. with a checkbox (column no active( so that they are not used in the forms? I'd like to configure the visibility of the columns in forms by admin interface. -
Allow users to fill out a Django form on their own personal website?
I am wondering if anyone has dealt with allowing Users to fill out a form on their own personal website, which is connected to the Django applications database? The general idea behind this, is allowing say a User (Party Planner in the Django app) to not have to come to the "Django Application" to input an event, rather they go to their own personal website, and input form information there which is POSTed to the Django applications database? It's an idea I have been throwing around, and just looking for some guidance in the right direction. Thank you in advance! -
authorization in requests.Session() not work with Django. I get AnonymousUser
I'm trying to create an authorized session using requests.Session() and work with files from the django model. import request session = request.Session() session.auth = ('username', 'password') auth = session.get('http://127.0.0.1:8000/login/') file = session.get('http://127.0.0.1:8000/file/123') #here response is (403 forbidden) In views.py i have check: user.is_authenticated; I always get false (get AnonymousUsers). How can I log in via requests with session retention to access files? Can anyone help? -
Django display content of Google Storage PDF within Heroku Site
I have an issue where the service account used to allow the Django application has the permissions to edit and delete the Google storage bucket. However, I use an iframe to load a preview for a PDF, this preview indicates the following: '''AccessDeniedAccess denied.Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.''' If I use an tag and load the same file from the Google bucket it works completely fine. However, using the messes it up due to insufficient permissions. Keep in mind that the files can not be publicly available due to privacy. Moreover, I would like to use the tag due to the variety of content being displayed. As it sometimes might be a PDF or Video. ScreenshotThe preview of the file unavailable -
How to get a reference to the already loaded leaflet map in Djano's admin page using Django-leaflet
I'm trying to add markers to the leaflet map loaded in Django's admin pages with data retrieved from an ajax call. However I cannot get a reference to the map that I can use in my template used to override the Django admin template. If I load the page, open the console, and run the code below it works. The marker is added to the map. Console: var map = window['leafletmapid_location-map']; L.marker([40.3830621, -111.773658]).addTo(map); However if I include the exact same code in my template it doesn't work because it is not getting the reference to the map, and I can't figure out why. Template: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} {% block content %}{{ block.super }} <script> var map = window['leafletmapid_location-map']; L.marker([40.3830621, -111.773658]).addTo(map); </script> {% endblock %} If I replace the entire script tag with the following I get undefined which I believe is the cause of the problem. Template: <script> console.log(window['leafletmapid_location-map']) </script> However if in change the template to the following I get the window object, and it shows it has the leafletmapid_location-map object available. Template: <script> console.log(window) </script> -
How can I deploy a django to app to heroku?
I am trying to deploy my django app to heroku. I have followed this tutorial word for word. After I have successfully deployed the application and open the app on the browser it says to me that there is an application error. It tells me to look at my logs. Here is my logs: 2022-01-17T21:45:19.636590+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=testshamir.herokuapp.com request_id=c045b7f7-0364-41c7-be06-b644b3131dff fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:20.139456+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=504625b3-1fb2-4016-96b2-32d3952cce93 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:24.591640+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/polld" host=testshamir.herokuapp.com request_id=46c3e46b-2abc-406d-a420-fcd67d112493 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:24.887285+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=95afd40f-1d54-4638-90c6-2cfa935d3fd7 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:28.377476+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/polls" host=testshamir.herokuapp.com request_id=880e0585-b93a-4b09-a878-80995cf007df fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:28.658839+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=35edc875-62ee-4b79-840c-98fba1aedd60 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:48:05.411725+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=testshamir.herokuapp.com request_id=5bb89c4b-0aae-4f28-9cf9-a14e3e7ff9ec fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:48:05.775751+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=333334a5-0824-4aff-b42b-1ae61403390a fwd="130.70.15.5" … -
Python/Django routing messed up when clicking a button
I am working through a basic django tutorial and I have become stuck. When the favorites button is clicked I am trying to redirect the user to reviews/favorite, which will then redirect to reviews/review_id, which is where they started. Instead, whenever I click the favorite button on the page it redirects me to reviews/reviews/review_id which fails. Interestingly enough if I remove the /reviews/ part from the form action in single-review.html then it routes me to /favorite, which fails because it doesnt exist, but when I put it back to reviews/favorite I go back to reviews/reviews/favorite as the routing. Anyone know what I am doing wrong? Views.py from django.http.response import HttpResponse from django.shortcuts import render from django.http import HttpResponseRedirect from django import forms from django.views import View from django.views.generic.base import TemplateView from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import FormView, CreateView from .forms import ReviewForm from .models import Review # Create your views here. # uses createview to handle all the data processing and then save data to database. Removes need for class ReviewForm in forms.py unless you want to customize class ReviewView(CreateView): model = Review form_class = ReviewForm template_name = "reviews/review.html" success_url = "/thank-you" class ThankYouView(TemplateView): template_name … -
Django model Foreign key serialization
In a django model, I want to custom the natural foreign key for the model to be serialized as it would be directly with the serializers.serialize function (and not just an array or tuple). Then, what prevents me doing this? class Player(models.Model): def natural_key(self): player = serializers.serialize('json',[self],use_natural_foreign_keys=True) return json.loads(player)[0] Is there a better way to return a json model for a foreign key of this form: { model: "play.player", pk: "72026f4d-3c74-4edd-9f88-5ab8330218b1", fields: {…} } -
Django filter - is DateTimeField filled
to my model I added a simply DateTimeField: expired = models.DateTimeField(default=None) . The value of the field can be either None or a Datetime. I'd like to filter for objects where the expired is filled with any datum, however I'm struggling to find the right filter. I think I tried all the combinations of filter / exclude and expired__isnull=True / expired=None, but I never get back the exact number. What's the right way to filter if the field has a DateTime in it, or not? Django: 1.11.16 Thanks. -
Django Middleware does not modify request in tests
I am trying to create test class for my custom middleware. The project is using Django REST framework. Middleware class works fine when server is running, but when I run test it behaves not quite as I would expect it to do. Maybe I misunderstood something, as I am quite new to testing in Django. my_middleware.py: class FX: a = False b = None c = '' def __init__(self) -> None: pass def __str__(self): return 'fx ok' class MyMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.fx = FX() response = self.get_response(request) print('done') return response views.py: class TestView(APIView): def get(self, request, format=None): print('View ok') print('FX: ', request.fx) return Response({'result':'ok'}) tests.py: class TestMyMiddleware(APITestCase): @classmethod def setUpTestData(cls): pass def setUp(self): pass def test_fx(self): response = self.client.get(reverse('TestView'), content_type="application/json") request = response.request self.assertTrue(hasattr(request, 'fx')) The code above actually runs the middleware. It prints "done" form the middleware call, then prints 'View ok' and also prints FX instance. However request.fx is not available in the test_fx method, thus giving assertion failure: self.assertTrue(hasattr(request, 'fx')) AssertionError: False is not true Any idea what I might be doing wrong? -
Django-import-export update_or_create with UniqueConstraint
I have this Profile model together with a constraint similar to a unique_together: class Profile(models.Model): #Personal Information firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=200) investor_type = models.CharField(max_length=200, choices=investor_type_choices) class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'investor_type'], name='email and investor_type') ] I want to implement a function update_or_create on the Profile which uses the email and investor_type as the argument for searching for the object. I tried adding this to my ProfileResource: def before_import_row(self, row, row_number=None, **kwargs): try: self.email = row["email"] except Exception as e: self.email = None try: self.investor_type = row["investor_type"] except Exception as e: self.investor_type = None def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Profile entries prior to importing rows. """ try: # print(self.isEmailValid(self.email), file=sys.stderr) if self.email and self.investor_type: profile, created = Profile.objects.update_or_create( email=self.email, investor_type=self.investor_type, defaults={ 'firstname': 'helloo', 'lastname': 'wooorld', }) except Exception as e: print(e, file=sys.stderr) but adding a non-existing Profile object: through django-import-export: is already giving out an error, Profile with this Email and Investor type already exists despite it not existing in the first place. -
Why i got this error on Django, When i run it on browser. I'm using the latest Django version and python 3.10.2. Please any fix for begginer like me
My name is Abdi from Ethiopia. My english is not very well, I was stuck on this error. [1]: https://i.stack.imgur.com/SVEdE.png [2]: https://i.stack.imgur.com/Q6RGF.png [3]: https://i.stack.imgur.com/sWPv5.png [4]: https://i.stack.imgur.com/9qJZM.png I am begginer for django.Why i got this error on Django,When i run it on browser. I'm using the latest Django version and python 3.10.2. Please! any fix for begginer like me. -
How to update Wagtail static files, they stopped working when I used STATIC_DIRS
I'm trying to update Wagtail from version 2.8 to the latest 2.15. Also, I had to update from Django 3.0 to 3.2. However, I noticed that when I use STATICFILES_DIRS, the style of the Wagtail admin (2.15) gets distorted as if it's using the files from the old version (2.8). PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) ... STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [os.path.join(PROJECT_DIR, 'static'),] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Conversely, when I delete the STATICFILES_DIRS, the style on the Wagtail admin gets fixed, but the all the style on my project its gone. I already checked and it's not the cache. I tried that several times, different browsers, etc. -
Django application global variables in database best praxis
I am a new in django. I storage global application variables inside settings environment folder. But now i need store variables inside Database because i want changes them from django admin. My way to do this: Create model class in django core, where define two variable app_name - list of application and data-JSON. But i think this is not best praxis. Since it may be difficult to use the GIT -
Split unit test units into a number of files in Django
I have a project built using Django and I use unittest library to do some tests, I write all the tests in tests.py file and then I run these tests with the command: ./manage.py test app Everything works without a problem, but the tests.py file gets bigger and more complex over time, is there a simple way to split this file into a number of files so that each file contains only one type of tests? -
django rest how to post comments in a post blog
I would like to know how to delete comments in a board using an url like this: DELETE /api/boards/{board_id}/comments/{comment_id} Current I can list all comments and post a comment using this: GET /api/boards/{board_id}/comments # will get all comments POST /api/boards/{board_id}/comments # will create a comment. I dont know how to get a single comment and dont know how to delete a comment using the extra action below this is my current view: class BoardViewSet(ModelViewSet): queryset = Board.objects.exclude(deleted=True) serializer_class = BoardSerializerList permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] def destroy(self, request: Request, *args, **kwargs) -> Response: board = self.get_object() if not board.deleted: board.deleted = True board.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_400_BAD_REQUEST) def get_serializer_class(self): if self.action == 'retrieve': return BoardSerializerRetrieve return super().get_serializer_class() @action(detail=True, methods=['get', 'post', 'delete'], serializer_class=CommentSerializer) def comments(self, request, pk=None): if self.request.method == 'GET': board = self.get_object() comments = board.comment_set.all() serializer = CommentSerializer(comments, many=True) return Response(serializer.data) if self.request.method == 'POST': board = self.get_object() serializer = CommentSerializer(data=request.data) if serializer.is_valid(): user = serializer.data['user'] text = serializer.data['text'] Comment.objects.create(board=board, user=user, text=text) return Response(status=status.HTTP_201_CREATED) these are my models: class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) description = models.TextField(max_length=1000) share_with_company = models.BooleanField() share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True) last_update = models.DateTimeField(auto_now=True) owner = models.ForeignKey('auth.User', related_name='boards', on_delete=models.CASCADE) deleted … -
how to ship a Django app as a docker image?
I would like to package and ship a Django web app as a Docker image. When I do a docker-compose up, I see a tree hierarchy in Docker desktop containers and works as expected when I navigate to http://localhost:85 django-dashboard-volt |___appseed_app |___nginx If I save and load the image, I see the following in the Docker desktop containers and the web application does not work: django-dashboard-volt_appseed-app nginx Here's how I save and load the images: docker save django-dashboard-volt_appseed-app:latest nginx:latest | gzip > django.tar.gz docker load --input django.tar.gz Here's the Dockerfile: FROM python:3.9 COPY . . ADD test . ADD data . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /test ENV APP_USER=xxxx ENV APP_HOME=/home/$APP_USER # install python dependencies #RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --upgrade pip RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --no-cache-dir -r requirements.txt RUN tar xvzf gurobi9.5.0_linux64.tar.gz ENV GUROBI_HOME /gurobi950/linux64 RUN cd /gurobi950/linux64 && python setup.py install RUN rm gurobi9.5.0_linux64.tar.gz RUN echo "TOKENSERVER=xxxx" > /gurobi.lic RUN groupadd -r $APP_USER && \ useradd -r -g $APP_USER -d $APP_HOME -s /sbin/nologin -c "Docker image user" $APP_USER ENV TZ 'America/Los_Angeles' RUN echo $TZ > /etc/timezone && apt-get update && \ apt-get … -
cant get profile images to display with django
I am working through a basic django upload image tutorial and I have become stuck. I am trying to let a user upload a file, store it in in a folder, and then save the address to that image in the db. This part all seems to be working. Then I try and have a simple page to display all images to make sure its working and the img tag in the HTML keeps having a src of "unknown". I am unsure of what exactly the problem is because there are no errors thrown anywhere. Views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.views.generic.edit import CreateView from django.views.generic import ListView from .models import UserProfile # Create your views here. class CreateProfileView(CreateView): template_name = "profiles/create_profile.html" model = UserProfile fields = "__all__" success_url = "/profiles" class ProfilesView(ListView): model = UserProfile template_name = "profiles/user-profiles.html" context_object_name = "profiles" Models.py from django.db import models # Create your models here. class UserProfile(models.Model): image = models.ImageField(upload_to="image") User-Profiles.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profiles</title> </head> <body> <ul> {% for profile in profiles %} <li> <img src="{{ profile.url }}"> </li> {% endfor %} … -
Does anyone know of a plugin to do dynamic calculations in the django formset?
Does anyone know if there is a jquery plug-in that can do calculations for a django formset (it is a dynamic form, it changes the id of each field per row each time the add button is clicked) -
How to copy the data in old col to new col with only unique values?
I'm trying to create a new unique field called last_name_unique. I need to copy the data from last_name to last_name_unique. The new field can be nullable so we can add null for the repeated values. For example, if there are two last names with value "Junior", under the last_name_unique there will be one value "Junior" and then null for the other "Junior" value. from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) Any idea how to achieve this would be appreciated. -
Django - How to set ordering on ManyToMany field queryset
I have following models: class Hashtag(models.Model): ... created = models.DateTimeField(auto_now_add=True) ... class Tweet(models.Model): ... hashtags = models.ManyToManyField( to='Hashtag', through='TweetHashtag', through_fields=('tweet', 'hashtag'), ) ... class TweetHashtag(models.Model): comment = models.ForeignKey( to='Tweet', on_delete=models.CASCADE, ) hashtag = models.ForeignKey( to='Hashtag', on_delete=models.CASCADE, related_name="tweets" ) created = models.DateTimeField(auto_now_add=True) My problem is when I get a Tweet, I want to get hashtags order by created. tweet = Tweet.objects.get(id=1) hashtags = list(tweet.hashtags.all()) When I check hashtags, I see the hashtags are in incorrect ordering. I want to get tweet.hashtags order by created (created of TweetHashtag) Is there anyway? I have one idea but I don't know how to do that. The idea is to override relation manager of hashtags in Tweet model. Is there any way? -
How to add markers to leaflet map in an ajax call? leaflet Cannot read properties of undefined (reading 'addLayer') Layer.js:52
I am trying to add markers to my leaflet map in an ajax call, but I am getting an error. I'm able to add markers to the map in the console, but don't know why I can't in the ajax call. Any help would be appreciated. Ajax Call // get reference to map var map = window['leafletmapid_location-map']; $('#id_sub_areas').change(function (event) { $.ajax({ type: 'GET', url: 'my_url', success: function (response) { L.marker([40.383061, -111.773658]).addTo(map) }; }); }); When I trigger the ajax call I get the error message- leaflet Cannot read properties of undefined (reading 'addLayer') Layer.js:52 However if I load the page I can add a marker to the map with the following code in the console. Console Code var map = window['leafletmapid_location-map']; L.marker([40.383061, -111.773658]).addTo(map); -
Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files
I am running a Django website and it's about to go into production. I am now at the point where I need to set DEBUG = False in my settings.py file. I am getting the typical 500 errors because I have static files that are being hosted locally. I am working on getting Whitenoise to work to host my static files so I can move on with DEBUG = False. I have followed a lot of documentation and a lot of tutorials and think all of my configurations are all set but I am still getting the same error. When DEBUG = False I am still getting 500 errors on my production pages that have static files. Also when I inspect any static files on the page when DEBUG = True the URL has not changed at all. I am posting all of my configuration below in hopes that there is a simple mistake I made that I have been continuously skipped over but Whitenoise doesn't seem to be working and there seems to be no different from the way it was before now as Whitenoise is "implemented". I have run python manage.py collect static I have run pip install … -
not getting right URL for entering specific project
I have my site set up, that every user can join many teams, but each team can have many projects, and each project can have many tasks, and I am listing all projects in a team, but i want to use the href to get to the specific project, which is displayed as a task. but i cannot direct it correctly. Here is my models.py class Note(models.Model): title = models.CharField(max_length=55) content = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) check_completed = models.BooleanField(default=False) notes = models.ManyToManyField(Note, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('checklists', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def last_comment(self): return self.notes.latest("date") class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") start_date = models.DateTimeField() due_date = models.DateTimeField() checklist = models.ForeignKey(Checklist, blank=True, null=True, on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def get_url(self): return reverse('tasks', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task_completed(self): return self.task_completed.count() class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, … -
Django how to pass custom error message in class based views
I need to be show custom error message for invalid forms. I don't know how to do it in class based views. here is my class based views: class EditPatient(UpdateView): model = Patient form_class = PatientUpdateFrom template_name = 'hospital/edit-patient.html' def form_valid(self, form): error_message = None if form.is_valid(): name = self.request.POST["patient_name"] email = self.request.POST["phone"] if len(name) > 20: error_message = 'maximum 20 character allowed in name' if len(phone) > 20: error_message = 'maximum 15 character allowed in phone' """ #I tried this but didn't work def get_context_data(self, **kwargs): context = super(EditPatient,self).get_context_data(**kwargs) context['error_message'] = error_message return context """ if not error_message: messages.add_message(self.request, messages.INFO, 'Patient Sucessfully Updated') form.save() return redirect('hospital:edit-patient',self.object.slug)