Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to use Django's static method in a CSS rule?
I am trying to use background-image css rule for a django template. I am unable to use static mode with the image url. Is there a solution or work-around for this? Here's what I have tried to do: .hero-landing { background: linear-gradient( rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7) ), url('{% static 'img/people_4.jpeg' %}'); background-size: cover; background-position: center; background-attachment: fixed; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 0 100px; color: #fff; } I can't get the url to work. -
django update statement not updating database as expected
I have django framework code where I am updating my database with simple found or not found on a condition where if cdr_number is equel to aparty variable update the database found if not update it with not found. but somehow even cdr_number is equal to aparty variable my code is still not updating the database with found although my if condition is working properly all the print statements and other operations are working. I have shared my print statements also for reference. please someone help on this thanks. for index,cdr_number in enumerate(cdr_numbers): # Read the CSV file # tests = reqData.objects.filter(data_id = data_ids[index]) test = temp_cdr_number[index].rec_data if str(aparty) == cdr_number: print(f"{aparty} FOUND") # print(f"{temp_cdr_number[index].data_id} {temp_cdr_number[index].req_data}") # COPY CDR TO CDRS FOLDER os.system(f"cp {file_path}{xlsx_file} cdrs/92{xlsx_file[:10]}-{data_ids[index]}.xlsx") # UPDATE DATA IN REQ_DATA TABLE # reqData.objects.filter(data_id=data_ids[index]).update(rec_data=f"{test}-{index}") print(reqData.objects.filter(data_id=data_ids[index]).update(rec_data=f"Found").query) # print(f"found updated {result}") # print(f"data_id : {data_ids[index]}") # RENAME FILE TO GLOBAL CSV os.rename(f'{file_path}{xlsx_file}',f"{file_path}global_csv.csv") # SAVE CDR INTO DATABASE # os.system("mysql -u root -p12341234 --execute='TRUNCATE ACCESS.global_csv;'") # os.system("mysql -u root -p12341234 --execute='SET GLOBAL local_infile=1;'") # os.system(f"mysqlimport -u root -p12341234 --local --fields-terminated-by=',' ACCESS {file_path}global_csv.csv") # os.system(f"mysql -u root -p12341234 --execute='CALL `ACCESS`.`ufone_imei_response`({req_id});'") # MOB IMEI RESPONSE MYSQL STORE PROCEDURE break else: print(f"not found {aparty}") # print(f"{cdr_number} not … -
I'm getting this error: ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiService -> _ApiService -> _HttpClient -> _HttpClient]
I have configured my ApiService with the HTTPClient and HttpHeaders and I am also using an Angular dependency injection to provide the HttpClient. But I kept encountering the same errors. I've already checked that the BrowserModule, AppRoutingModule and HttpClientModule imports were imported correctly and everything appears to be ok. Error Picture: ERROR: NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiService -> _ApiService -> _HttpClient -> _HttpClient]: My api.service.ts file: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseUrl = 'http://localhost:8000/'; httpHeaders = new HttpHeaders({'Content-Type': 'application/json'}); constructor(private http: HttpClient) { } getAllMembers() : Observable<any> { return this.http.get(this.baseUrl + 'members/', {headers: this.httpHeaders} ); }; } My app-routing.module.ts file: import { NgModule } from "@angular/core"; import { Routes, RouterModule } from '@angular/router'; import { MembersDetailComponent } from './members-detail/members-detail.component'; import { NewMemberComponent } from './new-member/new-member.component'; const routes: Routes = [ { path: 'member-detail/:id', component: MembersDetailComponent}, { path: 'new-member', component: NewMemberComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [ MembersDetailComponent, ] My app.module.ts file: import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppRoutingModule } from './app-routing.module'; import … -
What is difference between Celery Beats, Celery worker, Threads and Multiprocessors?
What is the difference between:- Celery beats and Celery Worker, and if Celery worker works just like threads or multiprocessors, why do we use celery worker especially? Thank you. I tried working with threads and Celery worker but found that threads is more clear and simple. -
Why is my Aleart Message not appearing after the user login wasn't correct? Django, html, css
This is the Script in my signIn.html {% if messg %} <script> aleart("{{messg}}"); </script> {% endif %} This is my Django View def postsign(request): email = request.POST.get("email") passw = request.POST.get("pass") try: user = auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials - try again" return render(request, "signIn.html", {"messg":message}) print(user) return render(request, "welcome.html", {"e":email}) def signIn(request): return render(request, "signIn.html") I was expecting an Aleart message on my screen that the Login was not correct. -
My Django models are saved, but the ImageField is not
I am using two classes to abstract the user in my system: the Django default User and my class Documentador. I treat them both as one on the interface side, and for creating a User and Documentador couple i use a Form passed to the template and deal with the data on the View to create and save both the models. My problem is: both models are saved without any errors, but the image in the Documentador class is not. I tried to create a Documentador model with an image in the Django admin, and it works. I also tested the fields that way: if not form.cleaned_data['foto']: return HttpResponseRedirect('/controle') and i was redirected to that path. I suppose is something with the form or the view, but can't find what. Form: class DocumentadorForm(forms.Form): foto = forms.ImageField(required=False) username = forms.CharField(label="Nome de usuário", max_length="20") first_name = forms.CharField(label="Primeiro nome", max_length="30") last_name = forms.CharField(label="Sobrenome", max_length="30") email = forms.EmailField() matricula = forms.IntegerField() password = forms.CharField(widget=forms.PasswordInput) my View: class UsuarioDocumentadorCreate(View): def get(self, request, *args, **kwargs): return render(request, 'mmrn/controle/crud_documentador/c_documentador.html', {'form':DocumentadorForm()} ) def post(self, request, *args, **kwargs): form = DocumentadorForm(request.POST, request.FILES) if form.is_valid(): f_foto = form.cleaned_data['foto'] f_username = form.cleaned_data['username'] f_first_name = form.cleaned_data['first_name'] f_last_name = form.cleaned_data['last_name'] f_email = form.cleaned_data['email'] … -
Can't render a plotly chart when using fetch
I have a chart that renders fine when loading the whole page, but if I use fetch to update data it doesn't render: Here are my views: def analytics(request): data = get_chart(60) context = { 'chart': data['chart'], } return render(request, 'app/analytics.html', context) def get_chart(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': data = get_chart(int(request.GET.get('interval'))) return JsonResponse({'chart': data['chart'], }) return JsonResponse({'status': 'Invalid request'}, status=400) else: return HttpResponseBadRequest('Invalid request') Here's template: <div class="row justify-content-start mb-2"> <div class="col"><a href="javascript:;" class="chart_scale" data-foo="1">1m</a></div> <div class="col"><a href="javascript:;" class="chart_scale" data-foo="60">1h</a></div> </div> <div class="row bg-light p-3 rounded justify-content-center align-items-center" id="chart"> {{chart|safe}} </div> <script type="text/javascript"> var chart = document.getElementById('chart') const chart_scales = document.getElementsByClassName('chart_scale') for (const button of chart_scales) { button.addEventListener('click', function (e) { url = '/analytics/update/?interval=' + e.target.dataset.foo fetch(url, { method: "GET", headers: { "X-Requested-With": "XMLHttpRequest", }, }) .then(response => response.json()) .then(data => { console.log(data['chart']) chart.innerHTML = data['chart'] }) }) } </script> I get the data both times, it's length is the same, but if I inspect the element after the fetch update I get empty div: <div id="my_chart" class="plotly-graph-div" style="height:768px; width:1024px;"></div> What am I missing? UPDATE The console output looks like this: Does the fact that half of it is red mean anything? -
How do you add viewflow to an existing django application
I have installed django-viewflow as per documentation. I have modified settings to add viewflow module. The workflow section of my admin pages has the process and tasks for viewflow. That is as far as I got. There is no viewflow.urls to include in my site.urls. I asked in the github discussion but the only reply was "just add the viewsets to your existing url configuration" but the example is their uquickstart demo and that was not helpful as the "demo" was empty. mysite.urls has from viewflow.contrib.auth import AuthViewset from viewflow.urls import Application, Site, ModelViewset ... vfsite = Site(title="Katacan", viewsets=[ Application( title='KTConnector', icon='people', app_name='KTConnector', viewsets=[ ModelViewset(model=User), ] ), ]) ... path('accounts/', AuthViewset(with_profile_view=False).urls), path('vf', vfsite.urls), I just need a little help on how to finish the install into my existing application. I feel that I am close but still no banana. Thanks MO -
Django with AWS S3, Debug False not working in production
I am using Django 4.2.5. I have deployed projects using Nginx, Docker, and AWS S3 before.But now, when Debug is True, there are no issues with AWS S3, but when Debug is set to False, CSS is not working. GET https://bucketname.s3-us-west-1.amazonaws.com/static/CACHE/css/output.bdb8c01056f5.css net::ERR_ABORTED 404 (Not Found) https://events.launchdarkly.com/events/bulk/88120c8d0102a7 net::ERR_BLOCKED_BY_CLIENT "This XML File Does Not Have Style Information" <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Key>static/CACHE/css/output.bdb8c01056f5.css</Key> <RequestId></RequestId> <HostId></HostId> </Error> I have configured the AWS S3 bucket policy, CORS, and made the necessary adjustments. I even created a new bucket and ran collectstatic with Debug set to False, but the issue persists. Any insights or solutions would be greatly appreciated.Thank you! AWS_S3_GZIP = True STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY =os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_FILE_OVERWRITE=False AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = False AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles") STATICFILES_DIRS = ( os.path.join(BASE_DIR,"static"), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) FILE_UPLOAD_HANDLERS = [ 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ] -
Iterate through a list and create a html element for every item in the list?
I have a Model(Objectives) which stores the data I want to iterate through. Here is its code in the models.py class Objectives(models.Model): target = models.CharField(max_length=50) description = models.TextField(max_length=300) time_left= models.DateField() gamemodes= models.ForeignKey(User, on_delete=models.CASCADE) Here is my View.py for it. """@login_required""" def user_obj(request): modes_avalable = Task.objects.filter(gamemodes=request.user) print("__________________________________________________________") print(modes_avalable ) # Add this line for debugging return render(request, 'modes_avalable .html', {'modes_avalable ': modes_avalable }) and here is the html I have to iterate through the list: <div class="Q3" > {% for ab in user_obj%} <div class="task-item"> <h3>{{ ab.target }}</h3> <p>{{ ab.description }}</p> <p>Due Date: {{ ab.time_left|date:"F j, Y" }}</p> </div> {% endfor %} Essentially I need it to create a task-item for every objective, I have 4 objectives on the computer for testing so there is something to test on. I also have a user_obj.html file which has essentially the same code as the html code avove. -
Django: Duplicate action when I press Follow or Unfollow button
I am doing CS50w project4 problem, so I have to build a Social Media app. This problem has a part where in the profile of the user a follow and unfollow button has to be available. My problem is when I press the follow or unfollow button, this increase or decrease the followers and the people that the user follow. views.py def seguir(request): if request.method == 'POST': accion = request.POST.get('accion') usuario_accion = request.POST.get('usuario') usuario = request.user.username # Comprobación de si ya lo esta siguiendo y recuperación de información de usuarios perfil_usuario = User.objects.get(username=usuario) perfil_usuario_accion = User.objects.get(username=usuario_accion) esta_siguiendo = perfil_usuario.seguidos.filter(username=usuario_accion).exists() if accion == 'follow': # Si no lo esta siguiendo se añade a la lista de seguidos de uno y de seguidores del otro if esta_siguiendo == False: perfil_usuario_accion.seguidores.add(perfil_usuario) perfil_usuario.seguidos.add(perfil_usuario_accion) # Redirección a la página del usuario seguido return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) else: # Comprobación de que lo siga if esta_siguiendo: perfil_usuario.seguidos.remove(perfil_usuario_accion) perfil_usuario_accion.seguidores.remove(perfil_usuario) return render(request, "network/profile.html", { "profile_user": perfil_usuario_accion, "logged_user": 0 }) profile.html {% extends "network/layout.html" %} {% block body %} <h1 id="titulo-perfil">{{ profile_user.username }} profile page</h1> <div id="contenedor-seguir"> <div id="seguidores">Followers: {{ profile_user.seguidores.count }}</div> <div id="seguidos">Following: {{ profile_user.seguidos.count }}</div> </div> {% if logged_user == 0 %} … -
Trouble Activating Conda Environment in Dockerized Django Application
I'm working on Dockerizing a Django application with a Conda environment, but I'm encountering issues. The issue is that when I run docker compose up my Django application does not start properly and hangs on system check. This is my DockerFile setup: # Use an official Python runtime as a parent image FROM continuumio/miniconda3 # Set the working directory to /webapp WORKDIR /webapp # Copy the conda environment file to the container COPY webapp/my_env.yml . # Create the conda environment RUN conda env create -f my_env.yml # Create the conda environment SHELL ["conda", "run", "-n", "my_env", "/bin/bash", "-c"] # Copy the current directory contents into the container at webapp COPY webapp . # List the contents of the directory RUN conda run -n my_env ls # Make port 8000 available to the world outside this container EXPOSE 8000 # Run the Django development server ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "my_env", "python", "manage.py", "runserver"] My docker-compose.yml: version: "3" services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_DB: webapp_connect POSTGRES_PASSWORD: tcatca124 volumes: - pgdata:/var/lib/postgresql/data webapp: build: context: . dockerfile: Dockerfile # Replace with the actual path to your Dockerfile ports: - "8000:8000" depends_on: - db volumes: pgdata: And this is a snippet from … -
<select> returning empty if the value isn't edited
So, I am working on an ticket system using Html, Css, JavaScript and Django, and I needed an field that changed depending on another field, after some searching I found a good JavaScript implementation to my case and it worked perfectly on the ticket creation part, but as I was doing the ticket editing part I got stuck with a problem, if there is no changes on the <select> field it simply gets an blank value instead of the value it was previously holding, changing the value works just fine but not changing it doesn't, I can't think of a way of preventing this yet and would like to ask if anyone has dealt with an similar problem that could help me. verticket.html(form part) <form name="form-ticket" id="formTicket" method="POST" action="{% url 'eticket' ticket.pk %}"> <div class="col-4 mt-4 m-auto"> {% if msg %} <div class="alert {{class}}"> {{msg}} </div> {% endif %} {% csrf_token %} <input class="form-control mt-4" type="text" name="numctt" id="numctt" value="{{ticket.numctt}}" placeholder="{{ticket.numctt}}"> <input class="form-control mt-4" type="text" name="nomctt" id="nomctt" value="{{ticket.nomctt}}" placeholder="{{ticket.nomctt}}"> <select required name="areaserv" id="areaserv"> <option disabled selected hidden>{{ticket.areaserv}}</option> </select> <select required class="followup" name="tiposerv" id="tiposerv"> <option disabled selected hidden >{{ticket.tiposerv}}</option> </select> <input class="form-control mt-4" type="text" name="tickettext" id="tickettext" value="{{ticket.tickettext}}" placeholder="{{ticket.tickettext}}"> {% block usuario %} … -
I have a problem with annotate. I want to add a subset counter column, but it doesn't get added
class ProductGroupInstanceInlineAdmin(admin.TabularInline): model=ProductGroup @admin.register(ProductGroup) class ProductGroupAdmin(admin.ModelAdmin): list_display=('group_title','is_active','group_parents','slug','register_date','update_date',) list_filter=('group_title','group_parents',) search_fields=('group_title',) ordering=('group_title','group_title',) inlines=[ProductGroupInstanceInlineAdmin] def get_queryset(self, *args , **kwargs): qs=super(ProductGroupAdmin,self).get_queryset(*args,**kwargs) qs=qs.annotate(sub_group = Count('groups')) return qs def count_sub_group(self,obj): return obj.sub_group I tried to add an extra column using the annotate method, which counts the subsets of my groups, but this additional column does not appear at all. -
How to upload a file larger than 32MB from django admin panel hosted in Cloud Run?
Problem I need to upload zip files with a size of ~800MB to a GCP Cloud Storage bucket using Django's admin panel. My Django API is hosted in Cloud Run, and I just found out Cloud Run has a request size limit of 32MB. I want to know if there's any workaround for this. What I tried I have tried using signed URLs and chunking the file in 30MB chunks, but got the same "413: Request too large" error. It seems that when I upload the file from the admin panel, it still sends a request with the whole file instead of sending it chunked. Here's my code up until now, which works perfectly from my local machine using a Cloud SQL proxy: utils.py: from django.conf import settings from google.cloud import storage def generate_signed_url(file_name, chunk_number): storage_client = storage.Client(credentials=settings.GS_CREDENTIALS) bucket = storage_client.bucket(settings.GS_BUCKET_NAME) blob_name = f'zip_files/{file_name}_chunk_{chunk_number}' blob = bucket.blob(blob_name) url = blob.generate_signed_url( version="v4", expiration=3600, method="PUT" ) return url def combine_chunks(bucket_name, blob_name, chunk_count): storage_client = storage.Client(credentials=settings.GS_CREDENTIALS) bucket = storage_client.bucket(bucket_name) # Create a list of the blobs (chunks) to be composed blobs = [bucket.blob(f'zip_files/{blob_name}_chunk_{i}') for i in range(chunk_count)] # Create a new blob to hold the composed object composed_blob = bucket.blob(f'zip_files/{blob_name}') # Compose the … -
Django // contact form connect to gmail
I would to know if someone has a good tuto about that, cause i find anything about that. I got only old tutos and google change his security about apps and when i create a special password for my app, it still doesn't work. connect contact form to gmail -
How can I filter an annotated query set
I have the code below that returns an aggregate of authors that have a book and the total amount of authors. This works well, but I want to get the count of authors that have a particular type of book and the total count of books. I have tried so many ways but giving wrong results. I would like to achieve this using annotate and aggregate as it will help performance. Below is my current code that works but it returns all authors with a book and total books, but I want authors with a particular type of book. from django.db.models import Count, Case, When, IntegerField, Sum data = self.author_set.annotate( total_books=Count("book", distinct=True), ).annotate( has_book=Case( When(total_books__gt=0, then=1), default=0, output_field=IntegerField(), ) ).aggregate( authors_with_books=Sum("has_book", default=0), authors_count=Count("pk", distinct=True), ) My Book model class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(null=True, blank=True, max_length=50) narration = models.CharField(null=True, blank=True, max_length=200) book_type = models.IntegerField(default=1) released = models.DateField() I have tried many tweaks but it returns wrong data. Please help -
language changed in django project but django-modeltranslation do not change
i used django-modeltranslation, the issue is when the language change, it does not affect and just one language shown, even than language was changed in the cookies these are my codes: class MenuItems(MPTTModel): title = models.CharField(max_length=50,verbose_name=_('Title')) url = models.CharField(max_length=100,verbose_name=_('Url Name')) parent = models.ForeignKey( 'self', null=True, blank=True, related_name='children', on_delete=models.CASCADE,verbose_name=_('Parent Menu')) order = models.IntegerField(default=0, verbose_name=_('Order')) class MPTTMeta: order_insertion_by = ['order'] def __str__(self): return self.title class Meta: verbose_name=_('Menu Item') verbose_name_plural = _('Menu Items') <!--ACCORDION Systematic START--> {% recursetree menu_items %} {% if not node.parent %} <div data-kt-menu-trigger="click" class="menu-item menu-accordion hover"> <!--begin:Menu link--> <span class="menu-link"> <span class="menu-icon"> <i class="ki-duotone ki-user fs-2"> <span class="path1"></span> <span class="path2"></span> </i> </span> <span class="menu-title">{{ node.title }}</span> <span class="menu-arrow"></span> </span> <!--end:Menu link--> <!--begin:Menu sub--> {% for child in node.get_children %} <div class="menu-sub menu-sub-accordion" kt-hidden-height="542" style=""> <!--begin:Menu item--> <div data-kt-menu-trigger="click" class="menu-item menu-accordion"> <!--begin:Menu link--> <span class="menu-link"> <span class="menu-bullet"> <span class="bullet bullet-dot"></span> </span> <span class="menu-title">{{ child.title }}</span> <span class="menu-arrow"></span> </span> <!--end:Menu link--> <!--begin:Menu sub--> <div class="menu-sub menu-sub-accordion menu-active-bg" kt-hidden-height="209" style="display: none; overflow: hidden;"> <!--begin:Menu item--> <!--begin:Menu link--> <div class="menu-item"> {% for instance in child.get_children %} {% if instance.is_leaf_node %} <a class="menu-link" href={% url instance.url %}> <span class="menu-bullet"> <span class="bullet bullet-dot"></span> </span> <span class="menu-title">{{ instance }}</span> </a> {% endif %} {% endfor %} … -
How can I display data from one page onto another page in django
So I am creating an expense tracking and budgeting app, and I have an idea that I want to implement. So I created a page (or app in Django) called "Budgets" and what I want to see when I select it is a table with columns 'Project Name', 'Budget (currency)', 'Expenses (currency)', 'Profit/Loss (currency)'. Now I have added a button on top which says "Add Budgets" and when I click it a form appears which I only have to feed 'Project Name' and 'Budget' and NOT the other two. I also have another page/app called "Expenses" which has every expense for the particular project. Now what I want is: To transfer the sum of all the expenses from the "Expenses" page/app and display it under the column 'Expenses' in the Budgets page. To make an automatic calculation of the profit/loss (i.e. Budget - Expenses) and have it display under the column 'Profit/Loss' in the Budgets page. I know for some people the question might not be clear and maybe extra information or attachments may be required, please don't hesitate to ask. I have not provided any code because I am unsure of what might be needed in particular. -
Unable to Terminate Django 2.1 Project Running on Ubuntu 20.04.2 LTS with NGINX, UWSGI, and Celery
I have a test project (a 'zombie' project) on the same server as the production version of my app. Both projects use Celery for background tasks, but they share the same RabbitMQ port. I noticed that some tasks from the production Celery instance were executed in the test environment. Attempting to resolve this, I tried to terminate the uwsgi process of the test project, but it was unsuccessful – the Django admin console for the test project remained accessible. Further attempts, such as renaming the project directory and restarting the server while ensuring the deletion of the relevant .pid file, also failed. I'm currently out of ideas and looking for help to resolve this issue. -
dj-rest-auth, django-allauth, mongodb authentication
i want to integrate user authencation in my django projet, i'm using dj-rest-auth, django-allauth and my db is mongodb but when i execute python manage.py migrate i get this error: File "/Users/venv/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 830, in __iter__ raise exe from e djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "django_site" LIMIT 1 Params: (1,) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None -
Django (DRF) ORM - Simple left join with reverse relation
I am trying to select data from my postgreSQL database using Django 3.2.9 and DRF 3.12.4. Here are my models : class Headpiece(ValidatedModelbase): class Types(models.TextChoices): POWDER = "Powder" SOLUTION = "Solution" id_headpiece = models.AutoField(primary_key=True) name = models.TextField(null=False) structure = models.TextField(null=False) total_structure = models.TextField(null=False) molecular_weight = models.FloatField(null=False) type = models.CharField(null=False, choices=Types.choices, max_length=255) status = models.BooleanField(default=True) comment = models.TextField(null=True, blank=True) class Meta: db_table = "headpiece" managed = True def __str__(self): return self.name class Matter(ValidatedModelbase): id_matter = models.AutoField(primary_key=True) dna_tag = models.ForeignKey(DNATag, on_delete=models.DO_NOTHING, null=True, blank=True) headpiece = models.ForeignKey(Headpiece, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='matter') class Meta: db_table = "matter" managed = True class Vial(ValidatedModelbase): id_vial = models.AutoField(primary_key=True) rack = models.ForeignKey(Rack, on_delete=models.DO_NOTHING) matter = models.ForeignKey(Matter, on_delete=models.DO_NOTHING, related_name='vial') barcode = models.CharField(null=False, max_length=255) position_column = models.IntegerField(null=False) position_row = models.IntegerField(null=False) quantity_left = models.FloatField(null=False) project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True) reserving_business_entity_name = models.CharField(null=True, max_length=255) origin_name = models.CharField(null=True, max_length=255) class Meta: db_table = "vial" unique_together = ["rack", "position_column", "position_row"] managed = True def __str__(self): return self.barcode The data i need is a list of Headpieces, joined with their Vials data. I want a new line for each Vial, and if no Vial is related, the Headpiece data only. In SQL, it translates to this : SELECT headpiece.*, vial.* FROM headpiece LEFT JOIN … -
Gofiber + Django - Template Recursion Issue
So I am generating a folder structure that uses accordion from bootstrap. This is working as intended for 1 level of depth. As soon as I want to go into 2+ levels of depth it does not work as intended. I get it working by tricking the handler. I run this via docker containers. I have a main for loop in the root of the structure. I that calls a template. I keep this template in partials folder. This works fine. within this template that is in the partials folder I once again call the template file as it should be a recursive loop until there is no need to call it again. I start my server using the following within the template: {% include "partials/subfolder_template.django" with folder=folder %} This holds the server from starting but I quickly modify this line to this: {% include "subfolder_template.django" with folder=folder %} Removing the partials/ makes the server work and boom - This server now starts and when I go to my handler the depth levels work as intended. The issue with this is that if the container fails or gets restarted then this will fail and show the following error on the … -
How can I post data to django import_export
I would like to test the import function from import_export django. When I run my test the code says I provide no dataset (None) even though I do provide a proper CSV file. Thus, my assertions (starting from self.assertIn('result', response.context)) fail. Why don't my resource class and def import_data see the dataset I provide in response = self.client.post(import_url, data=data)? My test: class ImportUserCase(TestCase): def setUp(self) -> None: self.admin = User.objects.create(login='admin', email='admin@example.com', password='password', is_staff=True, is_superuser=True) self.client = Client() self.client.force_login(self.admin) self.resource = UserImportResource() def test_import_action(self) -> None: import_url = '/admin/core/user/import/' process_url = '/admin/core/user/process_import/' input_format = '0' filename = 'users.csv' with open('users.csv', 'w') as f: writer = csv.writer(f) writer.writerow(UserImportResource.Meta.fields) writer.writerow('test', 'test@gmail.com', 'test, 'test', 'test) with open(filename, "rb") as f: data = { 'input_format': input_format, 'import_file': f, } response = self.client.post(import_url, data=data) self.assertEqual(response.status_code, 200) self.assertIn('result', response.context) self.assertFalse(response.context['result'].has_errors()) self.assertIn('confirm_form', response.context) confirm_form = response.context['confirm_form'] data = confirm_form.initial self.assertEqual(data['original_file_name'], 'books.csv') response = self.client.post(process_url, data,follow=True) self.assertEqual(response.status_code, 200) My resource: class UserImportResource(resources.ModelResource): class Meta: model = User instance_loader_class = UserLoader fields = ('login', 'email', 'first_name', 'last_name', 'gender') use_transactions = False def get_import_id_fields(self): return ['email'] def get_import_fields(self): return [self.fields[f] for f in self.get_import_field_names()] def get_import_field_names(self): return ('login', 'email', 'first_name', 'last_name', 'gender') def before_import(self, dataset, using_transactions, dry_run, **kwargs): to_delete = [] … -
In mutually selected data, how do you ask for the delete confirmation - Python, Django, HTML?
I want to select certain data and delete it from a code that has a check box. I can remove it, but I am unable to request a message of confirmation. Here is my view.py code. def expens(request): data = '' number = '' if 'delete_all' in request.POST: choosen = request.POST.getlist('x[]') if choosen: for selected in choosen: picked = Expenses.objects.filter(id=selected) picked.delete() messages.info( request, "Expens data has been deleted successfully.", extra_tags='success') else: messages.info(request, "Please select to delete.", extra_tags='error') if 'save' in request.POST: return render(request, 'expens.html', {'data': data, 'number': number}) And my HTML code: {% for expens in picked %} <div class="alert alert-danger" role="alert"> Do you want to delete: <b>{{ expens.assignment }} {{ expens.amount }}</b>?<br> <a class="btn btn-success" href="{% url 'expens_delete_config' expens.id %}">Yes</a> <a class="btn btn-danger" href="{% url 'expens' %}">No</a><br> </div> {% endfor %} <form method="post"> {% csrf_token %} <table class="table table-success table-striped" id="table"> <thead> <th>#</th> <th>Assignments</th> <th>Amount</th> <th>Date</th> <th><button class="btn btn-danger btn-sm" name="delete_all">Delete selected</button></th> </thead> <tbody> {% for info in data %} <tr> <td><input type="checkbox" name="x[]" value="{{info.id}}"> {{forloop.counter}}</td> <td>{{info.assignment}}</td> <td>{{info.amount}}</td> <td>{{info.add_date}}</td> <td> <a class="btn btn-danger btn-sm" href="{% url 'expens_delete' info.id %}"><i class="bi bi-x"></i></a> <a class="btn btn-warning btn-sm" href="{% url 'expens_edit' info.id %}"><i class="bi bi-pencil"></i></a> </tr> {% endfor %} </tbody> </table> </form> …