Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django views and HTML form
I have created a form in HTML and I want to bind it to a model, but I do not know how to make it possible to select a form from the database data by the type of a drop-down list. (for example, the name of the doctor and patient that should already be stored in the database.) When I do this through creating a form through django, everything works out, but I'm interested in HTML I get error : ValueError at /create_appointment/ Cannot assign "'patient'": "Appointment.patient" must be a "Patient" instance. models.py class Appointment(models.Model): time_appointment = models.DateTimeField() patient = models.ForeignKey( Patient, related_name='patient_to_appointment', null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey( Doctor, related_name='doctor_appointment', null=True, on_delete=models.SET_NULL) complaint = models.CharField(max_length=50, null=True, blank=True) views.py def create_appointment(request): if request.method == 'POST': datetime = request.POST['datetime'] patient = request.POST['patient'] doctor = request.POST['doctor'] service = request.POST['service'] appointform = Appointment( time_appointment=datetime, patient=patient, doctor=doctor, complaint=service) appointform.save() return redirect('/appointment') return render(request, 'main/f_appointment.html') html <body> <div class="text-center mt-5"> <form style="max-width: 480px; margin: auto" method="post"> {% csrf_token %} <p class="hint-text mb-3">Please sign in</p> <label class="sr-only" for="datetime"></label> <input type="datetime-local" name="datetime" class="form-control" placeholder="гггг-мм-дд чч:мм:сс время и дата записи" required autofocus /> <label for="patient" class="sr-only"></label> <input type="text" name="patient" class="form-control mt-2" placeholder="пациент" /> <label for="doctor" class="sr-only"></label> <input type="text" name="doctor" … -
Django Whitenoise causes error collecting static
When I run collectstatic on my Django site, I always get an error. This is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIRS = os.path.join(BASE_DIR, 'templates') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'not showing it here' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news', 'writers', ] INSTALLED_APPS += ('django_summernote', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'news.middleware.TimezoneMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIRS], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'news.context_processors.common_variables' ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { … -
Create a like button for blog posts in my Django?
I've been trying to create a like button for my blog posts in my Django blog but I can't figure out how to create one because it contain Integer . When the user clicks on the like button . The like button will increase and it will display near the post. This is my like module: class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) Thanks in advance -
Django extensions shell_plus --lab not working
I've been trying to use ./manage.py shell_plus --lab command but i keep getting following error: ... File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 556, in handle runner() File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 303, in run_jupyterlab self.run_notebookapp(app, options) File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 237, in run_notebookapp app.initialize(notebook_arguments) File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/jupyterlab/labapp.py", line 732, in initialize super().initialize() File "/home/user/.local/share/virtualenvs/project-MorsWGAo/lib/python3.8/site-packages/jupyter_server/extension/application.py", line 403, in initialize raise JupyterServerExtensionException(msg) jupyter_server.extension.application.JupyterServerExtensionException: This extension has no attribute `serverapp`. Try calling `.link_to_serverapp()` before calling `.initialize()`. I'm using pipenv this would be potentially relevant parts of my Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [scripts] dev = "./scripts/dev.sh" [requires] python_version = "3.8" [pipenv] allow_prereleases = true [packages] Django = "~=3.0.0" ... django-extensions = "*" ... [dev-packages] flake8 = "*" autoflake = "*" bpython = "*" epc = "*" importmagic = "*" ipdb = "*" ipython = "*" pyls-black = "*" pyls-isort = "*" coverage = "*" werkzeug = "*" jupyterlab = "*" I'd really appreciate any help with this. Thx in advance. -
Moving password validation errors for Django UserCreationForm, from password2, to password1
I've got a Django form class, that inherits from the built-in UserCreationForm. I'm working on submitting the form using AJAX, and returning the bound form (including errors) as rendered HTML if it doesn't validate. Something puzzling me is that the errors relating to the password (e.g. too short, common password...) appear for the password2 / confirmation field. Here's a screenshot of the default behaviour: From a UX perspective I feel as though it would be more useful for the errors to appear for the first password field in the form, so users can adjust that one, then confirm it by typing it again below. I've noticed that in UserCreationForm, clean_password2(), doesn't actually validate the password, it just checks that password1 and password2 match. Then in the _post_clean() method, password2 is validated, and any errors are added to that field. In my attempt to change it, I have overridden _post_clean() as follows: def _post_clean(self): super(forms.ModelForm, self)._post_clean() password = self.cleaned_data.get('password1') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password1', error) I don't want to call super, and have it validate and send errors to password2, so I am calling the post_clean method of the grandparent (ModelForm) instead (I think!), to not … -
Django Template curly brackets inside curly brackets
{% if hosts %} <div class="row"> {% for host in hosts %} {% if host.type_of == "Backend" %} <div class="col-sm-3">{{ host.type_of }}</div> {{ headers.{{ forloop.counter0 }} }} {% endif %} {% endfor %} </div> {% endif %} I am sending arrays, hosts and headers from views to my template, I need to get element of header with the current index (getting the header[i]) Error says Could not parse the remainder: '{{ forloop.counter0' from 'headers.{{ forloop.counter0' Can't seem to find any examples regarding to this. How can I achieve what I want ? -
BooleanField is not showing ( accessing ) in template
I am building a BlogApp and I built a comment disabled system, I did everything BUT Boolean Field's True or False options are not Accessing in Template. views.py This is the view of DetailView of Post. I did in it like :- If user tick Boolean Field while creating post then the comment form will not be seen. BUT..... def detail_view(request,id): data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None comment_form = CommentForm(data=request.POST) if Post.allow_comments == True : if request.method == 'POST': if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'mains/show_more.html', context ) new_post.html This is the view for Create new post. It will show the BooleanField while creating the Post. def new_post(request): """Add a new TOPIC .""" if request.method != 'POST': #No Data Submitted ; Create a blank form. form = PostForm() else: #Post data submitted ; process data. form = PostForm(request.POST,request.FILES) new_post = form.save(commit=False) new_post.post_owner = request.user new_post.save() return redirect('mains:posts') context = {'form':form} return render(request, 'mains/new_post.html', context) detail.html The Problem is in this Template {% if comment_form.allow_comments == True %} <br> <form method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" … -
Django 3.1.5 serving static files with Heroku
I'm having problems trying to get my Django web app on Heroku to pick up the static CSS file. Lots of the answers online already seem to refer to an older version of Django, but I've spent hours researching and still can't figure it out :( Help is appreciated! layout.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'mainapp/styles.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> {% if user.is_authenticated %} <a href="{% url 'logout' %}">Log out</a> {% else %} <a href="{% url 'login' %}">Log in</a> <a href="{% url 'register' %}">Register</a> {% endif %} {% block body %} {% endblock %} </body> </html> Info from Heroku which I think is relevant 2021-01-23T18:07:29.675104+00:00 app[web.1]: Not Found: /static/mainapp/styles.css 2021-01-23T18:07:29.675580+00:00 app[web.1]: 10.101.178.182 - - [23/Jan/2021:18:07:29 +0000] "GET /static/mainapp/styles.css HTTP/1.1" 404 179 "https://XXXXXX-XXXXXX-XXXXX.herokuapp.com/register" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36" 2021-01-23T18:07:29.676045+00:00 heroku[router]: at=info method=GET path="/static/mainapp/styles.css" host=XXXXXX-XXXXXX-XXXXX.herokuapp.com request_id=bb1c9f74-b21b-456e-96ca-b248d7ce5cd2 fwd="XX.X.XXX.XXX" dyno=web.1 connect=0ms service=6ms status=404 bytes=418 protocol=https base.py (settings) """ Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.1.5. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path … -
Using ```localStorage``` to store dynamically created buttons in Javascript
My goal is to have the user enter values which then generates a button. They should be able to continuously enter values and new buttons should be created following each entry. My current code allows for the creation of one button, but as soon the form is submitted, the page refreshes and the button is gone. How can I store them so that they stay on the page? My code: <script> var counter = 0; function createButton(){ var x = document.createElement("BUTTON"); x.className = "second"; var name = document.querySelector("#id_goal").value; var t = document.createTextNode(name); x.appendChild(t); document.getElementById("space_holder").appendChild(x); var insideclass = document.getElementsByClassName("second"); insideclass[counter].innerHTML = `<input type="button" onclick="location.href='/inside_goal'" value="${name}"/>`; counter = counter+1; }; </script> <h1 id = "home_header" style = "font-family: optima; text-align: center"> Nancy Dong </h1> <div id = "enter.goal"> <form id = "subBox" onsubmit="createButton();" method="post"> {% csrf_token %} {{ form }} <input type="submit", value = "Enter Goal"> </form> </div> <div id = "space_holder" style = "top: 50px; left: 50px;"> </div> Django Views.py class NewGoalForm(forms.Form): goal = forms.CharField(label="new goal") def index(request): return render(request, "index.html",{ "form": NewGoalForm() }) -
Concatenate Javascript for variable with django variable
Good afternoon, I have a javascript block that I would like to iterate and get a Django variable based on the index. How can I do this in a javascript block on django template? Example: var data = google.visualization.arrayToDataTable([ ['Descrição', 'Quantidade'], ['Concluídas', parseFloat("{{1_seller.seller_reputation.transactions.completed}}")], ['Canceladas', parseFloat("{{1_seller.seller_reputation.transactions.canceled}}")] ]); var options = { title: 'Transações ({{1_seller.seller_reputation.transactions.total}})', pieHole: 0.5, }; var chart = new google.visualization.PieChart(document.getElementById('1_transactionschart')); chart.draw(data, options); then the idea is to iterate over "1_", "2_", "3_" and goes on. How can I make this for in javascript and get the django variable? Regards, Bernardo -
Django: How to render data in tamplate from another template on button click
I would like to ask for help for my following issue: I have a template on the "Customer" side and template on the "Staff" side where both are in different django apps. Now..from Customer page I am via Ajax (button click) sending data to two different views (Customer and Staff) and saving objects to database . It is working but as you can see the Staff page will render data from Customer only When Loading the page. How I can render real time data on Staff page every time Customer will press the button either from view or from database? I believe I should use Django Channels for this purpose and I actually manage to get to work a test Chat room but I have no idea how I could implement it for my case. I am not an advance developer as you can see. Thank you in advance. -
Bootstrap Tooltip with HTML title attribute not working
I am trying to add a Bootstrap tooltip with 'data-html' attribute as true to a card as a span element using plain JavaScript. Some background Information I am using Django for the back-end and plain JavaScript for the front-end. Posts are added after the DOM content is loaded. A function addPost creates a card element where the post content and likes are displayed, near the like button I am trying to display the number of likes and with the help of a tooltip I want to display the names of the people who like that particular post. Here's the Layout.html file where the Bootstrap CSS and JS links are placed as well as the JS file of my project: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> <script src="{% static 'network/index.js' %}"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="#">Network</a> <div> <ul class="navbar-nav mr-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" onclick="load_postsbox({{user.username}})"><strong>{{ user.username }}</strong></a> </li> {% endif %} <li class="nav-item"> <a class="nav-link" id="all-posts">All Posts</a> </li> {% if user.is_authenticated … -
Can't refresh page in React-django app deployed in Heroku
I'm trying to deploy an application that I have made using the Heroku platform. I have followed this tutorial to deploy the application and everything seems to work well until the page is refreshed (whether I refresh it manually, or the internal code has to refresh it). Everything works fine on my local computer. The error: Not Found The requested resource was not found on this server. is displayed on the deployed app when I try to refresh the page. I'm guessing it's a problem with my "views.py" file or "settings.py" file. Here there are: ## views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache # Serve Single Page Application index = never_cache(TemplateView.as_view(template_name='index.html')) ## settings.py # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', # < As per whitenoise documentation 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hola.apps.HolaConfig', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = "uploads/" MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # # Database # # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': … -
Django/Python: update item in list
Hey so I am new to django/python and I want to create a to-do-app. I already have the basic structure, I can add a task, it is shown in my list and I can delete it. So I already have the C, R, and D from the CRUD features :-) Now I want to be able to update a task that is already in my list. So e.g. if I have a task called "laundry" I want to be able to click on it and change it to "do laundry" and save it. Or something like that. I have no idea how to to this or if it is possible. Maybe you can give me some inspiration (I want to do it myself so I don't need full code solutions). I am just kinda stuck and need somewhere to start... Thanks a lot in advance! -
local variable 'comment_form' referenced before assignment
I am building a BlogApp and I built a feature that if user disable comments ( through Boolean Field ) then the comments will be disabled. BUT i am stuck on an Error. When i open browser then it is showing me :- local variable 'comment_form' referenced before assignment views.py def detail_view(request,id): data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None if Post.allow_comments == True: if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() else: print("Comments are Disabled") context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, detail.html', context ) models.py class Post(models.Model): creater = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) date_added = models.DateTimeField(auto_now_add=True,null=True) description = models.CharField(max_length=10000,default='') allow_comments = models.BooleanField(default=False) detail.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} </div> <div class="col-6"> {{ form.description }} </div> </div> <br> {{ form.allow_comments }}<p>Allow Comments</p> <br> <br> <button type="submit">Add this Post</button> <button type="reset" value="reset">Reset Everything</button> </form> </div> I don't know . What am i missing in this. Any help would be appreciated. Thank You in Advance -
How can i save Multiple items in database using FileField in Django?
i want to upload multiple files from Django FileField. The code below upload single file instead of multiple files. i also define for loop for file data but i don't understand how can i files save in database? I would be grateful for any help. Views class NewsCreateView(CreateView): form_class = ArticleForm template_name = 'create.html' success_url = '/' def form_valid(self, form): form.instance.author = self.request.user for f in self.request.FILES.getlist('file_data'): # file_data it's an a Attribute instance = form.file_data = f instance.save() return super().form_valid(form) -
How do I change the 'name' HTML attribute of a Django Form field?
I have a Django 3.0 form # forms.py class SignupForm(UserCreationForm): email = forms.EmailField() This renders as the HTML element <input type="text" name="email" required id="id_email"> Is there a way to change the 'name' attribute? The widgets documentation suggests that either of these might work: # forms.py class SignupForm(UserCreationForm): email = forms.EmailField( widget = forms.TextInput( attrs = {'name': 'email_address'} ) ) or # forms.py class SignupForm(UserCreationForm): email = forms.EmailField() email.widget.attrs.update({'name': 'email_address'}) but both render with two name attributes; the first one isn't replaced: <input type="text" name="email" name="email_address" required id="id_email"> Is there a straightforward method of changing the name attribute? I've found a couple of related previous posts, but the questions and answers tend to be old (Django 1.0-era) and more convoluted than this process ought to be. I'm hoping that newer versions have a simpler solution. -
django: valueerror on optional field
This is my first django project, I'm not sure why I'm getting an error 'The 'image2' attribute has no file associated with it.' when those fields are optional. How can I fix this? model class LinksContent(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=100) somecontent = HTMLField(blank = True) image = models.ImageField(upload_to = 'images/%Y/%m/%d/') image2 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) image3 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) image4 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) links = ( ('faculties', 'faculties'), ('admission', 'admission'), ('resources', 'resources'), ('staff', 'staff'), ('research', 'research'), ) file1 = models.FileField(upload_to = 'files/%Y/%m/%d/', blank = True) section = models.CharField(max_length=13, choices=links) is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html> {% if content %} {% for item in content %} <div class="theHeader"> <img class = 'header-img' src = "{{ item.image.url }}"> <div class = 'author-info'> <img class = 'admin-img' src = "{{ item.author.image.url}}"> <p>&nbsp;{{ item.author}} &nbsp;</p> <p>&nbsp;{{ item.publish_date | naturaltime}}</p> </div> </div> <div id="content"> <h1>{{ item.title }}</h1> <p>{{ item.somecontent | safe }}</p> <div class = 'data'> <img class = 'images' src = "{{ item.image2.url }}"> <img class = 'images' src = "{{ item.image3.url }}"> <img class = 'images' src = "{{ … -
How to properly secure API login credentials with environment variables using React and Django
I have a project using React (frontend) and Django Rest Framework (backend), and it is currently deployed on PythonAnywhere. I'm using axios to connect to my API and load data from my database onto the React frontend. During development, I hardcoded the username and password for accessing the database into my index.js file (credentials are obscured below): import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; import axios from 'axios'; import 'semantic-ui-css/semantic.min.css'; import 'lightgallery.js/dist/css/lightgallery.css'; import './styles.css'; import * as serviceWorker from './serviceWorker'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post('/login/', { username: [HARD_CODED_USERNAME], password: [HARD_CODED_PASSWORD] }).then(rv => { console.log('Login', rv) }).catch(err => { console.log('Login error', err.response) }); const updatePhoto = () => { axios.patch('https://[WEBSITEADDRESS.COM]/api/photos/').then(resp => { console.log('Update response', resp) }).catch(error => { console.log("Update error", error) }) } ReactDOM.render( <App />, document.getElementById('root') ); serviceWorker.unregister(); This works, however the username and password are viewable upon inspection in the browser. Not only that, but the Django admin as well as the API is accessible to anyone, because it automatically logs them in using my username and password! I then tried using an .env file located at the root of my create-react-app project (same level with my package.json file): … -
ModuleNotFoundError at /blog/post/comment/update/18/ No module named 'test-post-ecomon'
I have a blog section of my website and I made an CommentUpdateView and after submiting the form it gives me this error ModuleNotFoundError at /blog/post/comment/update/18/ No module named 'test-post-ecomon' but I don't undersant why because this post exists and I implemented get_absolute_url in my Contact models and It should work right? When I create a new commment it works. view class CommentUpdateView(LoginRequiredMixin, UpdateView): model = Comment form_class = CommentUpdateForm template_name = 'blog/update_comment.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(author=self.request.user) model class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='replies') content = models.TextField(_('Content')) posted_date = models.DateTimeField(_('Posted Date/Time'), auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True) def __str__(self): return f'{self.author.username} - {self.post.title}' def get_absolute_url(self): return reverse('post', self.post.slug) urls path('post/<slug:slug>/', PostDetailView.as_view(), name='post'), path('post/comment/update/<int:pk>/', CommentUpdateView.as_view(), name='update-comment'), -
getting critical error while install mysqclient for django on ubuntu/ plesk
i create django project. when i add mysql database configuration on settings.py with migrate everything was created on mysql database. i'm using plesk . when i creating superuser it's added to auth_users database. but when i want to enter django admin with any users i'm getting user_auth error and django still looking information in sqlite database. this is on plesk server / ubuntu. when i created same django project and use freedbhosting and did same things i didnt get any errors and i enter to adminpanel with mysql.. i search and found that mabe i need mysqlclient on plesk/ubuntu server so i want try install it but when i want to install mysqclient i'm getting this error. Using cached mysqlclient-2.0.3.tar.gz (88 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip- install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/setup.py'"'"'; __file__='"'"'/tmp/pip- install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip- wheel- zeq33vj3 cwd: /tmp/pip-install-r9g0_kiz/mysqlclient_1e646ce6b9aa48bbb86f7b3a5092790f/ Complete output (41 lines): mysql_config --version ['5.7.32'] mysql_config --libs ['-L/usr/lib/x86_64-linux-gnu', '-lmysqlclient', '-lpthread', '-lz', '-lm', '-lrt', '-latomic', '- lssl', '-lcrypto', '-ldl'] mysql_config --cflags ['-I/usr/include/mysql'] ext_options: library_dirs: ['/usr/lib/x86_64-linux-gnu'] libraries: ['mysqlclient', 'pthread', 'm', 'rt', … -
Following a tutorial using Django/Python: ModuleNotFoundError: No module named 'pages'
I'm new to Django and am trying to create a very simple app off of a tutorial I found online. Working on a mac Django Version 2.0.7 Python 3.7.0 My file structure: helloworld ......venv ..........(other files) ......helloworld_project ..........(other files) ......manage.py ......pages .........._ pycache _ ..............otherfiles ..........admin.py ..........apps.py ..........migrations ..............(other files) ..........models.py ..........tests.py ..........urls.py ..........views.py The problem: when I run my urls.py file, I get the following message: Traceback (most recent call last): File "/Users/Bethany/Desktop/helloworld/pages/urls.py", line 3, in <module> from pages import views ModuleNotFoundError: No module named 'pages' My urls.py file: # pages/urls.py from django.urls import path from pages import views urlpatterns = [ path('', views.homePageView, name='home') ] I've tried replacing "from pages import views" with "from . import views" and get the same message. I've looked through a few similar questions on stack overflow, but haven't had success with finding a solution to fix my issue. does anyone have any suggestions? Thanks! If needed, this is the tutorial I'm following: https://djangoforbeginners.com/hello-world/ -
How To Create A Photo Gallery In Django?
Can someone perhaps provide some guidance as to how I would go about creating a photo gallery in Django? Currently I am able to upload one, and only one, photo. I would like to be able to upload multiple photos and query them in the template. I have scoured a lot of old posts on StackOverflow for an answer but everything either doesn't work (out of date) or is a half-answer. Thanks for any guidance you can provide. -
Scrapy error when run with Celery and Django Channels is installed: OSError: [Errno 9] Bad file descriptor
When I run this script with Django shell it will run without error, but when I run with celery worker it get this error: OSError: [Errno 9] Bad file descriptor. If I remove channels from INSTALLED_APPS the problem will be solved and task runs with celery worker without error. Running the same script with python Process (due to ReactorNotRestartable exception) in django shell get the same error which celery worker had: OSError: [Errno 9] Bad file descriptor. I think there's a conflict between Django Channels & Scrapy when spider is executed in another process. from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings def run_spider(spider) settings = get_project_settings() crawler_process = CrawlerProcess(settings=settings) crawler_process.crawl(spider) crawler_process.start() exception stack trace when run with celery worker: Task run spider raised unexpected: OSError(9, 'Bad file descriptor') Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/selector_events.py", line 256, in _add_reader key = self._selector.get_key(fd) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/selectors.py", line 192, in get_key raise KeyError("{!r} is not registered".format(fileobj)) from None KeyError: '9 is not registered' exception stack trace when run with python Process in Django shell: /usr/local/lib/python3.7/site-packages/billiard/pool.py in apply(self, func, args, kwds) 1387 ''' 1388 if self._state == RUN: -> 1389 return self.apply_async(func, args, kwds).get() 1390 1391 def starmap(self, func, iterable, chunksize=None): /usr/local/lib/python3.7/site-packages/billiard/pool.py in … -
How do I get self.request.user in DRF from a request in vue.js?
how do I get self.request.user in DRF from a request in vue.js? My request from .vue: async LoadCase() { this.case = await fetch( `${this.$store.getters.getServerUrl}/casedetail/${this.slug}` ).then(response => response.json()) } My class in views.py: class DetailCase(RetrieveAPIView): queryset = Case.objects.all() serializer_class = CaseDetalSerializers lookup_field = "slug" My class in serializers.py: class CaseDetalSerializers(serializers.ModelSerializer): possible_open = serializers.SerializerMethodField() class Meta: model = Case exclude = ("id","slug") def get_possible_open(self,case): request = self.context.get('request') print(request) print(request.user) What I get from print: <rest_framework.request.Request: GET '/api/v1/casedetail/rofl'> AnonymousUser Right now I'm getting the AnonymousUser for some reason, and I should be getting admin. What do I have to do to get it?