Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + google spreadsheets API how to save sheet data to model
I'm total newbie in django and I'm trying to save data that i get from my spreadsheet API to the model and be able to edit it on admin site. Using .get_all_values() I'm getting a list that contains whole spreadsheet data. I'd like to save that list to the model and make it that way -
size responsive field in django forms
I'm making an web application and i wanted to create responsive fields in my forms. When im visiting my site in small window all my forms fileds stick out of their containers borders. Example of my html code from login window. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login DomainManager</title> {% load static %} <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"> </script> </head> <body> <div class="center"> <div class="panel panel-info" > <div class="panel-heading"> <center> <h3 class="panel-title">Login</h3> </center> </div> <div class="panel-body"> <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p><b>Username: {{ form.username }}</b></p> <p><b> Password: {{ form.password }}</b></p> <center> <p><input type="submit" value="Login"></p> <input type="hidden" name="next" value="{{ next }}"> <a href="/register" style="color: black">No account? Register</a> </center> {% if form.errors %} <center> <p style="color:#ff0000;">Your login or password is wrong!</p> <p><a href="/accounts/password_reset/" style="color: black">Forgot password?</a></p> </center> {% endif %} {% if next %} <p>No access.</p> {% endif %} </form> </div> </div> </div> </body> </html> <style> body { background-color:#f9f9f9; } .panel > .panel-heading { background-color: #222222; color: gray; text-align: center; } .panel-info { border-color: #222222; } .panel-body { padding-left: 10%; padding-right: 10%; } div.center { margin: 0; width: 15%; top: 30%; left: 50%; position: absolute; -ms-transform: translate(-50%, -30%); transform: translate(-50%, -30%); } </style> i use UserCreationForms … -
Is it possible to reference a model's verbose name in help text?
I'm looking to do something like below. class AbstractIsActive(models.Model): is_active = models.BooleanField( 'active', default=True, help_text='Select to determine whether a %(verbose_name)s is active.' ) class Meta: abstract = True I'm having a hard time finding where in the ForeignKey field code it allows you to use %(class)s in verbose_name. -
redis server not working in Django application on Windows
I'm trying to make a chat application using django-channels following the documentation but there is this one final stage where I'm stuck. After putting channel-layers in settings.py as mentioned in the docs: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I honestly don't know how to handle this redis-channel issue but I followed the help from this forum as well but this didn't help. Now there is no issue in starting the server but the moment I put a message in the chat box, It doesn't appears on the chat box in the same room in another window (which according to documentation should happen). Instead it gives me an error on the server console saying: aioredis.errors.ReplyError: ERR unknown command 'EVAL' WebSocket DISCONNECT /ws/chat/room/ [127.0.0.1:64070] If I need to re-install redis on my windows machine please let me know how can I do it properly. Any kind of help will be highly appreciated. -
I'm trying to fetch particular data using ajax, I can't do it properly
I'm trying to fetch particular data from the database using ajax, I can get all data using 'all()' method. But I can't get particular data only ajax code <script type="text/javascript"> $(document).ready(function(){ $("#request-btn").click(function(){ $.ajax({ url: "{% url 'contact_details' %}", type: "GET", data: { property: "{{ property.id }}" }, dataType:"json", success: function(result){ $.each(result, function() { $("#request-btn").hide() html = "<h6>Contact me" + "<br>" + "Email:" + this.email + "<br>" +"Mobile:" + this.mobile + "<hr>" $("#response").append(html) }); } }); }); }); views.py def contact_details(request): property_id = request.GET.get('property') if request.user.is_authenticated: property_details = Property.objects.get(id=property_id) seraializer = PropertySerializer(property_details, many=True) details = seraializer.data return JsonResponse(details, safe=False ) else: return JsonResponse({"authenticated": False}) It throws the error TypeError: 'Property' object is not iterable In 'all()' method it gives all the data, For testing I make some changes in code(changed 'many=True' to 'many=False) seraializer = PropertySerializer(property_details, many=False) but it gives undefined values and output shown repeately here serialization I'm using serializers. serializer.py class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = ('id', 'email', 'mobile') I need to Email and mobile data, How to fix this -
using request.data instead of serializer class in Django
I have been using in one of my views request.data instead of serialzer to get json data and work on it, my question is this ok or lets say "a good practice" to use request.data or should i create serializer class for that view? -
Django - show all images assigned to the post
I am creating blog application and I would like to show all images which were uploaded to the single blog post. Here are my Models.py: class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE, related_name='postimages') image = models.ImageField(upload_to='gallery/') Views.py class PostGalleryView(DetailView): model = Post template_name = 'blog/gallery.html' context_object_name = 'photos' In the template if I put there {{ photos.postimages }} then it shows on the page: blog.PostImage.None even though that 2 images are uploaded to the particular blog post. {{ photos.postimages.count }} shows number 2. If I tried to loop through photos.postimages it throws an error: 'RelatedManager' object is not iterable. Any idea how I can access the PostImage model in the template? -
Displaying PNG in Django
i am currently working on a project where i want to get a screenshot of an given url. After displaying this screenshot i take this png and modulate it into a RGB-image. I have 2 problems. First since a few days, the correct screenshot-png is not displayed anymore but an older version gets displayed every time, even though in my media dir the current screenshot is correct. Second my function for modulating doesnt display any RGB-png not even creates it in the folder. This is very surprising since i used this function/algorithm outside of django and it excellently worked. Maybe I forgot any details. Any Help is much appreciated, thanks in advance!! [1] (https://i.stack.imgur.com/cOCpd.jpg "screenshot") [2] (https://i.stack.imgur.com/N2jAl.jpg "modulate") [3] (https://i.stack.imgur.com/BtpG8.jpg "html") [4] (https://i.stack.imgur.com/b1RGL.jpg "settings") -
Django 3.1 media prefix not showing on urls
I am using Django 3.1. settings.py looks like BASE_DIR = Path(__file__).resolve(strict=True).parent.parent MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' urls.py looks like from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my model image field looks like dev_image_one = models.ImageField(upload_to='dev/', blank=True, null=True, verbose_name = 'image 1') When files are uploaded, they end up in the /media/dev directory. When they are to be displayed, the url looks like: <img src="dev/1.png"> If I manually append /media/ on to the front of the url, the image displays. I never had this problem before so I'm at a loss as to what is going wrong. I never used 3.1 before, so I'm wondering if that doesn't have something to do with it. No problem with the static files. Thanks. -
Python Geoip2 maxminddb.reader error in EC2 server
Hi I am facing a issue with below code. PS : Its working fine with my local machine but facing issues in servers. import geoip2.database def get_geo_city_from_ip(ip="103.148.20.109"): try: reader = geoip2.database.Reader('GeoLite2-City.mmdb') response = reader.city(ip) city=response.city.name reader.close() return city except Exception as e: return None a = get_geo_city_from_ip() print("City ####",a) Error Traceback (most recent call last): File "test.py", line 2, in <module> import geoip2.database File "/var/www/html/geo/test/lib/python3.5/site-packages/geoip2/database.py", line 10, in <module> import maxminddb File "/var/www/html/geo/test/lib/python3.5/site-packages/maxminddb/__init__.py", line 5, in <module> import maxminddb.reader File "/var/www/html/geo/test/lib/python3.5/site-packages/maxminddb/reader.py", line 36 _buffer: Union[bytes, FileBuffer, "mmap.mmap"] ^ SyntaxError: invalid syntax Packages & Version Python 3.5.2 aiohttp==3.6.2 async-timeout==3.0.1 attrs==20.2.0 certifi==2020.6.20 chardet==3.0.4 geoip2==4.0.2 idna==2.10 idna-ssl==1.1.0 maxminddb==2.0.2 multidict==4.7.6 pkg-resources==0.0.0 requests==2.24.0 simplegeoip2==1.0.2 typing-extensions==3.7.4.3 urllib3==1.25.10 yarl==1.5.1 -
Post method is not updating database Django
Post method is not updating database Hi everyone! I’m really new in Django and python and I really need your help, please. I need to modify one attribute (state) of an instance of my Anomalie class. I'm using forms to do that. The problem is when I “submit” to update it, I have nothing in my database. I'm following step-by-step tutorial but in my case is not working. So here is my model class: class Anomalie (models.Model): ANOMALIE = ( ("Etiquette absente", "Etiquette absente"), ("Etiquette decalee", "Etiquette decalee"), ("Etiquette inconnue", "Etiquette inconnue"), ) ANOMALIE_STATE = ( ("traité", "traité"), ("mise à jour", "mise à jour"), ("signalé", "signalé"), ) type = models.CharField( max_length=200, choices=ANOMALIE, null=False) date_report = models.DateTimeField(null=False, blank=False) localization = models.TextField(max_length=30, null=False, blank=False) state = models.CharField( max_length=200, choices=ANOMALIE_STATE, null=False) aisle = models.ForeignKey(Aisle, null=True, on_delete=models.SET_NULL) product = models.ForeignKey( Product, null=True, on_delete=models.SET_NULL) def datepublished(self): return self.date_report.strftime('%B %d %Y') def __str__(self): return self.type this is the view.py def treter_anomalie(request, pk): anomalie_pk = Anomalie.objects.get(id=pk) if request.method == "POST": anomalie_pk.state = 'traité' return redirect('/') context = {'anomalie_pk': anomalie_pk} return render(request, 'anomalie/treter_anomalie.html', context) this is the treter_anomalie.html {% extends 'base.html'%} {% load static %} {%block content%} <div id="layoutSidenav"> <div id="layoutSidenav_content"> <main> <div class="container-fluid"> <P>treter anomalie {{ anomalie_pk.id … -
Django filtering using multiple queries
On my homepage I have a search bar and when you search something it redirects you to a page with the results(titles and document types). On the left side of the page I want to implement a filter by document type. After the search my url looks like this: http://127.0.0.1:8000/search/?q=something After applying the filter: http://127.0.0.1:8000/search/?document_type=Tehnical+report I don't know how to implement the filters to search just in the objects list filtered by the query (q) on the search page. Also, I'm not sure if the url should look like this : http://127.0.0.1:8000/search/?q=something&document_type=Tehnical+report or like this http://127.0.0.1:8000/search/?document_type=Tehnical+report after applying the filter. models.py DOCUMENT_TYPES = [ ('Tehnical report','Tehnical report'), ('Bachelor thesis','Bachelor thesis'), ... ] class Form_Data(models.Model): title = models.CharField(unique=True, max_length=100, blank=False) author = models.CharField(max_length=100) document_type = models.CharField(choices=DOCUMENT_TYPES, max_length=255, blank=False, default=None) views.py def search_list(request): object_list = Form_Data.objects.none() document_types = DOCUMENT_TYPES query = request.GET.get('q') document_type_query = request.GET.get('document_type') for item in query: object_list |= Form_Data.objects.filter( Q(title__icontains=item) | Q(author__icontains=item)) return render(request, "Home_Page/search_results.html") home_page.html <div class="Search"> <form action="{% url 'home_page:search_results' %}" method="get"> <input id="Search_Bar" type="text" name="q"> <button id="Button_Search" type="submit"></button> </form> </div> search_results.html {% for form_data in object_list %} <h5>{{ form_data.title }}</h5> <h5>{{ form_data.document_type }}</h5> {% endfor %} <form method="GET" action="."> <select class="form-control" name="document_type"> {% for tag, label … -
Django cannot find 'channels.routing'
I am going through django channels tutorial. I've installed channels and when i import channels.routing in myProject/routing.py i get error Cannot find reference 'routing' in 'imported module channels'. I've clicked install package routing but it's given me nothing. I am still struggling with. If needed, i've included channels in settings -
How to create a div after 4 elements in django template
I Hope You Are Good I want to show my city in my footer I want 4 cities in each div after 4 cities added in div I want to create a new div and add 4 cities and so on here is the html reffrence: <div class="col-lg-3 col-md-3 col-sm-6 col-6"> <p><a href="/property/listings/?city=islamabad" class="fot-text">Islamabad</a></p> <p><a href="/property/listings/?city=karachi" class="fot-text">Karachi</a></p> <p><a href="/property/listings/?city=lahore" class="fot-text">Lahore</a></p> <p><a href="/property/listings/?city=rawalpindi" class="fot-text">Rawalpindi</a></p> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-6"> <p><a href="/property/listings/?city=Abbottabad" class="fot-text">Abbottabad</a></p> <p><a href="/property/listings/?city=Abdul Hakim" class="fot-text">Abdul Hakim</a></p> <p><a href="/property/listings/?city=Ahmedpur East" class="fot-text">Ahmedpur East</a></p> <p><a href="/property/listings/?city=Alipur" class="fot-text">Alipur</a></p> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-6"> <p><a href="/property/listings/?city=Arifwala" class="fot-text">Arifwala</a></p> <p><a href="/property/listings/?city=Astore" class="fot-text">Astore</a></p> <p><a href="/property/listings/?city=Attock" class="fot-text">Attock</a></p> <p><a href="/property/listings/?city=Awaran" class="fot-text">Awaran</a></p> </div> I want to like this HTML how can I achieve this! the following code dosen't work: <div class="col-lg-3 col-md-3 col-sm-6 col-6"> {% for city in citys %} <p><a href="/property/listings/?city={{ city }}" class="fot-text">{{ city }}</a></p> {% endfor %} </div> it adds all element in one div how can create new div after 4 items added on that div -
Get list of pending Celery jobs when no workers
I think I must be missing something. On my django server I do the following: inspector = app.control.inspect() for element in list: result = app.send_task("workerTasks.do_processing_task", args=[element, "spd"], queue="cloud") scheduled = inspector.scheduled() reserved = inspector.reserved() active = inspector.active() print("-- SCHEDULED") print(scheduled) print("-- RESERVED") print(reserved) print("-- ACTIVE") print(active) global_helper.execute_commands(["sudo rabbitmqctl list_queues"]) global_helper.execute_commands(["celery inspect active_queues"]) (excuse the printing, this is remote and I haven't set up remote debugging) There are no workers connected to the server, and I get this output: -- SCHEDULED None -- RESERVED None -- ACTIVE None [ sudo rabbitmqctl list_queues ] Listing queues ... [ celery inspect active_queues ] Error: No nodes replied within time constraint. So it looks like all of these tools require jobs to be on a worker somewhere. So my question is, how can I look at tasks which are still waiting to be picked up by a worker? (I have verified that app.send_task has been called 127 times) -
Django Monthly Calendar - Clickable Day
I am stuck with a basic understanding of django for a few days now. what do I have? a monthly calendar template showing me booked appointments a daily timetable template what do I want? I want the days of the monthly calendar be clickable, leading to the timetable of that specific day I failing to understand how to parse through the calendar in the html template to make the days clickable. I don't even know if this is the right approach. Plus, I do not know how to pass the day variable to the timetable template - all I able to manage is to show "today". any hints or reads that help me to wrap my head around this stuff? -
How to rewrite the respone of the django-simplejwt
{ "detail": "Authentication credentials were not provided." } I want to customize my own return format,but I can't find the position for the detail for example: { "error": "Authentication credentials were not provided." } -
How to set Django template path properly?
In most recent django documentation "Overriding from the project’s templates directory" https://docs.djangoproject.com/en/3.1/howto/overriding-templates/ it shows that you can use the following path for templates: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, ... }, ] I tried using [BASE_DIR / 'templates'] but I keep getting the following error: TypeError: unsupported operand type(s) for /: 'str' and 'str' It all works fine when I change the code to: [BASE_DIR , 'templates'] or [os.path.join(BASE_DIR , 'templates')], no problem in such case. Can someone explain what am I missing with the [BASE_DIR / 'templates'] line? Thank you. I'm using Python 3.8 and Django 3.1. -
heroku run python manage.py migrate not working
after applying all migration using heroku run python manage.py migrate. it gives this error. I had switched to postgresql. But migration are still applied only on sqlite3. OperationalError at / no such table: shastri_occasion Request Method: GET Request URL: https://bdsharma.herokuapp.com/ Django Version: 3.1.1 Exception Type: OperationalError Exception Value: no such table: shastri_occasion Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.12 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Fri, 11 Sep 2020 09:34:29 +0000 This is my setting.py database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ddbp7me1o4bf', 'USER' :'iwdvmaevgph', 'PASSWORD' : '****************************8', 'HOST' : '*****************8', 'PORT' : '5432', } } -
django recursion how to avoid self add in M2M
How to forbid user to follow itself? my user models: followers = models.ManyToManyField("self",blank=True,related_name='following', symmetrical=False) my action: @action(methods=['POST'], detail=True) def follow_unfollow(self, request, pk): follower = self.request.user user = get_object_or_404(User, id=pk) if user.followers.filter(id=follower.id).exists(): user.followers.remove(follower) else: user.followers.add(follower) return Response(status=status.HTTP_204_NO_CONTENT) -
Cannot install Django Framework on linux (PopOS - Ubuntu Based)
hbp@pop-os:~$ pip3 install Django Defaulting to user installation because normal site-packages is not writeable WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django/ Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping ERROR: Could not find a version that satisfies the requirement Django … -
activating celery worker and celery beat on cpanel host permanently
well i have wrote some tasks in my project and i have configured a celery worker and beat for 'em and everything is fine . i open the terminal run worker and beat and it just works. but this is on my local machine . i have deployed my project on a cpanel host and i've installed rabbitmq celery and everything there and also there i open the terminal of venv(with putty and ssh) and i run worker and beat with command line again and it works fine . but here is the thing . i can't do it cause i have to open my own computer and open 2 terminals and start workers.and when i close 'em workers stop . so how can i make them run permanently on the host ? -
Django - build a Facebook story - how to change BooleanField value after X days?
I'm trying something like a story FB apps. I don't know how to how to change BooleanField value after X days? class Story(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) image = models.ImageField(upload_to='story/') created_on = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title @property def is_active(self): if self.created_on < #(self.created_on + 2 days)# return False return True -
How to Customise Django default theme page?
I am developing functionality according to my requirement, and I want to customize Django default change_form.html file according to my App, I have set up all the files in the template/admin folder, suppose my app name is app1 the template path will be templates/admin/app1/modelname/files (change_form.html, change_list.html), I want to change in change_form.html files per my requirement, Because data is coming from multiple models in this file and I want to display data according to my requirements, please let me know how I can do it. this is the code that displays data on this file... {% block fields_sets %} {% for fieldset in adminform %} {% include "admin/includes/fieldset.html" %} {% endfor %} {% endblock %} -
Django Jinja output first element of list and then start for loop from second
I'm new to Django and I'm trying to output first picture of the model in the first div and all the other in the second div. I googled and didn't find any solutions. I'm sure that my solution is awful a bit. <div class="carousel-item active"> <img src="{{ carousels[0].image.url }}" class="d-block w-100" alt="..."> </div> {% for carousel in carousels([1]) %} <div class="carousel-item"> <img src="{{ carousel.image.url }}" class="d-block w-100" alt="..."> </div> {% endfor %} View: def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) carousels = Carousel.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products, 'carousels': carousels})