Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can not seem to register a namespace
My project was running fine, but then I decided to remake the entire thing and I keep getting the same error. I am trying to link all_blogs.html to detail.html. In all_blogs.html I have this a tag: . Every time I try to runserver I get the message "NoReverseMatch at /'blog' is not a registered namespace". From what I understand, we can register a namespace by adding "app_name = (namespace)" in urls.py. I did this and yet for some reason I still get the error. I am sure it has something to do with what I have in urlpatterns. Please check out my code and github link to see the entire project. github Thank you in advance for your efforts. Error page: NoReverseMatch at / 'blog' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: 'blog' is not a registered namespace Exception Location: C:\Python38\lib\site-packages\django\urls\base.py in reverse, line 83 Python Executable: C:\Python38\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\Admin\\Desktop\\webDev\\xennialsworld', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Python38\\lib\\site-packages'] Server time: Thu, 20 Aug 2020 22:54:36 +0000 My urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from … -
My model has a manytomanyfield field. I want to see the string value of this field and save it with the string value
My model has a manytomanyfield field. I want to see the string value of this field and save it with the string value Model.py class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) interior_feature = models.ManyToManyField(to="advertise.InteriorFeature") Serializer.py## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' -
elastic beanstalk key pair issue SSH
my django website is down and it's been one week without a result. The eb deploy is giving me issues even after updating many different version of wsgi.py the ec2 server is not accepting request load balancer is showing 404 I suspecting some sort of attack/corruption but, not sure. If I try to add key pair to my EB configuration- security it starts going into a infinite loop and new ec2 is created. SSH into instance dose not work all ports 22 http/https are set up. C:\Users\nor\Desktop\website>eb deploy Creating application version archive "app-200820_133953". Uploading: [##################################################] 100% Done... 2020-08-20 20:51:22 INFO Environment update is starting. 2020-08-20 20:51:45 INFO Deploying new version to instance(s). 2020-08-20 20:52:05 ERROR Your WSGIPath refers to a file that does not exist. 2020-08-20 20:52:19 INFO New application version was deployed to running EC2 instances. 2020-08-20 20:52:19 INFO Environment update completed successfully. [![auto created instance after adding key pair ][1]][1] -
Update session variable while request ongoing [Django]
I am using Django's session variable to store a list of requests and their status. When a task is started an entry is added to the session storage with request.session["history"][id] = new_entry(status=PENDING) When the request completes I set the value to request.session["history"][id] = new_entry(status=COMPLETE) But when the session variable is queried while the task is still running the new entry with status = PENDING is not in the session storage. def view(request): request.session["history"][id] = new_entry(id=k, status=PENDING) run_task() # --> takes time request.session["history"][id] = new_entry(id=k, status=COMPLETE) def get_history(request): history = request.session["history"] # --> does not contain new_entry(id=k, status=PENDING) when task is running EDIT The request.session.modified value is set to True after every update -
Using for loop to seperate formsets with <hr> only between forms and not at beginning or end
I only want the horizontal rule between each form and not at the beginning or end. How can I alter the code so that the last horizontal rule is removed and how many different ways are there to doing this? <form method="POST"> {% csrf_token %} {% for form in formset %} {{ form.as_p }} <hr> {% endfor %} <button type="submit">Add Family Members</button> </form> Here's another example: mylist = ['Tom', 'John', 'Jack', 'Joe'] for i in mylist: print(i) print('----------') How can I alter the code so that '--------' is printed between the names but not at the end? -
Django form not showing up
I am new to django and trying to show a form in an html file and I don't see the fields . I can see everything except the form. Task: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. views.py def index(request): entries = util.list_entries() searched = [] if request.method == "POST": form = Search(request.POST) if form.is_valid(): item = form.cleaned_data["item"] for i in entries: if item in entries: page = util.get_entry(item) page_converted = markdowner.convert(page) context = { 'page': page_converted, 'title': item, 'form': Search() } return render(request, "encyclopedia/entry.html", context) if item.lower() in i.lower(): searched.append(i) context = { 'searched': searched, 'form': Search() } return render(request, "encyclopedia/search.html", context) else: return render(request, "encyclopedia/index.html", {"form": form}) else: return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "form":Search() }) layout.html <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form method="post" action="{% url 'index' %}"> {% csrf_token %} {{form.item}} </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'create' %}">Create New Page</a> </div> <div> <a href="{% url 'random' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> -
Want to know , why when I am using django project.I cannot save html file
I want to know why when I am using python framework django in vs code.I can not save html file as html file.It is automatically converted into dj file. And also in the file html shortcut (like ! for template) is not working .Please help me -
Pass javascript output to a html <div> as a parameter
I have a m_template.html file which has a script as follow: <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: '/ajax/ajax_load_cities', data: { 'countries': countryId // add the country id to the GET parameters }, dataType: 'json', success: function (data) { // here data comes from url output or load_cities function $("#preview-items").html(data.tags); } }); }); </script> In the same template.html I defined a section like: <div id="preview-items"> {% for item in itemslist %} <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="{{ item.0 }}"> <span> {{ item.1 }} </span> </label> {% endfor %} </div> and load_cieties: def load_cities(request): .... data = { 'tags': list(cities) } return JsonResponse(data) My Question: How to pass data.tags which is a list of tuples to section as a parameter that within which I be able to style list items as I already defined in ? data.tags is something like [(id1, name1), (id2, name2), (id3, name3), ..] The problem is $("#preview-items").html(data.tags); line which rather than passing list, replaces list in the <div> so at the moment I have something like: id1name1,id2name2,id3name3,... -
Why navbar toggle doesn't toggle?
Im working on a personal project in Django, and i have a problem. I made the navbar with bootstrap but the toggle doesn't work. I have add the javascript and css from: https://getbootstrap.com/docs/4.4/getting-started/introduction/ but still doesn't work. This is my main.html {% load static %} <!DOCTYPE html> <html> <head> <title>Webart</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% include 'art/navbar.html' %} {% block content %} {% endblock %} <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> This is my navbar.html: <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Margjini-Art-Gallery</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav ml-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">About<span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Bio</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Painting </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Impresionism</a> <a class="dropdown-item" href="#">Acrylic</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item active"> <a class="nav-link disabled" href="#">Contact</a> </li> </ul> </div> </nav> <br> I dont really know where the problem is. I hope you guys … -
based on the choices selected in the model...I need to select appropriate region in class view using if_else logic
class GenerateRouterConfig(View): def get(self, request, pk, *args, **kwargs): router = Router.objects.get(pk=pk) AMERICAS = ("1.2.3.4", "10.23.136.1") ASIAPAC = ("1.2.3.5", "10.23.136.4") EMEA = ("1.2.3.6", "10.23.136.3") if router.REGIONS[1] == ('AMERICAS','AMERICAS'): calculated_public_ip = AMERICAS[0] calculated_tunnel_ip = AMERICAS[1] elif router.REGIONS[2] == ('ASIA','ASIA'): calculated_public_ip = ASIAPAC[0] calculated_tunnel_ip = ASIAPAC[1] elif router.REGIONS[0] == ('EUROPE','EUROPE'): calculated_public_ip = EMEA[0] calculated_tunnel_ip = EMEA[1] print(calculated_public_ip) print(calculated_tunnel_ip) Models.. class Router(models.Model): AsiaPac = 'ASIA' Americas = 'AMERICAS' EMEA = 'EUROPE' REGIONS = [ (EMEA, 'EUROPE'), (Americas, 'AMERICAS'), (AsiaPac, 'ASIA'), ] region = models.CharField( max_length=8, choices=REGIONS, default=Americas, ) Any hints? Based on the logic I used its not working..... Based on the if else logic I need to select the appropriate region tuples with calculated tunnel and public ip address. -
Graphene: Difference between Abstract ObjectType and Interface
I am unable to tell the difference between a graphene.Interface object and a graphene.ObjectType object with abstract = True meta class options. For example: import graphene class A(graphene.Interface): field_y = graphene.Int() field_z = graphene.String() class B(graphene.ObjectType): class Meta: abstract = True field_y = graphene.Int() field_z = graphene.String() class ChildA(graphene.ObjectType): class Meta: interfaces = (A,) field_x = graphene.Float() class ChildB(B): field_x = graphene.Float() When would I use one Child over the other? When would I not use one or the other? Any help is appreciated. -
Python django query database and get all FKs in list
I am new in django and I am working in order to implement a Rest API. My issue is with a query that I can't find a working solution no matter the number of hours spent on it. More specifically I have these two models: class Subcategory(models.Model): id = models.UUIDField(primary_key=True, editable=False, null=False, blank=False, default=uuid.uuid4) name = models.CharField(max_length=50, null=False, blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False, db_column='category') class Category(models.Model): id = models.UUIDField(primary_key=True, editable=False, null=False, blank=False, default=uuid.uuid4) name = models.CharField(max_length=50, null=False) image = models.CharField(max_length=100, default=None) As you can see each category has some subcategories and in the subcategory model I have a foreign key to the category. What i want to do is to query my database, get all categories and to each category add an extra field subcategories with a list of the subcategories. My idea it was to follow the FKs using .select_related but it seems to be a wrong solution since I am taking the following error: "message": "name 'subcategory__category' is not defined" My query is: Category.objects.all().select_related(subcategory__category).values() Any ideas on how to solve this issue and find a way to implement my query? Thank you in advance -
How do I resolve a permission error with django?
I am using Django to display my code in an html format using class based views. My code reads a log file and displays stats based on what is in there. When I try to access the log file from my computer this error message is displayed: [Errno 13] Permission denied: 'C:/Users/bhattaar/Downloads/access.log' I first tried going through the properties of the folder to make sure everything was set to read only (which it already was) and then I tried running the command prompt as an administrator and it still would not work. The line the error appears on is this: log = open('C:/Users/bhattaar/Downloads/access.log', 'r') Does anyone know how I can resolve this issue? -
How to call a function every time Django restarts?
I have a Django webservice that is hosted using Gunicorn in production. I need to call the function restart_event every time the webservice is restarted. This is the pseudo code of the function def restart_event(): """This function should be called everytime Django restarts""" # read list of registered companies from the database companies = Company.objects.all() for company in companies: # perform various operations on the data business_logic1(company) business_logic2(company) change_celery_settings() How do configure Django such that the above function is called every time Django restarts? Note that since Gunicorn is being used I won't be doing a python manage.py runserver rather I will be starting and stopping the Gunicorn webserver -
Images served on aws are not displaying on my website
Kindly help me, I have tried using aws with heroku to host my images but it has not been working for days now. The main issue is that my images are not showing on my website but are sent to my bucket whenever they are uploaded. Kindly help me please, thanks. -
Is there any way to store object in django request
Hello I am new to the Django framework and while I was building a small shopping project I faced the following problem. In the shop I wanted to make the items to be chosen but reserved when actually processed the cart and some time after processing their reservation is cleared. I did this with some database call using a custom timer class and I wanted the user to stop the timer whenever they remove the item from cart since I want to remove the reservation as well at the same time. Here is some of my code # my custom timer class class MyTimerClass(threading.Thread): def __init__(self, timewait, id, quantity): threading.Thread.__init__(self) self.event = threading.Event() self.timewait = timewait self.id_= id self.item_quan = quantity def run(self): # waits for the time(seconds) specified self.event.wait(self.timewait) # main work is done if not the stop method is called if not self.event.is_set(): user = UserModel.objects.get(id=self.usr_id) # Stored JSON list of cart items with thier id and quantity in the db :) cart = json.loads(user.cart) for item in cart: if item['id'] == self.item_id: item['quantity'] -= self.item_quan user.cart = json.dumps(cart) user.save() def stop(self): self.event.set() The user first chooses the items and then process them so that they can actually … -
Twitter / Tweepy OAuth - How to save oauth_token to verify it on callback in a REST API setup
I am writing a simple Twitter authentication flow with a REST API setup. Client side is just plain javascript/Vue code - there is no server-side rendering. This consumes a backend REST API built with Django Rest Framework, using tweepy library to wrap the Twitter API. I have the authentication working, with the following steps: User clicks a 'log in to twitter' button, which fires a call to my backend API /get-url/ API calls Twitter's get_authorization_url (using my Twitter app credentials), gets the token, and returns this redirection URL to the client Client redirects user to the Twitter URL to complete authentication On callback, client passes all params thru to backend API endpoint API gets token and secret; creates a tweepy API with user auth; and calls verify_credentials If everything worked fine, we create a user account in a Django database tied to the Twitter user, storing their token and secret; logs the user in with a JWT; and returns a 200 success with token. Front end deals with doing JWT token refreshing etc; but otherwise uses this for authentication on the rest of the API. However, there is one bit I'm stumped on: The Twitter docs suggest that in my … -
Saving PDFs to disk as they are generated with django-wkhtmltopdf
What I'm trying to implement is this: User sends query parameters from React FE microservice to the Django BE microservice. URI is something like /api/reports?startingPage=12&dataView=Region These PDFs are way too big to be generated in FE, so doing it server side Request makes its way into the view.py where the data related to dataView=Region is queried from the database, each row is iterated through and a PDF report is generated for each item Each dataView=Region can consist of a few hundred items and each of those items is its own report that can be a page long or several pages long As the reports are generated, they should be saved to the server persistent volume claim and not be sent back to FE until they have all run. When they have all run, I plan to use pypdf2 to combine all of the PDFs into one large file. At that point, the file is sent back to the FE to download. I'm only working on 1. and 3. at this point and I'm unable to: Get the files to save to storage Prevent the default behavior of the PDF being sent back to the FE after it has been generated … -
Django Model serializer returning ID
i've created the models and serializers as below serializers.py class ProductCategorySerializer(ModelSerializer): class Meta: model = ProductCategory fields = ['id', 'name'] @staticmethod def get_product_category_name(obj): return obj.product_categories.name class ProductSerializer(ModelSerializer): product_categories = ProductCategorySerializer class Meta: model = Product fields = ['id', 'name', 'default_price', 'description', 'product_categories'] models.py class ProductCategory(models.Model): class Meta: db_table = 'itw_product_category' verbose_name = 'product category' verbose_name_plural = 'product categories' name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): class Meta: db_table = 'itw_product' verbose_name = 'product' verbose_name_plural = 'products' name = models.CharField(max_length=50) default_price = models.FloatField(max_length=10) description = models.TextField(max_length=50) deleted = models.BooleanField(default=False) product_categories = models.ManyToManyField(ProductCategory, verbose_name='product_categories', related_name='products') Now, when i try to create a new model, product_categories returns only the id and not the name, what should i change? Example: { "id": 25, "name": "kms", "default_price": 932.0, "description": "kms", "product_categories": [ 5 ] } -
Flutter App using App Engine backend, contained within google cloud platform
is it possible to connect flutter app(mobile front-end) to App Engine(django backend) just using google cloud? What products would require? Thank you, much appreciated :) -
Django 'no such column' after changing spelling of attribute
I have the following classes: class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') name = models.CharField(max_length=500) phone = models.CharField(max_length=500) address = models.CharField(max_length=500) logo = models.ImageField(upload_to='restaurant_logo/', blank=False) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("name", "phone", "address", "logo") I realized I spelled address as "adress" so i changed it to "address". Now I get the error 'no such column'. I tried making migrations but it says no migration to make. How can I fix this? -
Filtering issue in DRF
The problem I'm having looks like: TypeError: init() got an unexpected keyword argument 'name' "GET /apartmentimages/ HTTP/1.1" 500 136691 I have such a model.py class: class Apartment(models.Model): apartment_title = models.CharField(max_length=200) apartment_description = models.TextField() apartment_location = models.CharField(max_length=200) apartment_people_quantity = models.PositiveIntegerField() apartment_price = models.CharField(max_length=200) apartment_type = models.CharField(max_length=50, null=True) def __str__(self): return self.apartment_title class ApartmentImage(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', null=True, blank=True) And serializers.py class: class ApartmentSerializer(serializers.ModelSerializer): class Meta: model = Apartment fields = ( 'id', 'url', 'apartment_title', 'apartment_description', 'apartment_location', 'apartment_people_quantity', 'apartment_price', 'apartment_type', ) class ApartmentImageSerializer(serializers.ModelSerializer): class Meta: model = ApartmentImage fields = ('id', 'url', 'apartment', 'image',) in views.py: apartment_id = django_filters.CharFilter(name="apartment__id", queryset=Apartment.objects.all()) class Meta: model = ApartmentImage fields = ('apartment_id',) class ApartmentImageView(viewsets.ModelViewSet): queryset = ApartmentImage.objects.all() serializer_class = ApartmentImageSerializer filter_backends = (DjangoFilterBackend,) filter_class = ApartmentImageFilter -
Sorting release versions of the format YYYY.MM.DD in a Django queryset
I have a Django model that looks like this: from django.db import models from distutils.version import LooseVersion # Create your models here. class ReleaseNotes(models.Model): version = models.CharField(max_length=64, db_index=True, help_text="Version/Release") status = models.CharField(max_length=64, blank=True, null=True, help_text="Status") release_date = models.DateField(blank=True, null=True, help_text="Release Date") description = models.TextField(blank=True, null=True, help_text="Description") def description_to_bullet_points(self): return self.description.split('\n') def release_notes_list(self): qs = ReleaseNotes.objects.order_by('-version') return sorted(qs, key=lambda qs:LooseVersion(qs.version)) def __str__(self): return self.version And I display the "release notes" with this template: {% if release_notes_list %} <ul> {% for release_note in release_notes_list %} <p><b>{{ release_note.version }}</b><br> {% for bullet_pt in release_note.description_to_bullet_points %} <br>{{ bullet_pt }} {% endfor %} </p> {% endfor %} </ul> {% else %} <p>No release notes are available.</p> {% endif %} I want to display the "release notes" with the newest release note on top. But I have versions of the format YYYY.MM.DD so the version 2020.11.1 does not show up on top. The version come out in this order: 2020.8.1 2020.7.1 2020.6.2 2020.6.1 2020.5.4 2020.5.3 2020.5.2 2020.5.1 2020.4.4 2020.4.3 2020.4.2 2020.4.1 2020.2.6 2020.2.5 2020.2.4 2020.2.3 2020.2.2 2020.2.1 2020.11.1 2020.1.4 2020.1.3 2020.1.2 2020.1.1 -
SSL context override vulnerability on Django-rest serializer
I have HCL AppScan CodeSweep installed on VScode and it picked up an SSL context vulnerability on one of my Django serializers and I was just wondering I can go about fixing it without changing my desired functionality. class CategoryDetailSerializer(CategoryListSerializer): products = serializers.SerializerMethodField() class Meta: model = Category fields = ( 'id', 'title', 'products', ) def get_products(self, obj): # The source of the SSL context override return ProductListSerializer(obj.product_set.all(), many=True, context=self.context).data -
I keep getting the error "ModuleNotFoundError: No module named 'environ' in my settings.py file". I have installed the dependency in my python shell
I keep getting an import error on environ in my settings.py file, I have it installed via poetry in my .venv file as well. Could this be an error outside the settings file possibly? ` import environ env = environ.Env( DEBUG=(bool, False), ENVIORNMENT=(str, 'PRODUCTION'), ) environ.Env.read_env() ENVIRONMENT= env.str('ENVIRONMENT') SECRET_KEY = env.str('SECRET_KEY') DEBUG = env.bool('DEBUG') ALLOWED_HOSTS = tuple(env.list('ALLOWED_HOSTS')) `