Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to compare the stored values and the inputs by user to remove duplicates in django views?
I have a variable in Django View which is interfacelist and it contains [TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2, TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21]. This is what the user input from the HTML and I request.POST.get it to the view. And in my database (SQL), I have the following: Here comes the question, how do i compare the data in the database and interfacelist and remove any duplicates? Like in this case, TenGigabitEthernet1/0/1, TenGigabitEthernet1/0/2 so I would remove it and keep the TenGigabitEthernet1/0/20, TenGigabitEthernet1/0/21 to be updated in the database. I tried the following codes: (This is happening is Django View) cursor.execute(f"SELECT interface FROM {tablename} WHERE id >=2") righttable = cursor.fetchall() print(righttable) #Notworking #for i in righttable: # if interfacelist[i] == righttable[i]: # interfacelist.remove(a) #Notworking for i in interfacelist: updatequery2 = f"INSERT INTO {tablename}(interface) VALUES('{i}')" cursor.execute(updatequery2) cursor.close() The variable righttable in this case will be the image shown earlier. It contains [TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5]. Also, the commented out codes are not working as it gives me a error of list indices must be integers or slices, not tuple. How do I fix this to achieve what I wanted? Would greatly appreciate if anyone can advise or help me. Thank you! -
django model object filter from 2 different model
So I am trying to filter comments made by a specific user within a specific station. First I have a model named comment and it has a relationship with the post. class Comment(Votable): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments_authored', on_delete=models.CASCADE, blank=True) text = RichTextUploadingField(blank=True, null=True) parent = models.ForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.PROTECT) It's pretty easy to filter just based on author. And then I have the model for post: class Post(Votable): title = models.CharField(max_length=200, unique=False) submitter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_submitted', on_delete=models.CASCADE) url = models.URLField('URL', max_length=200, null=True, blank=True) text = RichTextUploadingField(blank=True, null=True) def children(self): return self.comments.filter(parent=None) def __str__(self): return self.title def save(self, *args, **kwargs): # new if not self.post_slug: self.post_slug = slugify(str(self.title)+str(self.pk)) return super().save(*args, **kwargs) The post model has a relationship with the station, which I use StationPost to establish the relationship. So a station can have many posts: class StationPost(BaseModel): station = models.ForeignKey('Station', related_name='posts_set', on_delete=models.CASCADE) post = models.ForeignKey('Post', related_name='station', on_delete=models.CASCADE) class Meta: unique_together = ['station', 'post'] And in case of any confusion, here is the model for station class Station(BaseModel): #this is to add the station for each posts: alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') station_name=models.CharField(max_length=19,validators=[alphanumeric], unique=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='station_creator', on_delete=models.CASCADE) text = models.TextField(max_length=200, default='brief … -
how to use csrf token with django, react and axios and nginx
It been a few hours that i am getting the following errors while doing a post request to the backend from react frontend Access to XMLHttpRequest at 'https ://api.foo.com/api/create/' from origin 'https ://www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My full stack app was working correctly, react front end, django backend, infrastructure made of s3 for react, both hosted on aws cloudfront using terraform until i tried to implement the csrf token below i created the following config react axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true const Create = () => { const [fields, handleFieldChange] = FormFields({ name: "", }); const options = { headers: { 'Content-Type': 'application/json', } }; const handleSubmit = (e) => { e.preventDefault(); axios.post("https ://api.foo.com/create/", fields, options) .then(response => { ... django settings.py CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = "csrftoken" CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Access-Control-Allow-Origin', ] nginx ... location / { add_header 'Access-Control-Allow-Origin' 'https ://www.foo.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,X-CSRFToken'; ... } Any help would be much appreciated, thanks -
Unable to ssh into aws EC2 instance
I have a django application running on EC2. I was able to ssh into the server instance. However, just before running certbot to obtain ssl certificate, I ran the command sudo ufw enable. That command prompted an alert that running it might alter ssh command (or something of that nature), but I ignored the warning and proceeded to enable ufw. After obtaining the ssl certificate I logged out of the server. When I tried to connect to the server subsequently, I keep getting the error ssh: connect to host ec2-xxx-xxx-xxx.us-east-2.compute.amazonaws.com port 22: Connection timed out I have spent several hours trying to fix the error but it persists. Why am I unable to connect to my ec2 instance after running sudo ufw enable.Though I'm not very sure, does using let's encrypt certbot to obtaining ssl certificate alter certain configurations in the server? I'm somewhat confused about the whole process. (the major commands I ran to obtain the ssl certificate are: sudo apt install python3-certbot-nginx and sudo certbot --nginx -d your_domain) -
i18next doesn't translate when I run "npm run build", React in frontend, Django backend
I am making a project using React on front-end and Django on back-end.. Front-end and back-end are separated. My issue occurs only when I "npm run build" and when I run python local server to view my website I can see my front-end and I managed to connect it to backend... there is no error.. but my translation doesn't work.. ONLY in this occasion When I "npm start" on front-end it works perfectly.. Here is my i18n.js file.. import { initReactI18next } from 'react-i18next'; import LanguageDetector from 'i18next-browser-languagedetector'; import HttpApi from 'i18next-http-backend'; import i18next from "i18next"; i18next .use(HttpApi) .use(LanguageDetector) .use(initReactI18next) .init({ supportedLngs: ['en', 'rs'], fallbackLng: 'en', debug: false, // Options for language detector detection: { order: ['cookie', 'htmlTag'], caches: ['cookie'], }, react: {useSuspense: false}, backend: { loadPath: '/assets/locals/{{lng}}/translation.json', }, }) export default i18n;``` Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 30, 2021 - 02:08:28 Django version 3.2.7, using settings 'backend.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [30/Sep/2021 02:08:31] "GET / HTTP/1.1" 200 2513 [30/Sep/2021 02:08:31] "GET /static/js/main.4a38a3d9.chunk.js HTTP/1.1" 200 83939 [30/Sep/2021 02:08:31] "GET /static/css/2.3c7a9eae.chunk.css HTTP/1.1" 200 39104 [30/Sep/2021 02:08:31] "GET /static/js/2.c8bb41dc.chunk.js HTTP/1.1" 200 457027 [30/Sep/2021 02:08:31] … -
django python project is not using the specified template files
I know this is something dumb, but I'm a new programmer and I've been smacking my head against it for 2 hours and you will likely see it in 2 seconds so... View AllEncountersListView which has declared template_name = 'encounter_list_all.html' is using instead 'encounter_list.html'. I know the view is being called since it prints to terminal as expected. Thanks for your time. views.py: class AllEncountersListView(generic.ListView): model = Encounter paginate_by = 20 template_name = 'encounters_list_all.html' def get_queryset(self): print('in allEncounterListView') #to prove the correct view is being called return Encounter.objects.filter(user=self.request.user).order_by('-encounter_date') urls.py: urlpatterns = [ path('',views.index, name='index'), path('openencounter/', views.open_encounter, name='openencounter'), path('myencounters/', views.EncountersByUserListView.as_view(), name='my-encounters'), path('allencounters/', views.AllEncountersListView.as_view(), name='all-encounters'), path('encounter/<int:pk>', views.EncounterDetailView.as_view(), name = 'encounter-detail'), path('todaysencounters/', views.TodaysEncountersListView.as_view(), name='todays-encounters'), path('logout/', views.logout_view, name='logout'), path('export/', views.export_data_view, name = 'export'), ] file tree: ── Aents4 │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── templates │ │ ├── registration │ │ │ └── login.html │ │ └── temp │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── encounters │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20210926_1548.py │ │ ├── 0003_alter_encounter_encounter_date.py │ │ ├── 0004_auto_20210927_1704.py │ │ ├── 0005_animal_max_daily.py … -
Error on PostgreSQL: Line number: 1 - value too long for type character varying(10)
I'm able to do a bulk upload via django's ImportExportModelAdmin without a problem on my localhost and on the staging application. But when I try it on prod, it displays an error. One thing to note the key difference is that I am using SQLite for my local and staging sites. But prod uses Amazon RDS PostgreSQL database. I haven't encountered this problem since, and I don't know where to start looking. Here is the traceback: Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(10) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/env/lib/python3.6/site-packages/import_export/resources.py", line 668, in import_row self.save_instance(instance, using_transactions, dry_run) File "/home/ubuntu/env/lib/python3.6/site-packages/import_export/resources.py", line 446, in save_instance instance.save() File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 727, in save force_update=force_update, update_fields=update_fields) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 765, in save_base force_update, using, update_fields, File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw, File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute … -
"GET /static/css/bootstrap.min.css.map HTTP/1.1" 404 1834
I'm creating django site, I have some template and for some reason I'm getting this in django terminal. [29/Sep/2021 23:36:46] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 404 1834 This is my html code <!-- Core Stylesheet --> <link href="{% static 'style.css' %}" rel="stylesheet"> <!-- Responsive CSS --> <link href="{% static 'css/responsive.css' %}" rel="stylesheet"> Tried to add here, <link href="{% static 'css/bootstrap.min.css.map' %}" rel="stylesheet"> but not working. Still same. This style.css, is doing this. @import url('https://fonts.googleapis.com/css?family=Roboto:400,500,700,900'); @import 'css/bootstrap.min.css'; @import 'css/owl.carousel.min.css'; @import 'css/animate.css'; @import 'css/magnific-popup.css'; @import 'css/font-awesome.min.css'; I only get error for first one, and I'm having a problem with my site style, some functions are not working. But I'm getting, with .map extention. What I need to do? -
Django admin select dropdown
I have a field in my model called day. I want in the admin area to have a pre populate dropdown for this field instead of the text input. I have search and cant find a solution. <select name="day" id="day"> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> </select> Modle: class Timetable(models.Model): gym_class = models.ForeignKey('GymClass', on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() day = models.CharField(max_length=12) time_slot = models.CharField(max_length=12) trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE) def __str__(self): return self.gym_class.name admin.py: from django.contrib import admin from .models import GymClass, Category, Trainer, Timetable admin.site.register(GymClass) admin.site.register(Category) admin.site.register(Trainer) admin.site.register(Timetable) -
Trying to COPY adjacent folder into Docker image but copies the entire folder over
I have a directory structure like the following: project-root/ api/ docker/ Dockerfile ... src/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py client/ docker/ Dockerfile nginx.conf src/ App.js index.js In my API Dockerfile I'm trying to just copy src in to /app. However, I keep getting the entire api directory. What I expect to see is: app/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py This stage is the only one where src is copied over. The python-base and builder-base are either env vars or application dependencies. FROM python-base as production COPY --from=builder-base $VENV_PATH $VENV_PATH RUN chmod +x . /opt/pysetup/.venv/bin/activate COPY ../src /app WORKDIR /app CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application", "-t", "150"] I've tried COPY ../src /app, COPY ./src /app, COPY src /app. How should I copy over just the src to app in this project structure? -
Need help iterating through each row in SQLite DB to render to html template
I'm using the Django framework with SQLite DB. I'm using SQL queries in my views.py and connecting that data to render on the frontend in my dashboard.html template. I'm having trouble iterating through each row in my database table 'scrapeddata'. When I view the dashboard, the data being rendered is all bunched up together in one div. I'm hoping to get each row in the database to render in one div each. I tried placing a for loop in my views.py but when I do that, I only get one row from the database rendered on dashboard.html. Any help is appreciated, thank you. views.py: def dashboard(request): connection = sqlite3.connect('db.sqlite3') cursor = connection.cursor() col1 = '''SELECT companyname FROM scrapeddata ORDER BY companyname ASC''' cursor.execute(col1) companyname = cursor.fetchall() col2 = '''SELECT name FROM scrapeddata''' cursor.execute(col2) name = cursor.fetchall() col3 = '''SELECT portfolio FROM scrapeddata''' cursor.execute(col3) portfolio = cursor.fetchall() people_data = [] data = { 'companyname': companyname, 'name': name, 'portfolio': portfolio } people_data.append(data) connection.close() if request.user.is_authenticated: return render(request, 'dashboard.html', {'people_data':people_data}) else : return redirect('/login') dashboard.html: Here's the for loop in the template. {% for data in people_data %} <div> <p>{{ data.companyname }}</p> <p>{{ data.name }}</p> <p>{{ data.portfolio }}</p> </div> {% endfor %} -
Django passing a variable through the path, causing path repetitions. how to get out of that loop?
I know this is an armature question but here goes. I have a url path as follows: path('projects/<s>', PL.projects), and i pass a string from the html template by putting it into an herf tag like so projects/some_string. this works once but then the base url changes to <ip>/projects/some_string. so when i try to excite the path to pass a string in that domain then I get an error as the url is now <ip>/projects/projects/some_string. how do i set it up so that i can pass as many strings as possible as many times as possible without having to clean my url in the browser everytime. Thanks for the help. -
Get cumulative running sum with group by in django orm
I have a table of two (relevant) columns. table: Transaction columns: transaction_date, amount I would like to get the cumulative amount for each month. So, for each month, get the sum of transactions from the beginning to that point in time. In PostgreSQL I would do something like this: SELECT date_trunc('month', transaction_date::date) AS formatted_transaction_date, SUM(SUM(amount)) OVER (ORDER BY date_trunc('month', transaction_date::date) ROWS UNBOUNDED PRECEDING) AS cumulative_transaction_amount FROM transaction GROUP BY date_trunc('month', transaction_date::date); I am trying to do the same in Django Orm. The closest I have gotten is this: Transaction.objects.values( formatted_transaction_date=TruncMonth('transaction_date') ).annotate( cumulative_transaction_amount=Window( expression=Sum('amount'), order_by=TruncMonth('transaction_date').asc(), frame=RowRange(start=None, end=0), ), ) This however throws an error: django.db.utils.ProgrammingError: column "transaction.amount" must appear in the GROUP BY clause or be used in an aggregate function I understand that the Django query I am executing is not identical to the PostgreSQL query. The PostgreSQL query runs SUM(SUM(amount)), while the Django query translates simply to SUM(amount). However, I was unable to find the syntax of Django to achieve same result. What am I doing wrong? -
One database with multiple django projects
I have two django projects connecting to same database. One of them is using authentication with custom user model and is working fine. Now i have to secure second project and use user authentication. It will be more or less similar to what we are using in first project. I tried creating models in second project but i think it is conflicting with already existing django tables. My question is how can we have two separate projects, each having their own django tables (auth and other). Till now i have tried and i am getting following error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'app.customuser', but app 'app' doesn't provide model 'customuser'. -
Django Annotate - get list of numbers in annotate
This models djago implements annotate with ArrayAgg, just in excecuted queryset view error Unable to get repr for <class 'project.model.auditoria.AuditoriaQuerySet'>. Help me please. this is query: modelA.objects.filter(field_a_id__in=list_elements,field_b_id=n).annotate(arrar_list_with_annotate=ArrayAgg(list(ModelB.objects.filter(ModelB.field_a = Cast('modelA.field_a', IntegerField()), modelA.field_c = int(nn)).values_list('ModelB.field_a', flat=True)))).values('create','view','modified','delete','arrar_list_with_annotate') -
Add delete raw button to table from database Django
I have a form on the page that adds data to the database and displays it in a table I need to add a button that will delete a specific row by id from the database index.html <tbody> {% for expense_item in expense_items %} <tr> <td>{{ expense_item.username}}</td> <td>{{ expense_item.expense_name }}</td> <td>{{ expense_item.category }}</td> <td>{{ expense_item.cost }}zł</td> <td>{{ expense_item.date_added}}</td> <td>BUTTON HERE</td> </tr> {% endfor %} </tbody> Models.py class ExpenseInfo(models.Model): username = models.CharField(max_length=255, default='NoName') expense_name = models.CharField(max_length=20) category = models.CharField(max_length=20) cost = models.FloatField() budget_id = models.CharField(default='0123456789', max_length=10) date_added = models.DateField() user_expense = models.CharField(max_length=20) Views.py def add_item(request): budget_id = request.user.last_name name = request.POST['expense_name'] category = request.POST['category'] expense_cost = request.POST['cost'] expense_date = request.POST['expense_date'] try: ExpenseInfo.objects.create(username=request.user, expense_name=name, category=category, cost=expense_cost, date_added=expense_date, user_expense=budget_id) except ValueError or TypeError: print('No data.') return HttpResponseRedirect('app') -
Django 3 Form Data not posting to DB and I would like it to, what am I missing?
This in in the early stages of testing and my expectation is that I should have enough here to write to the DB and I see no signed of a failure anywhere aside from the empty table after several POST attempts. #WEB FORM <form action="/" method="POST" id="ticketsubmitform"> {% csrf_token %} <div class="form-control" {% if form.date_submitted.errors %}errors{% endif %}> {{ form.date_submitted.label_tag }} {{ form.date_submitted }} {{ form.date_submitted.errors }} </div> <div class="form-control" {% if form.contact_name.errors %}errors{% endif %}> {{ form.contact_name.label_tag }} {{ form.contact_name }} {{ form.contact_name.errors }} </div> <div style="padding-bottom: 12pt"> <button type="submit"> >>> Submit Ticket >>> </button> </div> </form> #views.py def ticketing_app(request): if request.method == 'POST': form = TicketForm(request.POST) if form.is_valid(): ticket = Ticket( date_submitted=form.cleaned_data['date_submitted'], contact_name=form.cleaned_data['contact_name'], ) ticket.save() else: form = TicketForm() return render(request,'authentication/ticketing-app.html',{ "form": form }) #forms.py class TicketForm(forms.Form): date_submitted = forms.DateField(label="Date Submitted:", required=True, error_messages={ "required": "Date must not be empty." }) contact_name = forms.CharField(label="Contact Name:", max_length=45, required=True, error_messages={ "required": "Contact Name must not be empty.", "max_length": "Please enter a shorter name." }) #models.py class Ticket(models.Model): #---Base Meta----------------------------------------- date_submitted = models.DateField(max_length=15) contact_name = models.CharField(max_length=45) No errors on post - [29/Sep/2021 21:18:55] "POST / HTTP/1.1" 200 I do not see anything missing that would prevent a DB write -
django coverage not covering the urls despite writing specific tests for the urls
in my app named backoffice_engine, my urls.py file is as follows from django.urls import path, include from . import views urlpatterns = [ path('test/', views.test, name='test'), path('', views.dashboard, name='dashboard'), path('dashboard/', views.dashboard, name='dashboard'), path('add_new_client/', views.add_new_client, name='add_new_client'), path('edit_client/<int:client_id>', views.edit_client, name='edit_client'), .....some more paths.... ] my test_urls.py file for this urls.py file is as follows from django.test import SimpleTestCase from django.urls import reverse, resolve from backoffice_engine.views import * class TestBackofficeEngineUrls(SimpleTestCase): def test_test_url(self): url = reverse('test') self.assertEquals(resolve(url).func, test) def test_blank_url_uses_dashboard_function(self): url = reverse('dashboard') self.assertEquals(resolve(url).func, dashboard) def test_add_new_client(self): url = reverse('add_new_client') self.assertEquals(resolve(url).func, add_new_client) def test_client_detail(self): url = reverse('client_detail', args=['1']) self.assertEquals(resolve(url).func, client_detail) my understanding is runnning coverage on this file should result in coverage report showing that the following urls have been covered by unit tests. however coverage report for backoffice_engine.urls.py is zero missing by default. the report only is checking only the first 3 lines of the urls.py file -
how to take multiple images from webcam and save into database javascript - django
i'm trying to use modelformset_factory with capturing image from webcam , in order to take several images and save into database ? i'm only able to take one image , is there any way to achieve that please ? or how to use dynamic number of canvas ? class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) **NOTE ** my javascript solution doesnt work with formset const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); context.drawImage(player, 0, 0, canvas.width, canvas.height); const imgFormat = canvas.toDataURL(); docs.value = imgFormat e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none … -
Django custom user 'Account' object has no attribute 'has_module_perms'
I create a custom user model to login via email, but i got some issue when im tried to login on admin channel from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManajer(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email = self.normalize_email(email), password= password, username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self.db) return user I'm able to create a superuser. However, when I try to login with email. I got this Error Exception Type: AttributeError Exception Value: 'Account' object has no attribute 'has_module_perms' Exception Location: ....\env\lib\site-packages\django\utils\functional.py, line 241, in inner Can someone fix that ? -
Django join between 3 tables
Hi i dont know really how i can perfom a join between this 3 tables. class Table1(models.Model): '''Productos a ser utilizados''' name = models.CharField() class Table2(models.Model): '''Productos a ser utilizados''' table1 = models.ForeignKey(Table1, related_name='TableTwo', on_delete=models.CASCADE, null=True, blank=True) class Table3(models.Model): '''Productos a ser utilizados''' codigo = models.IntegerField() table1 = models.ForeignKey(Table1, related_name='TableThree', on_delete=models.CASCADE, null=True, blank=True) im really confused about subquerys and join on django i dont know how i can do this. -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I am trying docker-compose an app with django and postgres using docker-compose but I get an error with the "NAME" Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'POSTGRES_NAME': 'postgres', 'POSTGRES_USER': 'postgres', 'POSTGRES_PASSWORD': env('POSTGRES_PASSWORD'), 'POSTGRES_HOST': 'localhost', 'POSTGRES_PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_NAME: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=sec DATABASE_URL=postgres://postgres:pass@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=pass POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Where does this "NAME" come from? Thanks for your help -
Django, Postgres and Docker compose: django.db.utils.OperationalError: could not connect to server: Connection refused
Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': env('POSTGRES_PASSWORD'), 'HOST': 'localhost', 'PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_DB: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=thekey DATABASE_URL=postgres://postgres:thepassword@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=thepassword POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Inside my postgres database it says 2021-09-29 20:29:02.375 UTC [1] LOG: starting PostgreSQL 13.4 (Debian 13.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv6 address "::", port 5432 2021-09-29 20:29:02.379 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2021-09-29 20:29:02.384 UTC [26] LOG: database system was shut down at 2021-09-29 20:29:00 UTC 2021-09-29 20:29:02.390 UTC [1] LOG: database system is ready to accept connections PostgreSQL Database directory appears to contain a database; Skipping initialization I am not able to connect the django app with the postgres, can someone please help? I have started … -
Django - PermissionRequiredMixin - Return a 'permission_denied_message' in current View, instead of a 403 Page?
Django version 3.0.5 I want to use the PermissionRequiredMixin in my View to display a banner message the same way I would with the SuccessMessageMixin. For example, if a user attempts to delete an object and they do not have permissions, the permission_denied_message would essentially be treated as an error message an displayed in the current view as a banner message. Is that even possible? the code that I currently have does not work - it always redirects to the 403 page. see below: class DocDeleteView(PermissionRequiredMixin, SuccessMessageMixin, DeleteView): model = SlateDoc success_url = reverse_lazy('slatedoc-list') success_message = "SlateDoc was deleted!" permission_required = ('slatedoc.delete_slatedoc') raise_exception = True permission_denied_message = "Permission Denied" def delete(self, request, *args, **kwargs): if self.has_permission() is False: messages.error(self.request, self.permission_denied_message) else: self.object = self.get_object() self.object.soft_delete() messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url()) -
django register_simple_tag send two parameter and how can ı use this in if condition?
In my project I want user make just one comment to Doctor profile.So ı choosed to use register_simple_tag and find if user made comment before bu if condition doesn't work.Can anyone know which part is wrong or has the another better way to solve this issue? commentExist.py register=template.Library() @register.simple_tag def isCommentExist(request,doctor): commmentExist=CommentModel.objects.filter(parent=None,is_published=True,doctor=doctor,comment_user=request.user).count() if commmentExist: return True else : return False profile.html {% if request.user.is_authenticated %} {% load commentExist %} {% isCommentExist request doctor as existComment %} {% endif %} {% if existComment %} # make some operation {% else %} # make some operation {% endif %}