Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does changing my render request in views.py break my ability to import images in my base.html?
In my views.py, I have a function for my homepage; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile}) #This is the problem line and my HTML runs perfectly; <body> <header> <div class="container"> <img src="{% static 'css/images/uReflect.png' %}" alt="logo" class="logo"> <nav> But when I change my home function in views.py to the code below, my page stops working. I have no idea how an error with 'post.image' would correlate to me accessing my images that are independent of posts, and exist in a separate folder. The weirdest part to me is how the error says "NoReverseMatch at /home" but the error doesn't even occur in home.html, it occurs in base.html. Although, home.html does extend base.html; @login_required(login_url="/login") def home(request): user_object = User.objects.get(username=request.user.username) user_profile = Profile.objects.get(user=user_object) posts = Post.objects.all() return render(request, "main/home.html", {'user_profile': user_profile, 'posts': posts}) # Change made here with posts -
Django: query filter
I have two models that are related: one is a list of participants. The other is a list of times they have checked in or out of an office. The table (Checkin) has one record for every checkin/checkout pair. So, there can be many records for any participant. How can I retrieve only the very last (most recent) record for a participants checkin and then pass the participant and only that most recent Checkin record to my template? From what I can tell there's no ability to do something like a last() in my template, so how would I go about filtering to get just that single record? Thank you. Models: class Participant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) class CheckIn(models.Model): adult = models.ForeignKey( Participant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkin = models.DateTimeField(blank=True, null=True) checkout = models.DateTimeField(blank=True, null=True) View snipit: p_checkins = Participant.objects.all().order_by('created') queryset = p_checkins context_object_name = "the_list" template_name = 'list_of_checkins.html' -
Is it better to use JsonField or multiple model fields for a Django Model?
For example, class TestModel(models.Model): title = models.CharField(max_length = 200) descriptions = models.JsonField() Or class TestModel(models.Model): title = models.CharField(max_length = 200) description_1 = models.TextField() description_2 = models.TextField() description_3 = models.TextField() description_4 = models.TextField() description_5 = models.TextField() Assume that I have a limited (max 5) number of descriptions. Which approach is better and would be considered as good practice? -
Django server: execute a function once a day
I have a django server which uses a another api to use its resources. In order to use the api, i need to pass access token. And I have refresh token which expires after two weeks. What I want to do is to define a function that checks if refresh token expires that day and if so, update tokens. Most importantly, I want to call that function once a day. I can do that with setInterval in javascript, but what is the most efficient and safest way to implement that feature with python ? -
keep getting bad request when I try to upload image to Django using react native camera
I am trying to make a camera app using react native and send the image to backend using Django. here is the code for taking picture and update it on Django. I tried PUT and POST method. const [image, setImage] = useState(null) const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } const takePicture = async() => { // setimage(null); if(camera){ const options = { base64: true, quality: 0.5 } const data = await camera.takePictureAsync(options) setimage(data.uri); const upload = new FormData(); upload.append('name', '') upload.append('image', image); console.log(upload); fetch("http://192.168.0.154:8000/API/getObjectProperties/object/1/" , { method: 'PUT', // headers: { // 'Content-Type': 'application/json' // }, body: upload } ).then( (res) => res.json()).catch( (error) => console.error(error)); } } but I keep getting bad request although it works when using postman. bad request the FormData is it because it cannot read the file from the camera.takePictureAsync() as it is like "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FThesisApp-1fe17b3a-01c2-46c4-953e-6368f5dc1eeb/Camera/d909cdfe-9d40-4788-a212-63780d715321.jpg" instead of just d909cdfe-9d40-4788-a212-63780d715321.jpg? is there any solution … -
Unable to display string from backend to Django Template
Hi I am unable to display some string from my custom view backend to django template. The string from backend is able to send over to the client side browser but still unable to display. The error message that I am trying to display is a lockout message from django-axes. it is a custom view function that returns a HttpResponse(JsonResponse(response_data)) where the response_data is as shown in the image inserted. Below is what I have tried. HTML <div class="login-form clrbg-before"> <p class="text-success" id="login-success" style="display: none;"></p> <form role="agent-login" class="login" id="" action="{% url 'agent-login' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" placeholder="Email address" name="email" class="form-control"> </div> <div class="form-group togglepassword-right"> <input type="password" placeholder="Password" name="password" class="form-control"> <i class="glyphicon glyphicon-eye-open form-control-feedback" id="togglePassword"></i> </div> <p class="text-danger text-center" id="password-error" style="display:none;"> {{ errors }}</p> <div class="form-group"> <button data-request="ajax-submit" data-target="[role='agent-login']" class="btn-1 " type="button"> Login now </button> </div> </form> <div style="text-align: center;"> <a href="#" class="gray-clr" id="agent-forgot"> Forgot Password? </a> </div> </div> views.py def agent_login(request): start = time.time() sop(start) response_data = {'login': "Failed"} redirect_url = '' data = [] error = False errors = {} result = 'FAIL' message = '' response_status = HTTP_400_BAD_REQUEST if request.POST: redirect_url = '' data = [] error = False errors = {} result … -
Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 failed:
i am trying to deploy my django web app on Google Cloud App Engine, but are running to a connection error. This is after I have done all the configuration like main.py, entry point, app.yaml. After doing some digging, they all point to my postgresql database blocking my connections somehow, but i checked and my database is up and running on sql cloud. Here is the screenshot of the error: [the error image][1]: https://i.stack.imgur.com/bDIfY.png Here is my app.yaml file: # [START django_app] runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: django_blog.wsgi.application env_variables: APPENGINE_URL: https://engineblog.wn.r.appspot.com #entrypoint: gunicorn -b :$PORT django_project.wsgi:main inbound_services: - warmup # Only pure Python libraries can be vendored # Python libraries that use C extensions can # only be included if they are part of the App Engine SDK # Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27 # libraries: # … -
Django - User Password Change by coding
I am trying to give permission to change password for logged in user. coded as below.. result comes as password has been changed but password not set. def changepassword(request): if request.method == 'POST': user = authenticate(request, username=request.user,password=request.POST['old']) if user is None: return render(request, 'pmp/changepassword.html', {'error': 'Current Password Enter Mismatch! '}) else: try: if request.POST['password'] == request.POST['confirm']: u = request.user u.set_password('password') return render(request, 'pmp/changepassword.html', {'success':'Password has been changed!'}) else: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'New Password and confirm Password mismatch!'}) except ValueError: return render(request, 'pmp/changepassword.html',{'form': AuthenticationForm(), 'error': 'Password not changed!'}) return render(request, 'pmp/changepassword.html') -
How to fix `TypeError: 'AnonymousUser' object is not iterable ` in Django
I'm using LoginRequiredMixin in Django. However I got error. TypeError: 'AnonymousUser' object is not iterable It happen in this line if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: of this code. class SpeakerListView(LoginRequiredMixin, ListView): template_name = 'speaker/list.html' context_object_name = 'speakers' model = Speaker def dispatch(self, request, *args, **kwargs): # if user does not have speaker, redirect to create view if Speaker.objects.filter(user=self.request.user, is_deleted=False).count() == 0: messages.error(request, _('xxx')) return redirect('speech:speaker_add') return super().dispatch(request, *args, **kwargs) If you know, how to solve this problem. Please help me! -
Django: Update 2 tables
I'm trying to update two tables/models at once, but I'm stumbling on the correct approach. I have two models: Models (a simplified representation) : class WaiverAdult(models.Model): first_name = models.CharField(max_length=50, blank=True) class CheckIn(models.Model): adult = models.ForeignKey( WaiverAdult, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') checkintime = models.DateTimeField(blank=True, null=True) checkoutime = models.DateTimeField(blank=True, null=True) Here is my view: def checkin(request): waiver_id = request.POST.get('id') action = request.POST.get('action') if waiver_id and action: try: adult = WaiverAdult.objects.get(id=waiver_id) if action == 'checkmein': c = CheckIn(adult=adult) c.save() adult.status = True adult.save() ... I'd like to also save the "checkintime" to Checkin. Any direction is greatly appreciated. Thank you. -
Can't import module NAME - django password validators
I am trying to add custom password validators in Django but i can't figure out why it wouldn't import the module. Anyone has encountered this issue or can tell me why i have this error please ? Here is the code in authentication/validators.py: from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class LowercaseValidator(object): def validate(self, password, user=None): if not re.findall('[a-z]', password): raise ValidationError( _("The password must contain at least 1 lowercase letter, a-z."), code='password_no_lower', ) def get_help_text(self): return _( "Your password must contain at least 1 lowercase letter, a-z." ) Here is my updated settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 12, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'authentication.validators.LowercaseValidator', }, ] And here is the error i have: The module in NAME could not be imported: authentication.validators.LowercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. P.S: i did create an app called "authentication" and my validators.py is in the folder of the application. Thank you in advance for your answers ! -
Django: images not loading instead of alternative text
I tried to display media thumbnails from other news website on my django website homepage by using feedparser, but the image is not loading, instead the alternative displayed: this is my current homepage looks like homepage.html: <div class="col-md-2 my-auto"> <img src="{{ post.image.url }}" class="img-fluid ml-3 my-3" alt="{{ post.pubdate }}" > </div> models.py: class Post(models.Model): title = models.CharField(max_length=200) description = models.TextField() pubdate = models.DateTimeField() link = models.URLField() image = models.URLField() def __str__(self): return self.title startjobs.py(this file used feedparser to parse news): logger = logging.getLogger(__name__) def save_new_posts(feed): feed_title = feed.channel.title feed_image = feed.channel.image['href'][0] for item in feed.entries: if not Post.objects.filter(link=item.link).exists(): post = Post( title=item.title, description=item.description, pubdate=parser.parse(item.published), link=item.link, image=feed_image, ) post.save() def fetch_realpython_posts(): _feed = feedparser.parse("http://feeds.foxnews.com/foxnews/latest") save_new_posts(_feed) def fetch_talkpython_posts(): _feed = feedparser.parse("https://feeds.nbcnews.com/nbcnews/public/news") save_new_posts(_feed) def delete_old_job_executions(max_age=604_800): DjangoJobExecution.objects.delete_old_job_executions(max_age) views.py: class HomePage(ListView): template_name = "homepage.html" model = Post paginate_by = 10 ordering = ['pubdate'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["posts"] = Post.objects.filter().order_by("-pubdate")[ :10 ] return context main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path("", include("news.urls")), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='homepage.html'), name='homepage'), ] Not sure why the image is not displayed instead of alternative text, any help would be appreciated -
How can I get ip address in django
I am building an application in Django that gets the ip address of the user to track their location. And once their location is determined, I want to be able to figure if their signup date coincides with a holiday in their country. Please, how can I do this? Any module or library to install? Do I have to include some details in the models? Thanks. -
connect `sqlachemy` to the django db
Is there a way to connect sqlalchemy to the django db? I am running a django test where a test database is created connection._connections.settings['default'] gives: {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': 'qwertyu', 'HOST': 'localhost', 'PORT': '5432', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}} But if I try to connect to this database using sqlalchemy: user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql+psycopg2://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) a completely new database is created. So any data inserted using model.bulkcreate() live is a different database than the one created by sqlalchemy. I would like to be able to use both. I want to use sqlalchemy for long time series (1M to 10M rows) where model.bulkcreate() is taking very long. I find it weird that the engine of connection is 'django.db.backends.postgresql', while the engine of sqlalchemy is postgresql+psycopg2 or postgresql. Is there a way to connect connection with sqlalchemy? thanks -
How to make Apache pass through basic auth to Django?
How do you configure Apache to pass through all basic authentication requests so that they're handled by a Django WSGI site Apache's hosting? I've implemented a basic authentication handler directly in Django, based on this snippet, so that it integrates easily with the built-in admin app, and is more easy to unittest and integrate with my Django application's custom logging. This works perfectly when run from the devserver. Unfortunately, I'm finding that when run from behind Apache, the default Apache config denies all basic authentication requests, and doesn't bother to send them to Django. These docs recommend some ways to setup conventional Apache basic auth configs, but they all assume a hard-coded path and special permissions for this distinct site, which has to be setup to explicitly do the credential checking with data passed from Apache. I have application logic that dynamically determines the paths that should be tested for basic auth, and therefore need to be handled by Django, and never by Apache so I don't want Apache to do anything for basic authentication. I just want it to pass through the request, and let Django worry about checking credentials, and then returning a 401 response. I can't find … -
How to extract text from a word doc textbox using Python/Django and docx
I am trying to extract and replace text in a .docx word file using the docx library with python (3.7) which i then save as "TESTFIL.docx" The normal paragraph text in the doc extracts fine and i can replace it, however any text within a textbox is not being picked up. Appreciate any help, tips or libraries i can use side note: the Aspose library does both, but the $1000 license fee is just too much for this project. Code snippet below: def replaceDoc2(self,file,variables): print("WE Here") doc=Document(file) Dictionary = {"NAME": "SHILLAN", "MEMBERSHIPNO":"0007"} for i in Dictionary: for p in doc.paragraphs: print(p.text) if p.text.find(i)>=0: p.text=p.text.replace(i,Dictionary[i]) #save changed document if os.path.exists("TESTFIL.docx"): os.remove("TESTFIL.docx") doc.save('TESTFIL.docx') else: print("The file does not exist") doc.save('TESTFIL.docx') -
How to select a specific HTML element from a for loop in a Django template?
I am trying to create a button that hides and displays only the specific HTML elements that are in the same div with it through JavaScript. All the divs are within a Django template for loop and display different information. Right now, I am using a querySelector to select the id, but that is not correct because it selects the first element it finds with that id. html <div> {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6> <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6> {% if post.user == request.user %} <button class="edit_button" value="{{ post.id }}">Edit</button> {% endif %} <textarea class="textarea" id="edit_area"></textarea> <input type="submit" value="Save" class="edit_save" id="save"> </div> {% endfor %} </div> javascript document.addEventListener('DOMContentLoaded', function(){ //hide the textarea const editingTextareas = document.querySelectorAll(".textarea"); for (const textarea of editingTextareas){ textarea.style.display = 'none'; } //hide the save buttons for the textarea const saveButtons = document.querySelectorAll(".edit_save"); for (const s_button of saveButtons){ s_button.style.display = 'none'; } //adds the click to the edit buttons const editButtons = document.querySelectorAll('.edit_button'); for (const button of editButtons) { id = button.value; button.addEventListener('click', () => … -
Where to find the headers of its deployed heroku application?
This is a pretty short question. I deployed a Django app to heroku and would like to have access to the contents of that app's security headers. The subject is not well documented on the Internet. I don't know the procedure to access it. Thanks! -
how to load image from django models
i want to load the picture from model. but i get "<QuerySet [<Photo: ira>]>" except of photo. i have tried to use photo.url, photo.image.url, photo.image, photo.image.image but it does not work my templtate: <div id="userInfo"> <img src="{{ photo.url }}" alt="{{ username }}"> <div id="statusAndName"> <h1>{{ username }}</h1> <h3>{{ status }}</h3> </div> </div> my view: def UserPage(request,user_num): user = User.objects.get(pk=user_num) #get user info username = user.username posts = Post.objects.filter(user=user.id) photo = Photo.objects.filter(user=user.id) status = user.status return render( request, 'userpage.html', context={'username': username, 'posts': posts, 'status': status, 'photo': photo}, ) my models: class Photo(models.Model): """ A typical class defining a model, derived from the Model class. """ # Fields user = models.OneToOneField('User', on_delete=models.SET_NULL, null=True, help_text="user's id") photo = models.ImageField() # Metadata class Meta: ordering = ["-user"] def __str__(self): """ String for representing the MyModelName object (in Admin site etc.) """ return self.user.username -
Why do I get this error when I deploy a Django App in Railway?
There is a problem when I deploy a Django app in Railway, this is the error that is in the logs. Error message I have looked up the error in Google, and I got that I have to change the library "psycopg2" to "psycopg2-binary", but I still get the same error. Version of psycopg2-binary Is there some idea about what is happening? -
How to access the filtered list of related objects when using FilteredRelation?
I have a list of Funds that I have to query by their related model Commitment (as in "return the funds in which associated commitments fill this criteria). I need to annotate each fund with an aggregation over the filtered commitments, as well as access each item in the filtered relation. I'm trying to use FilteredRelation: funds = Fund.objects.annotate( f_commitments=FilteredRelation( "commitments", condition=Q(pk="c40ae23d-50ee-47c5-9397-c1670098ecd9") ) ) I'm trying a basic query just to test the filter. The query runs, but the funds it returns don't have a f_commitments attribute as it usually does with annotations: AttributeError: 'Fund' object has no attribute 'f_commitments' Is there something wrong with the query or FilteredRelation don't support accessing the filtered items directly? -
Is there any way to remove the index error ,
i am building a simple website which displays the value from the csv file . The csv files contains id,name,hr,bp values . But when we give the id number it says index out of range will be attaching the code and pics error website demo.csv main.py -
Django PositiveBigIntegerField
So, im trying to work on my apps and I have PositiveBigIntegerField's in some of my models. I thought for sure it was already included with Django but now i'm starting to think otherwise. Whenever I run my server, im getting an error stating that AttributeError: module 'django.db.models' has no attribute 'PositiveBigIntegerField' Has anyone run into this problem before? -
Cannot assign requested address when connecting to Redis through Docker
Creating containers from my Django+Redis+React project and getting the error: Error 99 connecting to localhost:49157. Cannot assign requested address. When I visit the url localhost:8000 This is my docker-compose file: version: "3.8" services: redis: restart: always image: redis:latest ports: - "6379:6379" pairprogramming_be: restart: always depends_on: - redis command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - ./signup/.env - ./payments/.env - ./.env build: context: ./ dockerfile: Dockerfile ports: - "8000:8000" container_name: "pairprogramming_be" ... #Error 99 connecting to localhost:49153. Cannot assign requested address. This my .env file: DEBUG=1 DJANGO_ALLOWED_HOSTS=0.0.0.0 my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR django-project/peerplatform COPY requirements.txt ./ RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . ./ EXPOSE 8000 CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000", "--settings=signup.settings"] Here is my settings.py incase the issue is here: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://redis:6379", # "TIMEOUT": 5 * 60, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "pairprogramming" } } ... CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "LOCATION": "redis://redis:6379", }, } ... REDIS_HOST = 'redis://redis:6379' REDIS_PORT = 6379 REDIS_PASSWORD = 'redispw' -
css is not working after deploying django application on aws with gunicorn nginx
I have deployed my django project on EC2 but the css is not working after deployement. I also ran collcectstatic command but still got unlucky, when I checked in nginx error.log it showing in front of css files that permission denied like this: 2022/07/18 17:38:01 [error] 2262#2262: *4 open() "/home/ubuntu/theoj/online_judge_project/staticindex.css" failed (13: Permission denied), client: 49.38.225.106, server: 13.126.144.76, request: "GET /static/index.css HTTP/1.1", host: "13.126.144.76", my project directory structure: online_judge_project/ account/ homesrc/ language/ media/ oj/ /*name of my project*/ settings.py problempg/ static/ /* folder containing css files*/ staticfiles/ /* folder made after running command collectstatics*/ template/ manage.py **settings.py: ** """ Django settings for oj project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from importlib.resources import path from pathlib import Path import os from .info import * EMAIL_USE_TLS = EMAIL_USE_TLS EMAIL_HOST = EMAIL_HOST EMAIL_HOST_USER = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD EMAIL_PORT = EMAIL_PORT # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR=os.path.join(BASE_DIR,'template') FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = …