Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Database service dependency not working properly in docker-compose
I am building a webapp in Django. I want to use Postgres instead of default sqlite and wanted to achieve this using docker-compose. Here is my docker-compose file. I expect postgres to spin up before my app but unfortunately this does not happen. Whenever I try to run the docker-compose up command, my webapp starts building first and eventually gives me an error of the database connectivity which is also attached. version: '3.7' networks: metagov_network: services: policykit_app: container_name: policykit restart: always build: context: . dockerfile: Dockerfile args: POSTGRES_DB: metagov POSTGRES_HOST: database POSTGRES_USER: postgres POSTGRES_PASSWORD: supersecretpassword ports: - "8081:8080" depends_on: - database networks: - metagov_network database: image: postgres:alpine restart: always environment: - "POSTGRES_DB=metagov" - "POSTGRES_USER=postgres" - "POSTGRES_PASSWORD=supersecretpassword" ports: - "5432:5432" networks: - metagov_network volumes: - metagov-storage:/var/lib/postgresql/data volumes: metagov-storage: I run the command: docker-compose up --build -d --force-recreate My Dockerfile looks like this: FROM ubuntu WORKDIR metagov RUN apt install postgresql-client -y RUN apt install python3-pip -y COPY policykit metagov RUN pip3 install --no-cache-dir -r metagov/requirements.txt EXPOSE 8000 ARG POSTGRES_DB ARG POSTGRES_HOST ARG POSTGRES_USER ARG POSTGRES_PASSWORD RUN python3 metagov/manage.py makemigrations RUN python3 metagov/manage.py migrate ENTRYPOINT ["python3"] CMD ["metagov/manage.py", "runserver", "0.0.0.0:8000"] And this is the error I get: django.db.utils.OperationalError: could not translate host … -
Is it possible to add Google Maps markers of locations read from a file in Django?
I'm developing a Django project and I'm trying to render a map that contains several markers of different locations. I want to read these locations from a file, but up till now I used JS and HTML to render a map that contains a single marker on it. Here is the JS code: function initMap() { const uluru = { lat: 0.0018211100000000001, lng: 0.009671981000000001 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); const marker = new google.maps.Marker({ position: uluru, map: map, title: "Turbine 7", }); } and the HTML code is a only a div that contains the position of the map inside of it: <div id="map"></div> and here is a picture of the final output: -
How to print all the Routes used in Django?
I want to display all the Routes in an app built with Django, something like what Laravel does with the command: php artisan route:list Is there a way to get all the Routes? -
How to use the for range loop in django admin?
I need something like forloop.counter in templates. Is this possible? -
Django - second trigger of htmx tries to load an unexpected URL gives a 403 error
I have a table of cells, each with a different object instance, and using htmx to update the objects. I've created a CBV that takes the request.post from the htmx and saves the modified object to the db. The htmx does a hx-swap and loads a new <input> tag into my form, along with some background-color style based on the saved object. I can click on many cells and update several objects this way. This is working as expected and I don't see any errors. However, the second time that I try to update the same cell/object, I get a 403 error. This error does not show in the browser. The cell just seems unresponsive. I can continue updating other cells. The error shows up in my browser console. views asessmentdetail - view that loads template and retrieves all the objects to fill in the table def assessmentdetail(request, assess_pk, class_pk): """List the current grades for the assessment""" user = request.user assessment = Assessment.objects.get(id=assess_pk) classblock = Classroom.objects.get(id=class_pk) course_pk = classblock.course.pk objective_list = Objective.objects.all().filter( assessment=assess_pk).order_by('objective_name') student_list = Student.objects.all().filter( classroom=class_pk).order_by('nickname') gra = Grade.objects.filter( assessment=assess_pk).filter(cblock=classblock.id) context = {'objective_list': objective_list} new_or_update = gra.exists() grade_report = [str(new_or_update)] grade_list = [] grade_id_array = [] grade_report.append(len(objective_list)) # print(len(objective_list)) … -
how do I update fields in django
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(max_length=80) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) dob = forms.DateField() address = forms.CharField(max_length=100) city = forms.CharField(max_length=30) country = forms.CharField(max_length=30) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'dob', 'address' , 'city' , 'country' , 'password1', 'password2'] this is my code in forms.py It is used to create a profile. when I added new fields they show when creating the user but when I try to sow them on a profile page only a couple show. <div class="media-body"> <h2 class="account-heading">{{user.profile}}</h2> <p class="text-secondary">{{user.first_name}}</a> {{user.last_name}}</p> <p class="text-secondary">{{user.dob}}</p> <p class="text-secondary">{{user.email}}</p> <p class="text-secondary">{{user.address}}</p> <p class="text-secondary">{{user.city}}</p> <p class="text-secondary">{{user.country}}</p> </div> this is my code from my profile page but when I go onto my site it only shows the fields I created at the start before adding more later. -
Function doesn't update in asyncio
I'm writing a bot in aiogram with a backend on django for postgresql (had the same issue before converting from pure psycopg2). One of the finite states I'm in, should constantly check for updates in the DB, except it doesn't happen. Here's the code for the loop in bot: @dp.message_handler(state=Current.start_state) async def func(msg: types.Message, state: FSMContext): async def res(): return await function(args) global ticket ticket = await res() while ticket == -1: ticket = await res() if ticket == -1: await asyncio.sleep(3) print(ticket) #debugging I've tried it without the function: @dp.message_handler(state=Current.start_state) async def func(msg: types.Message, state: FSMContext): global ticket ticket = await function(args) while ticket == -1: ticket = await function(args) if ticket == -1: await asyncio.sleep(3) print(ticket ) And many other combinations, including making the loop condition while = True and having a break in the loop for when the condition is met. And I can insure you, the results change, I can see that in pgAdmin4 and by running this function separately in another script while the bot is running. It seems to work sometimes if I manually change the information in DB, and even then, not always. Basically, whilst this loop is running for user A, another … -
Displaying messages through django signals
I'm looking to make a django app that uses signals. (using django signals) There I would like to run some functions, and based on which output they give, send a message within the webpage. so for example, if the function fails i want to send a message saying it failed. this is pretty much want i would want in signals.py ----- def handle_event(request, *args, **kwargs): try: --unimportant-- except: messages.error(request, 'error message') post_save.connect(handle_event, sender=Event) how would i go about doing this? -
How to enable console scripts in Django?
Running Python 3.6 on Redhat. I've installed an extremely complicated project. 5 engineers worked on this for years, but they are all gone now, so I've no one to ask. At the top level of the project: setup.py Inside of that: # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'blueflow-connector-aims = app.connectors.aims.__main__:cli', 'blueflow-connector-csv = app.connectors.csv.__main__:cli', 'blueflow-connector-discovery = app.connectors.discovery.__main__:cli', 'blueflow-connector-fingerprint = app.connectors.fingerprint.__main__:cli', 'blueflow-connector-mock = app.connectors.mock.__main__:cli', 'blueflow-connector-nessusimport = app.connectors.nessusimport.nessusimport:cli', 'blueflow-connector-netflow = app.connectors.netflow.__main__:cli', 'blueflow-connector-passwords = app.connectors.passwords.__main__:cli', 'blueflow-connector-portscan = app.connectors.portscan.__main__:cli', 'blueflow-connector-pulse = app.connectors.pulse.pulse:cli', 'blueflow-connector-qualysimport = app.connectors.qualysimport.qualysimport:cli', 'blueflow-connector-sleep = app.connectors.sleep.__main__:cli', 'blueflow-connector-splunk = app.connectors.splunk.__main__:cli', 'blueflow-connector-tms = app.connectors.tms.__main__:cli', ] }, I ran: pipenv shell to create a shell. If I try a console script: blueflow-connector-mock I get: bash: blueflow-connector-mock: command not found That goes to bash which is clearly a mistake. I also tried: python3 blueflow-connector-mock which gives me: python3: can't open file 'blueflow-connector-mock': [Errno 2] No such file or directory How do I activate these console scripts, so they will actually run? -
wagtail can't add ckeditor to blocks
I'm using wagtail and trying to use ckeditor inside blocks but seems not working the field with ckeditor not showing in admin when I try to create or edit a page I want to use ckeditor because I can use the option source to insert div and class inside text my code for blocks is : from ckeditor.fields import RichTextField class widgetBodyBlock(blocks.StructBlock): heading = blocks.CharBlock(required=False, label=_('Heading')) text = RichTextField(null=True, blank=True) image = ImageChooserBlock() class Meta: template = '_template/blocks/body_block.html' icon = 'edit' label = _('Widget Body') but in admin the field not showing like in picture it's show only heading and image -
What is the best way to include apps in INSTALLED_APPS, Django
We can add apps in settings.py like, let suppose my app name is myapp INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.AppConfig' #OR 'myapp' ] I just want know to what is the difference between them? I found myapp.apps.AppConfigis a good practice but why? And how can i do this in __init__.py file? -
How do I filter date in react component
I am using the Django rest framework to create API and it is returning 2022-03-04T05:16:07.552250Z this data how do I filter only date from this data. -
Django Modals Validation Errors
Looked a lot into a solution of my issue but didn't get it right. I want to show the errors in the Modal form and don't close until it is valid. For now I am able to get the errors in the customer.html page after the Modal closes. Forms.py class CustomerForm(forms.ModelForm): //...... Form Widget HERE ......//// class Meta: model = Customer fields =['customername','customerlogo','emailaddress','addressLine1','membership','pobox','phonenumber','emailaddress'] Views.py def customer(request): context = {} customers = Customer.objects.all() context['customers'] = customers if request.method == 'GET': form = CustomerForm() context['form'] = form return render(request, 'Mainapp/customer.html', context) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'New Client Added') return redirect('customer') else: messages.error(request, form.errors) return redirect('customer') return render(request, 'Mainapp/customer.html', context) HTML MODAL. <div id="create-modal" data-backdrop="static" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Customer Details</h4> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body p-4" data-backdrop="static"> <div id="error"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert-dismissible alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} </div> <form action="#" action="Mainapp/customer.html" id="customerfrm" method="POST"> <!-- onsubmit="submitForm(event)"--> {% csrf_token %} <div class="row"> <div class="col-lg-9"> <div class="mb-3"> <label for="customername" class="form-label">Customer Name<span … -
How to filter in Django Rest Framework function based view?
So many documentation for filtering in Django rest framework but all the examples are in class based view. but I am trying to do the same in DRF function based view. I wanted to do multiple filter for my items queryset. I tried one way and it is working perfectly. Here first I am trying to search by item name or restaurant name in one request. then I take another keyword and try to filter restaurant name or item name based on restaurant city. It is working perfectly like if I hit this url http://localhost:8000/api/items/?keyword=lasagne&keyword1=paris then it gives me the perfect response. But What I am asking for is that now my code looks for this specific part is messy and I want to add more fields for multiple filtering. Which procedure to follow? Should I follow this one and multiple requests and trying to filter from this. Suppose now I want to filter the queryset based on dish_type, price, item_type, location and then search for items by name or restaurants by name #this is my models class Restaurant(models.Model): user = models.OneToOneField(CustomUser, related_name='restaurant', on_delete=models.CASCADE, null=False) name = models.CharField(max_length=200, blank=True, null=True) profile_picture = models.ImageField(null=True, blank=True) address = models.TextField(max_length=2000, blank=True, null=True) city … -
How to render a data frame from views.py to an html template in django?
I'm building a webapp with Django, and one of the features is that the user can upload a dataset and view it on another page. I'm currently only attempting to read a dataset from a file path and display it in another page; I've placed my test.csv in the file that I want to read from, but I keep getting the error 'list' object has no attribute 'to html'. Here is the views.py: path = r"C:/Users/user/Documents/django_saved_files/" path1, dirs, files = next(os.walk(path)) file_count = len(files) dataframes_list = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) dataframes_list.append(temp_df) dataframes_list_html = dataframes_list.to_html(index=False) return render(request,'blog/view_datasets.html',{'Dataframe':dataframes_list_html}) and Here is the HTML Template: <body> <div class="container"> <h1 class="section-header">Datasets Available</h1><hr> <div class="content-section"> Output: {{Dataframe|safe}} </div> </div> </body> -
Django Authentication system modifications
I am new to Django Authentication system and I am unable to find the correct debugging method. I want to create a function to handle login requests and I have done the necessary steps to do the same. created a login url path in main project URLS.py file. path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), created a login url in members app to point to a function created in views.py urlpatterns = [ path('login/', views.login_user, name='login'),] defined what to do when user comes to specific url def login_user(request): if request.method == 'POST': print('-'*100) username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You are now logged in")) return redirect('index') else: messages.success(request, ("Invalid credentials")) return redirect('login') return render(request, 'registration/Login.html') I have created a Login Page in templates folder. {% extends 'Base.html'%} {% block title %} Login to the Blog Page {% endblock %} {% block content%} <h1>Members Login</h1> <div class="form-group"> <form method="POST" action=""> {% csrf_token %} <div class="mb-3"> <label for="exampleInputEmail1" class="form-label">User Name</label> <input type="text" class="form-control" name = "username"> <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> <button type="submit" class="btn btn-primary">Login</button> </form> … -
Django-Vue get_absolute url error on template
I am trying to route my Vue home page to the detail page of the specific product with its url when the button is clicked on. Though my django and vue servers run fine. I get this error in chrome. Chrome error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'get_absolute_url') at Proxy.render (HomeView.vue?43d0:14:1) at renderComponentRoot (runtime-core.esm-bundler.js?d2dd:893:1) ... The error only shows up when I add the router link tag with the product.get_absolute_url method. When I take it off, the product items (latestProducts) render fine. HomeView.vue <template> <div class="home"> <div class="product-container"> <div class="product-item" v-for="product in latestProducts" :key="product.id" > <img class="prod-img" :src="product.get_image" alt="" /> <h2>{{ product.name }}</h2> <p>{{ product.price }}</p> </div> <div> <router-link v-bind:to="product.get_absolute_url" ><button>View Item</button></router-link > </div> </div> <router-view /> </div> </template> Here is my models.py file where the get_absolute_url model is defined. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug} / {self.slug }/' I have read the django docs that suggest using the reverse() function and the viewname … -
is there a way i can autofill a form in django forms
i am trying to get data to be autofilled that i am getting from a code generator . so without needing a user to fill it in i want it to be already filled from django.utils.crypto import get_random_string unique_id = get_random_string(length=32) class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class Bybitapidata(ModelForm): class Meta: model = Bybitapidatas fields = ('apikey','apisecret','sectoken') widgets = { 'apikey': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Bybit Api Key' }), 'apisecret': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Bybit Api Secret' }), 'sectoken': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Please enter a 12 Digit token'#here i want to automatically give 12 digits that is being generated }) } -
Permission error when i try to write KML files in django + ubuntu + apache
I'm Using the SimpleKML pip package to be able to create kml and kmz file from some cords I have in my database Here is my code : @permission_classes(["IsAuthenticated"]) @api_view(['POST']) def add_cords_to_breach(request): data = {} if request.method == 'POST': # try: breach_id = request.data['breach_id'] breach_object = models.Breach.objects.get(id=breach_id) cords = request.data['cords'] kml = simplekml.Kml() for item in cords: new_cord = models.BreachCords.objects.create( latlng=item, breach=breach_object) theLat = float(item.split(",")[0]) theLng = float(item.split(",")[1]) kml.newpoint(name=item.split(",")[0], coords=[(theLat,theLng)]) print(kml.kml()) theDIR =os.path.join(BASE_DIR,f'kml_files/') kml.save(f'{theDIR}{breach_id}.kml') kml.savekmz(f'{theDIR}{breach_id}.kml') data = {"success": True, } return Response(data, headers=get_headers()) the data are being processed perfectly and when I print the output using print(kml.kml()) the out as XML is perfectly printed. but when it comes to the line of saving I get this error PermissionError: [Errno 13] Permission denied: '...(full_path_shown_here)../kml_files/253.kml' -
Django template - combining a loop within a loop and sorting by date
I have an array called Events. Within the Events array I have another array called Recurrences, using the Django-Recurrences library. I get the events context from my view as well as today's date and an end date: context['events'] = PartnerEvents.objects.filter(partner=context['partner']) context['today'] = datetime.combine(timezone.now().date(), time(0, 0)) context['end'] = context['today'] + timedelta(days=21) return context I then loop it out in my template as follows. {% for e in events %} {% for ts in e.recurrences.occurrences %} {% if ts >= today and ts <= end %} <p>{{ts|date:'d F'}}</p> {% endif %} {% endfor %} {% endfor %} It would then display all the events and occurrences, that will take place today and the next 21 days, eg 05 March 07 March 08 March 09 March 10 March 11 March 12 March 14 March 15 March 16 March 17 March 18 March 19 March 21 March 22 March 23 March 24 March 25 March 05 March 12 March 19 March However, since certain 'partners' can have more than 1 event on a day, it's causing the the other event to only be looped after the specific event. As you'll notice 05 March, 12 March, 19 March which is another "event" only occurring on … -
The Python spacy module not working on Apache
I have a Django application running on Apache24 in Windows. I am using Python 3.9.5. The application works fine. But after installing the spacy module and importing it on a Python file as follows, import spacy the application is hanging and the Apache no longer responses. The spacy module works fine with Django's server (python manage.py runserver) My settings are fine. But in case you wonder, here are some of them. In the settings.py file: ALLOWED_HOSTS = ['localhost'] In the C:\Apache24\conf\httpd.conf file WSGIApplicationGroup %{GLOBAL} LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIScriptAlias / "C:/Users/Administrator/Documents/myproject/myproject/wsgi.py" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" WSGIPythonPath "C:/Users/Administrator/Documents/myproject/" Alias /static C:/Users/Administrator/Documents/myproject/static <Directory C:/Users/Administrator/Documents/myproject/static> Require all granted </Directory> <Directory C:/Users/Administrator/Documents/myproject/myproject/> <Files wsgi.py> Require all granted </Files> </Directory> Any idea why the spacy module doesn't work on the Apache server and how to fix it? -
Mark_safe not render html
Trying to generate a thumbnail for preview, the imgtag is not render. I see so many questions about that, and try various solutions unsuccessful. admin.py class AdminProductImages(admin.TabularInline): model = ProductImages form = ProductImagesForm extra = 3 max_num = 3 def image_tag(self, obj): return mark_safe('<img src="%s" style="width:150px;height:150px;"/>') % (obj.image_file_w200_png.url) image_tag.short_description = 'xImage' image_tag.allow_tags = True fields = ( 'image_file_w200_png','image_tag', ) readonly_fields = ('image_tag',) list_display =('image_file_w200_png','image_tag') """ fieldsets = ( (None, {'fields': ('image_file_w200_png',)}), ) """ add_fieldsets = ( (None, { 'fields': ('image_file_w200_png',), }), ) class Media: js = ('js/img_product_upload.js',) models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file_w200_png = models.ImageField( upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) #... forms.py class ProductImagesForm(ModelForm): image_file_w200_png = forms.FileField(widget=forms.ClearableFileInput( attrs={ 'class': 'image_add_product' } )) class Meta: model = ProductImages fields = ['image_file_w200_png',] After days, can't found the mistake, yet... Some tips are welcome. Django 4.0 -
Getting related models in template
I've got two models. I'm attempted to get a qs of jobs for a given review within my template Models.py class Job(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) cart = models.ForeignKey(Cart, related_name="cartmodel", on_delete=models.CASCADE, null=True, blank=True) class Review(models.Model) cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) views.py reviews = Review.objects.all() template {% for review in reviews %} {% for i in review.cart.job_set.all %} {{i.employee}} {% endfor %} {% endfor %} The code in my template isn't working. Any thoughts how to correctly build this set in my template ? Thanks! -
Why is Permission table populated in test database, while others aren't (django python)?
While playing around with django testing I noticed that Permission table in test database is not empty (like, for example, User and tables of models defined by me) - it has all permissions from the real table. My questions: Is the Permission table the only prepopulated table? (I have trouble inspecting other tables, because db is in-memory) Where is it prepopulated (I also couldn't find)? Upon setting up test suit? Or just before executing each test method? Or maybe added to queryset everytime it is requested? -
Python Django objects.filter() queries
Hi I do not know how can i use filter to get a category of item inside my DB table. This is my table for your reference. My index is a Menu page with 4 of the foods, then I am trying to create each sub page according to the category and filter to show the food from the category only.