Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at when calling url
I can't work out why im getting this error NoReverseMatch at / when calling <a href="{% url 'show_token_details' token.id %}"> def show_token_details(request,token_id): token = Token.objects.get(token_id == token_id) return render(request, 'ecommerceproductdetails.html', {}) path("token/<int:token_id>", views.show_token_details, name='show_token_details'), What am I missing here? Thanks -
How can I pass in the login/register data for my django-rest api in the form of a url?
I am following along with a book on the django-rest framework and I am having issues grasping a certain concept. The book uses the built-in Browsable API feature to do basic CRUD and LOGIN/LOGOUT/REGISTRATION functionality. What it fails to mention is how I can achieve such functionality using only the URL, which would be needed for, say connecting the API to the frontend of a REACT app. Example: I have an API which displays Posts and this path shows all posts: path('api/v1/', include('posts.urls')), I want to use this path for example, to register. path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), How would the URL look like ? -
Why are my images not showing at the index page?
I am trying to create an auction website where the users can input an image url and bid on the entries. The issue I am currently having is that my images are not reflecting on my index page except I hard code it. I'm not sure what I am doing wrong as I have tried using different options such as using an imageField and trying to convert the URL to an image(This didn't work) and I have tried tweaking the codes but still having the same issue. Please assist a newbie URL.PY path("create/", views.create_listing, name="create_listing"), MODELS.PY class Auction(models.Model): ABSTRACT = 'AB' MODERN = 'MN' ILLUSTRATION = 'IN' select_category = [ ('ABSTRACT', 'Abstract'), ('MODERN', 'Modern'), ('ILLUSTRATION', 'Illustration') ] title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) # image_upload = models.ImageField(upload_to='images/') image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) category = models.CharField( choices=select_category, max_length=12, default=MODERN, ) created_at = models.DateTimeField(auto_now_add=True) FORMS.PY class AuctionForm(forms.ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid', 'image_url', 'category'] VIEWS.PY def create_listing(request): form = AuctionForm() user = request.user if request.method == 'POST': form = AuctionForm(request.POST, request.FILES) images = Auction.objects.get('image_url') if form.is_valid: context = { 'user': user, 'images': images } form.save() return redirect('index', context) else: form = … -
Symmetrical link between two objects in Django
I have a model with all the info of a plant and another model which consists of creating links between these plants. But when I create a link between two plants for example I create an ideal link between basil and garlic in the Django admin, I don't have the symmetrical link between garlic and basil. Should we add symmetrical = true in the model? Here is Plant model : from django.db import models class Plant(models.Model): class LEVEL(models.TextChoices): NONE = None EASY = 'easy', MEDIUM = 'medium', HARD = 'hard' class SUNSHINE(models.TextChoices): NONE = None FULL_SUN = 'full_sun', SHADOW = 'shadow', SUNNY = 'sunny', MODERATE = 'moderate' class IRRIGATION(models.TextChoices): NONE = None WET = 'wet', WEAKLY = 'weakly', MOIST = 'keep_soil_moist', GENEROUSLY = 'generously', SLIGHTLY_DAMP = 'slightly_damp', COVERED_WITH_WATER = 'covered_with_water' class SOIL_N(models.TextChoices): NONE = None HUMUS = 'humus', LIGHT = 'light', CLAY = 'clay', DRAINED = 'drained', ALL_TYPE = 'all_types' class SOIL_T(models.TextChoices): NONE = None POOR = 'poor', MEDIUM_SOIL = 'medium_soil', RICH = 'rich', FERTILE = 'fertile', DRAINED = 'drained', ADD_PEBBLES = 'add_pebbles', ALL_TYPE = 'all_types' class HARDINESS(models.TextChoices): NONE = None VERY_FRAGILE = 'very_fragile', FRAGILE = 'fragile', RUSTIC = 'rustic', MEDIUM = 'medium', SUPPORT_FRESHNESS = 'support_freshness', # COLD_RESISTANT = 'cold_resistant' … -
HTML show image if it exists and show nothing if it doesn't
I need to display an image on my HTML page but only if it exists in my directory. If it doesn't, then show nothing. How can I write a function that checks if the image exists, then if yes, display it if no, don't show anything? I am using django as a back end. -
Django channels Disconect after closing the tab
I'm new to Django channels and I'm building a simple chatroom. With this chatroom, I want to disconnect a user if he closes the browser tab and if he reopens the tab with the same link, I want to reconnect him to the same chat that he was. How can I do that? -
Django not finding environment variables set by Github Actions
I have a Github Action that creates a Docker image, and the issue I am having is that when I docker logs backend I get an error like: File "/usr/src/app/api/settings/common.py", line 165, in <module> AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"] File "/usr/local/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'AWS_ACCESS_KEY_ID' As part of my .yml for GitHub I have this code which from research should inject the environment variables into my Docker image. jobs: build_and_deploy_backend__production: runs-on: ubuntu-latest steps: - name: Checkout the repo uses: actions/checkout@v2 - name: Build image run: docker build -t backend . env: AWS_ACCESS_KEY_ID: ${{ secrets.GLOBAL_AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.GLOBAL_AWS_SECRET_ACCESS_KEY }} I am wondering if there is anything obvious that I am doing wrong. -
How i can implement asyncio in the below on function
Basically i wanna to extract youtube video information but "ydl.extract_info(video_url_id, download=False)" take 3 seconds per request. and atleast 50 to 100 request is required and it takes alot time. def get_video_urls(video): ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'}) final_list= [] for url in video: video_url_id= f'https://www.youtube.com/watch?v={url["snippet"]["resourceId"]["videoId"]}' with youtube_dl.YoutubeDL({'forceurl':True, 'quiet':True, 'skip_download':True}) as ydl: result = ydl.extract_info(video_url_id, download=False) final_list.append(result['formats'][-2]['url']) return final_list -
How to show the progress of PG stored procedure in a DJango Application
We have a long-running stored procedure that can be invoked from a Django web application. How can I show the status on the stored procedure in my web page, say in-progress, error, or completed in my web page? -
Can't figure out DeclarativeMeta error with alembic and sqlalchemy in django project
I could use some help figuring out how to debug this: I suspect that there is something wrong with my models.py file but the error messages are pretty vague. Using Alembic and sqlalchemy instead of Django ORM (relatively new to all the above) and successfully made a migration and migrated it to alembic version folder. Whole reason I'm using alembic sql alchemy is because I am trying to hit external api and was told in another post that alembic was needed to manage migration histories or there would be issues with django tracking migrations. I have a custom command class that calls the scraper and I am passing the data to pandas dataframe then attempt to write it to database defined in my models.py file. For brevity I will just post my models.py, the end of the error log as well as link to full repo from datetime import datetime from sqlalchemy import Column, Integer, DateTime, String, Numeric, BigInteger, UniqueConstraint from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from django.db import models class CMC(Base): __tablename__ = 'apis_cmc' id = Column(Integer, primary_key=True) inserted_at = Column(DateTime, default=datetime.utcnow) name = Column(String) symbol = Column(String) price = Column(Numeric) market_cap = Column(BigInteger) market_cap_dominance = Column(BigInteger) fully_diluted_market_cap … -
django connect remote postgresql
Trying to connect to a remote server, serving my posgresql My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'ubuntu@username.host.com', 'PORT': '5432', } } Getting error: django.db.utils.OperationalError: could not translate host name "ubuntu@hostname.host.com" to address: Name or service not known Where the hostname and host is of course not hostname and host, just using for this example. -
Trouble posting to many-to-many field
I am trying to post a combination object, which refers to already existing tag objects. Basically I want the tag_id field of the combination to include 2 ids referring to Tag objects. This is my code: models.py class Combination(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True) resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True) tag_id = models.ManyToManyField(Tag, null=True) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) objects = models.Manager() def __str__(self): return str(self.tag_id) or '' serializers.py class CombinationSerializer(serializers.ModelSerializer): tag_id = TagWithIdSerializer(many=True, required=False) resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(), required=True, source='resource', write_only=False) gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(), required=False, source='gameround', write_only=False) user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(), required=False, source='user', write_only=False) class Meta: model = Combination depth = 1 fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score') def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user score = 0 tag_data = validated_data.pop('tag_id') combination = Combination( user=user, gameround=validated_data.get("gameround"), resource=validated_data.get("resource"), created=datetime.now(), score=score ) for tag_object in tag_data: combination.set(tag_id=tag_object) if len(combination.tag_id) == 2: return combination def to_representation(self, instance): rep = super().to_representation(instance) rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data return rep With this I am currently getting an AttributeError : 'Combination' object has no attribute 'set' How can I get rid of this? -
Page not found(404),Current path didn't match any of these
Views.py From django.http import HttpResponse def home(request): Return HttpResponse('Hello World') urls.py(my_app) From Django.urls import path From . Import views Urlspatterns=[ Path(' ',views.home) ] Main urls From django.urls import path, include From Django.contrib import adim Urlspatterns=[ Path('admim/',.....) Path(' ',include('my_app.urls)) Settings.py Installed apps=[ " ", " ", 'my_app', ] Why I run the server it tells me page not found, ....... current empty path didn't match any of these, my Django has been working fine until recently, even if I start a new project from scratch it ends up with same result, I'm actually at the edge of giving up on Django ,I really need help please.... thanks in advance -
RedisCache' object has no attribute 'ttl'
hello friends in new project i use Django4 and i set the "django.core.cache.backends.redis.RedisCache" for the cache but i have the error it say "AttributeError: 'RedisCache' object has no attribute 'ttl'" .it refer to the line of my code that i add it below : from django.core.cache import cache def validate_token(token, check_time=True): if cache.ttl(token) == 0: return False try: data = claim_token(token) except Exception: return False if "type" not in data.keys(): return False can anyone tell me how i can resolve it ? (i know ttl mean time to live) -
Converting RGB PDF in CMYK with plain black using ghostscripts sOutputICCProfile
currently i am generating a pdf using weasyprint version 52.5. The pdf generated is in RGB but i need it in CMYK for printing. Now i tried converting it using ghostscript version 9.50 which works just fine, but my generated PDF always consists of texts in rich black. I did find a solution to convert the RGB(0,0,0) to plain black(K=100%). I tried the hack described in this issue: Converting (any) PDF to black (K)-only CMYK. But this only worked if my pdf didn't consists any transparent objects which i have, else ghostscript would render my PDF to a bitmap which i don't want. Now instead of using the hack, the ghostscript support recommended using ICC profiles to accomplish the same result: https://bugs.ghostscript.com/show_bug.cgi?id=704872. So i had to consult my printer to provide me with an icc profiles which i should use instead of the hack. And here is the problem, i can't get to make ghostscript use and embedd the ICC profile into the pdf. It seems ghostscript converts the pdf to cmyk but i think its using the defaul_cmyk.icc profile and not my specified icc profle. Also i don't realy think that the ICC profile from my printer is the … -
Fetching data to Django view working manually but not with Selenium. Why?
I am using Selenium to test a Django app I have created. The following code works fine 'manually' but does not work with Selenium. Why ? ## dummy.html ## {% extends 'main.html' %} {% load static %} {% block title %} Dummy page {% endblock title %} {% block meta %} <meta name="robots" content="noindex"> {% endblock meta %} {% block content %} <div class="container"> <div class="row"> <div class="col d-flex justify-content-center align-items-center"> <h1 class="text-primary font-handwriting">Dummy page</h1> </div> </div> <br> <div class="row"> <div class="col d-flex justify-content-center align-items-center"> <h2 class="text-primary font-heading">THIS IS A DUMMY PAGE</h2> </div> </div> <br> <div class="row"> <button id="trigger-dummy-button" type="button" class="btn btn-primary text-white font-base fw-bold text-uppercase" title="Trigger dummy button">Trigger dummy button</button> </div> </div> <script> var someDummyURL = "{% url 'home_page:another_dummy_view' %}"; </script> <script type="module" src="{% static '/js/dummy.js' %}"> </script> {% endblock content %} ## dummy.js ## 'use strict'; var newValue; async function postDummyFunction(request) { var response = await fetch(request); if (response.ok) { var updatedReturnedValue = await response.json(); newValue = updatedReturnedValue.returnedValue; alert('-- postDummyFunction -- | newValue = ' + newValue); // When the script is triggered manually by clicking, response.ok = true and newValue = "Hello World OK !" return newValue; } else { // When the script is triggered by … -
What is causing the '403 Forbidden error' in my Apache2 server? And how can I fix it? The available fixes on the web are not working for me
A little bit of context to my problem... I'm trying to deploy my django application following a tutorial (https://www.youtube.com/watch?v=Sa_kQheCnds) which uses linode to setup a linux apache server, and after following the steps, it always results in the same error, 403 Forbidden: You don't have permission to access this resource. I've followed the steps in this guide roughly 6 times now and I've determined that I'm definitely not doing anything the guy didn't do. Something worth mentioning is that in the tutorial, Ubuntu 18.10 is being used, however I don't have Ubuntu 18.10 available, so I've tried it using Ubuntu 18.04, 20.04 and 21.10. In my sixth and latest attempt, I am using Ubuntu 21.10 I've also tried running the server with DEBUG=True to see if I can get a little more insight on the error, but it just displays the following: The tutorial is very long so I've broken down every single step in this post. The steps I had to follow are: (everything done in the Windows Linux Bash shell) Creating Linode and analizing Ip Address and SSH Credentials I got Root Connection to the Server ssh into the server for the first time Installing Software Updates Running … -
Is there any way to get notifications to admin site in Django when new instances of models are created in database?
I am thinking of creating a website where users will add posts and basically I will check whether the posts are are valid or not in the Admin site. I was looking if it was possible to have some type of notification inside the admin every time someone posts or else I have to refresh the admin again and again everyday and continuously look for changes. Any sort of alternative solutions would also be appreciated. Thanks. -
Why I failed to connect to the django server?
enter image description here Please forgive me for the poor English expression. I follow the tutorial, use the command: python3 manage.py runserver 0.0.0.0:8080 in docker container and start django server like the picture. But I can not connect to it by IP. I am sure that I have already open the 8000 port and this port is on listening.By the way, I use the ubuntu and set the server in the aliyun. I am so confused with it and I can find the answer online (maybe my searching skill is bad). so I am asking for help.Thanks -
How to add additional image field not present in django forms
I need similar solution as provided in one issue over stackoverflow named as "Additional field in django form". But i want to use image field rather then input. Can anyone help? -
Can´t see user menu django-jazzmin
Hello I am having an issue with django-jazzmin. I can´t see the usermenu on the navbar I mean is there but even though i change the navbar colour it can't bee seen.In this first image you can see the issue even changing the navbar colour In thi second image you can see the issue even changing the navbar colour -
django-security-session: issue with session variable lost when session expired
I develop an app and I have some session variables used in views. I use django-security-session to logout user. But when user login after being logout with django-security-session, it is redirected to the last visited page/view, as it is supposed to be (normal django-security-session behaviour). But my issue, is that using session variable in views, when user is lougout, session variables are lost, and error is raised. Maybe I am do not have good "pratices" using sessions variables this way... but for now, I would like to keep using if possible. How can I manage this issue? settings.py SESSION_SECURITY_WARN_AFTER = 14*60 SESSION_SECURITY_EXPIRE_AFTER = 15*60 views.py @method_decorator(login_required, name="dispatch") class EligibiliteUpdate(SuccessMessageMixin, UpdateView): model = Eligibilite form_class = EligibiliteForm template_name = "ecrf/eligibilite_form.html" # nom template à utiliser avec CBV : [nom_model]_form.html success_message = "La fiche Eligibilite a été modifiée." def get_success_url(self): return reverse("ecrf:patient", args=[Patient.objects.get(pat = Eligibilite.objects.filter(ide = self.kwargs["pk"]).first().pat.pat).ide]) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) patient = self.request.session.get("patien # <= session variable lost when user is logout context["form_name"] = "eligibilite" context["ide"] = self.kwargs["pk"] context["exist"] = Eligibilite.objects.filter(pat = patient.ide).exists() # <= error raised # creation context["eli_sai_log"] = Eligibilite.objects.get(ide = self.kwargs["pk"]).eli_sai_log context["eli_sai_dat"] = Eligibilite.objects.get(ide = self.kwargs["pk"]).eli_sai_dat # lock context["is_locked"] = Eligibilite.objects.get(ide = self.kwargs["pk"]).ver context["user_has_lock"] = Eligibilite.objects.get(ide … -
Unable to create process using 'C:\Users\Abhishek Anand\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver'
I'm trying to use runserver command over vs code terminal. But now it is giving me the error. " Unable to create process using 'C:\Users\Abhishek Anand\AppData\Local\Programs\Python\Python310\python.exe manage.py runserver'". But I have the python interpreter in my environment path. Also, I have my virtual environment which I created while initiating the project but still and using the interpreter in my environment I was getting the same error.. Please help me out with that.enter image description here -
Django Image Field default image clear
I've cleared Django Image Field default image from django admin panel. Now im getting error viewing the webpage in browser. So how can I undo this. If i set another image it's working well. But i can't leave this empty, is there any solution>>> django-admin default image -
Django - Retieve Data from Reservation Form and Display back to User
Trying to pull data from my Database and display it back to the user so they can edit/delete it for full CRUD functionality. At the moment when i iterate through the reservations it comes back empty. Below is the relevent code: Models.py file: class Reservations(models.Model): name = models.CharField(max_length=50) phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16, unique=True) email = models.EmailField() date = models.DateField() time = models.CharField(choices=time_options, default="12pm", max_length=10) number_of_party = models.IntegerField(choices=party_size, default=1) reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, max_length=15) Then the forms.py file: class ReservationForm(forms.ModelForm): class Meta: model = Reservations fields = ['name', 'phone_number', 'email', 'date', 'time', 'number_of_party'] widgets = { 'date': DatePickerInput(format='%d-%m-%Y'), } Views.py: class RetrieveReservationView(ListView): model = ReservationForm Path in the Urls.py file: path('retrieve/<slug:pk>/', RetrieveReservationView.as_view(), name="retrieve_reservation"), And Finally the Html file associated with it: <ul> <!-- Iterate over reservations list --> {% for reservation in reservations %} <!-- Display Objects --> <li>{{ reservation.name }}</li> <li>{{ reservation.phone_number }}</li> <li>{{ reservation.email }}</li> <li>{{ reservation.date }}</li> <li>{{ reservation.time }}</li> <li>{{ reservation.number_of_party }}</li> <hr/> <!-- If object_list is empty --> {% empty %} <li>No Reservation have been made</li> {% endfor %} </ul> At the moment i just keep getting back "No Reservation has been made" but i have two/three in the database for the user logged in. …