Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value of <h1> and <p> tag(which changes dynamically time to time) from html to Django in views.py and print in def
SO I want to print the value of restName (which is in )in vscode console after positive. When I click on the submit button it should be get printed in the console in def. Views.py def home(request): if request.method == 'POST': if request.POST.get('form2'): print("Positive") restName=str(request.POST.get('restName')) print(restName) return render(request,'rest.html') else: print("Negative") rests= Restaurent.objects.all() for rest in rests: print(rest) return render(request,'home.html',{'rests':rests}) HTML CODE <div class="container-fluid"> <div class="container-fluid " > <div class="row "> {% for rest in rests %} <form action="home" method="post" > {% csrf_token %} <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-3" > <div class="card" style="width: 18rem;"> <img src="{{rest.RestImg.url}}" class="card-img-top" alt="..."> <div class="card-body"> <!-- I want RestName and RestAddr send to Rest Def in views.py --> <h5 class="card-title" name="restName">{{rest.RestName}}</h5> <p class="card-text" name="restAddr">{{rest.RestAddr}}</p> <input type="submit" name="form2" > </div> </div> </div> </form> {% endfor %} </div> </div> </div> -
Django ImportError: Couldn't import Django When Use Docker
I am getting an error in console while trying to use docker. How to fix it but when I test With localhost it just work. error PS C:\Users\Test\Desktop\Projects\Testadmin\master> docker-compose up Creating network "master_default" with the default driver Creating master_web_1 ... done Attaching to master_web_1 web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 8, in <module> web_1 | from django.core.management import execute_from_command_line web_1 | ModuleNotFoundError: No module named 'django' web_1 | web_1 | The above exception was the direct cause of the following exception: web_1 | web_1 | Traceback (most recent call last): web_1 | File "manage.py", line 10, in <module> web_1 | raise ImportError( web_1 | ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? master_web_1 exited with code 1 docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED l RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ manage.py #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'master.settings') try: from django.core.management import execute_from_command_line except ImportError as … -
Django object of type 'type' has no len()
we can't get the http response as json. Error we encountered: TypeError at /ui/subfix/3 object of type 'type' has no len() Request Method:GETRequest Code sample: @api_view(('POST',)) @csrf_exempt @renderer_classes(JSONRenderer,) def project_image_alternative_form_submit_ajax(request, object_id): project_image = ProjectImage.objects.filter(pk=object_id).first() response_json = { 'message': 'Image ...', } return Response(response_json, status=status.HTTP_200_OK) -
I want to add First name and last name field
My form only gives me username, email, password1, password2, i wanna have First name and Last name on this firl too. My form: <div class="col-12"> <h1>{% trans "Sign Up" %}</h1> <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> -
OperationalError at / no such table: posts_post
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error "OperationalError at / no such table: posts_post". -
name 'AuthUserUserPermissions' is not defined
I'm really confused.I want to create and insert data to auth_user_user_permissions, but it seems it not working. I also already imported . Please explain and help me from django.contrib.auth.models import User, auth, Permission current_code AuthUserUserPermissions.objects.create(permission_id=id, user_id=user.id) -
How to write log records to existing error log file
The error log that my django error's get written to is highly accessible. As a result, within my code, I'd like to use this same file for my logging. My configuration looks like this. Settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/opt/python/log/djangoerrors.log' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } Within my view, I've got this: import logging logger = logging.getLogger(__name__) def myview(request): ... some code ... logger.error('hello. This should be logged to the error file.') Unfortunately, this text isn't being written to my djangoerrors.log file. Can you see what I'm missing? Thanks! -
How to filter table using daterangepicker?
I used AdminLTE's Date Range Picker for my web application. What I need to do is to flter the datatable I have using the said date range. But the output of the picker is all integer type, wherein my datatable date and time is alphanumeric. Date range picker: The dates in my table: I have no idea how to convert the 'month' integer to string in able to filter the table. I am using django default 'datetime.now' on saving the data. How do I use this date range picker for filtering? -
Content Aggregator
I am web scraping data from skysports of all the top european football table standings. I was able to get the dataframe with pandas but I can not find a solution to display the tables on html besides using csv files. Is there another way or do I have to use a different technology? Please and thanks page = [ 'https://www.skysports.com/premier-league-table', 'https://www.skysports.com/la-liga-table', 'https://www.skysports.com/bundesliga-table', 'https://www.skysports.com/serie-a-table', 'https://www.skysports.com/ligue-1-table' ] league = [ "epl", "liga", "bund", "serie", "ligue", ] for pag, leag in zip(page, league): response = requests.get(pag) soup = BeautifulSoup(response.text, 'html.parser') top_col = soup.find('tr', attrs={'class': 'standing-table__row'}) columns = [col.get_text() for col in top_col.find_all('th')] last_df = pd.DataFrame(columns=columns) last_df contents = soup.find_all('tr', attrs={'class':re.compile('standing-table__row')}) for content in contents: teams = [tea.get_text().strip('\n') for tea in content.find_all('td')] first_df = pd.DataFrame(teams, columns).T first_df.columns=columns last_df = pd.concat([last_df,first_df], ignore_index=True) -
MultiValueDictKeyError : file attachement
Hi there i'm trying to send an email with a file as attachement but i get an MultiValueDictKeyError error this is my view: def postuler_save(request): name = request.POST.get('name', '') mail = request.POST.get('mail','') numero = request.POST.get('numero','') etablissement = request.POST.get('etablissement','') email= EmailMessage("message from:" + "" + name, "phone number:" + ""+ numero + "mail:" + ""+ mail+"etablissement" + ""+ etablissement,EMAIL_HOST_USER,[mail]) email.content_subtype = 'html' file = request.FILES['file'] email.attach(file.name, file.read(), file.content_type) email.send() return HttpResponseRedirect("/") this is the traceback Traceback (most recent call last): File "C:\Users\WD\Miniconda3\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('file'), another exception occurred: File "C:\Users\WD\Miniconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\WD\Miniconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\WD\Desktop\weserveit\gestion\views.py", line 32, in postuler_save file = request.FILES['file'] File "C:\Users\WD\Miniconda3\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /postuler_save Exception Value: 'file' -
Django Rest framework Simple JWT Custom Authentication
I am new to django and having trouble with authentication. I have different users(customer, admin, operator). So i want to authenticate according to the type of user when they hit a specific URL. I am using simple jwt to create tokens but cannot authenticate the username and password in the specific api view. -
What is the purpose of the UID within this Django Sign Up Function
I am learning how to create a django sign up page and I am at the point of creating an email verification. I am trying to use the code snippet here: def usersignup(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() return HttpResponse('We have sent you an email, please confirm your email but I do not know what purpose the uid serves. Why is encoding the user model object in the verification email necessary? -
I am importing Django select2 widget and getting Uncaught typeError
I am trying to import a Django Select2 widget, but keep getting an Uncaught typeError: adapter is not a function. I can't seem to find this issue online, but previously I was running the urls below in my widgets.py https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css I want to upgrade to most recent version of select2 (4.0.13), but can't seem to get it to work. How can I fix this? class Select2Mixin(): class Media: css = { 'all': ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css",) } js = ("https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.js", 'js/customselect2.js') def update_attrs(self, options, attrs): attrs = self.fix_class(attrs) multiple = options.pop('multiple', False) attrs['data-adapt-container-css-class'] = 'true' if multiple: attrs['multiple'] = 'true' for key, val in options.items(): attrs['data-{}'.format(key)] = val return attrs def fix_class(self, attrs): class_name = attrs.pop('class', '') if class_name: attrs['class'] = '{} {}'.format( class_name, 'custom-select2-widget') else: attrs['class'] = 'custom-select2-widget' return attrs class Select2Widget(Select2Mixin, forms.widgets.Select): def __init__(self, attrs=None, choices=(), *args, **kwargs): attrs = attrs or {} options = kwargs.pop('options', {}) new_attrs = self.update_attrs(options, attrs) super().__init__(new_attrs) self.choices = list(choices) class Select2MultipleWidget(Select2Mixin, forms.widgets.SelectMultiple): def __init__(self, attrs=None, choices=(), *args, **kwargs): attrs = attrs or {} options = kwargs.pop('options', {}) new_attrs = self.update_attrs(options, attrs) super().__init__(new_attrs) self.choices = list(choices) I also call this into my html file <html> <head> <!--Importing CSS stylesheets--> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" /> <link … -
Clean the string before eval in Django REST Framework
I am POSTing a str(list) to my web service written in Django Rest Framework: to_post = str(['a','b','c']) response = requests.post( 'https://myservice.com/', data={ 'field1': to_post, } ) In my view, I receive it as: class CheckVisibilitySerializer(serializers.Serializer): field1 = serializers.CharField(max_length=1000) class CheckVisibilityView(CsrfExemptMixin, APIView): """ List all snippets, or create a new snippet. """ authentication_classes = [] @csrf_exempt def post(self, request, format=None): # pylint: disable=unused-argument, redefined-builtin serializer = CheckVisibilitySerializer(data=request.data) if serializer.is_valid(): field_1 = serializer.data.get('field_1') But the string I receive contains ''s so field_1 contains "['a\','\b','c']". I need to do eval(field_1) to turn it into a list again for processing. How do I remove the ''s to eval it properly? -
Id is required in Formset editing Django
I'm trying to edit my values for 2 formsets. I'm using a inline formset in one of the forms. I can create data just fine, but updating is not working. What can be wrong? Here is my code. models.py class Projeto(models.Model): nome_projeto = models.CharField('Nome do Projeto', max_length=200) def __str__(self): return self.nome_projeto class Colaboradores(models.Model): projeto = models.ForeignKey(Projeto, on_delete=models.CASCADE, related_name='colaboradores') colaborador_projeto = models.CharField(max_length=200, blank=True) def __str__(self): return self.colaborador_projeto forms.py from django import forms from .models import Projeto, Colaboradores class PostForm(forms.ModelForm): class Meta: model = Projeto fields = '__all__' nome_projeto = forms.CharField(label='Nome do Projeto:', required=True, widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) views.py def editar_projeto(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = PostForm(instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(instance=projeto_editar) context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = PostForm(request.POST, instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(request.POST, instance=projeto_editar) if form.is_valid() and form_colab.is_valid(): projeto_editado = form.save() form_colab.instance … -
role doesnot exist when trying to configure postgresql with django in docker
I am new in both docker and postgres. Here I am trying to connect postgres with django. Everytime i try docker-compose up I get this error db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-09-15 21:58:42.169 UTC [1] LOG: starting PostgreSQL 12.4 (Debian 12.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2020-09-15 21:58:42.170 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-09-15 21:58:42.170 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2020-09-15 21:58:42.179 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2020-09-15 21:58:42.197 UTC [25] LOG: database system was shut down at 2020-09-15 21:58:41 UTC db_1 | 2020-09-15 21:58:42.203 UTC [1] LOG: database system is ready to accept connections web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). db_1 | 2020-09-15 21:58:45.233 UTC [32] FATAL: password authentication failed for user "sddhruvo" db_1 | 2020-09-15 21:58:45.233 UTC [32] DETAIL: Role "sddhruvo" does not exist. db_1 | Connection matched pg_hba.conf line 99: "host all all all md5" web_1 | Exception in thread django-main-thread: web_1 | … -
How do I headlessly create a page in Wagtail?
Is there any way I mimic the Wagtail behaviour of creating pages? The only way that I can think of is to totally replicate the POST request sent by them upon clicking 'Publish' in the admin interface, but that would be just hideous. I need this because I need to get a product list from an api, treat them and insert them in my DB. I would prefer to do this through wagtail so I do not drift away from my CMS In a perfect world this would be a call to some api endpoint where I provide the needed fields in the body of the request. -
Django - creating a random page selector
I'm hoping to create a link on a homepage that, when clicked, will randomly redirect the user to 1 out of 5 entry pages (CSS, Django, Git, HTML, Python) on the site. I saw someone else asking essentially the same question (select an random page with django) and I tried to follow the 2 answers but now when I click on my Random Page link I have an error: NoReverseMatch at /wiki/random/ Reverse for 'index' with arguments '('Git',)' not found. 2 pattern(s) tried: ['wiki/random/$', 'wiki/$'] Request Method: GET Request URL: http://127.0.0.1:8000/wiki/random/ Exception Type: NoReverseMatch views.py from django.urls import reverse from django.http import HttpResponseRedirect from . import util import random def random_page (request): entries = util.list_entries() selected_page = random.choice(entries) return HttpResponseRedirect (reverse('index', args=[selected_page])) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("css/", views.css, name="CSS"), path("django/", views.django, name="Django"), path("git/", views.git, name="Git"), path("html/", views.html, name="HTML"), path("python/", views.python, name="Python"), path("createnew/", views.createnew, name="New_Entry"), path("random/", views.random_page, name="index") ] layout.html <div> <a href="{% url 'index' %}">Random Page</a> </div> I was a little worried about making the homepage and random_page have the same name "index" but even when I changed the name in views.py to "random" and then changed it in … -
How to test django (3.0) CreateView's 'form_valid' method and parameters with a test client?
Some info In order to make some "current-logged-in-user" info available across multiple views and apps, I stored they're keys in session, which is available via any request instance I used class based CreateView to create an object with a ModelForm I've created I wanted to use some object's key in session inside the CreateView's valid_form method The valid_form method is called from post, so in order to pass request to valid_form, I overrode post and valid_form, as seen below What I'm trying to do I want to test the valid_form instance, specifically its request value. To do so, I'm using Django's test client. Do note, I'm NOT trying to test a ModelForm instance, I'm trying to test the view and test the valid_form method (and its parameters). Some code models.py: class MyModel(models.Model): my_model_text = models.CharField(max_length=100) my_model_date = models.DateTimeField( 'my model date', auto_now_add=True) views.py: class CreateMyModelView(LoginRequiredMixin, generic.edit.CreateView): model = MyModel template_name = 'myapp/create-my-model.html' form_class = CreateMyModelForm def post(self, request=None, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form, request) else: return self.form_invalid(form) def form_valid(self, form, request): my_model_text = form.cleaned_data['my_model_text'] MyModel.objects.create(my_model_text=my_model_text) return redirect(reverse('myapp:mypage')) forms.py: class CreateMyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['my_model_text'] tests.py: class CreateMyModelViewTests(TestCase): @classmethod def setUpTestData(cls): cls.my_auth_user = … -
Digitalocean Django Ubuntu
could someone please let me know, which command should I use for Configure the Python 3 Virtualenv ? I'm using https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html this guide, but after the command "virtualenv ." I have python 2.7 in my bin folder instead of 3+ -
Static files not found when Docker container is running in Django React app
I am trying to run my Docker image to see it on my browser yet all that appears is an empty screen, upon inspection I see the following errors: [2020-09-12 17:31:42 +0000] [12] [INFO] Starting gunicorn 20.0.4 [2020-09-12 17:31:42 +0000] [12] [INFO] Listening at: http://0.0.0.0:8000 (12) [2020-09-12 17:31:42 +0000] [12] [INFO] Using worker: sync [2020-09-12 17:31:42 +0000] [14] [INFO] Booting worker with pid: 14 Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js Not Found: /static/css/2.7253a256.chunk.css Not Found: /static/css/main.a85cbe2c.chunk.css Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js The commands I have run are: docker build . -t projecthub and docker run -d -p 8000:8000 --name theprojecthub projecthub:latest I am very unsure why these static files are even being looked for, I cannot seem to find any reference to them in my code. Does anybody know what I should do? Here is my Dockerfile: FROM stefanomil/django-npm:latest RUN mkdir usr/src/app WORKDIR /usr/src/app COPY frontend ./frontend COPY backend ./backend WORKDIR /usr/src/app/frontend RUN npm install RUN npm run build WORKDIR /usr/src/app/backend ENV DJANGO_PRODUCTION=True RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python3 manage.py collectstatic && \ python3 manage.py makemigrations && \ python3 manage.py migrate && \ gunicorn project_hub.wsgi --bind 0.0.0.0:$PORT Here are the relevant parts of my settings.py file: … -
How to display data inside query search django
i read the django docs and found a way to search database. According to docs >>> Author.objects.filter(name__contains='Terry') [<Author: Terry Gilliam>, <Author: Terry Jones>] What is want is to display all variables associated with an author. For example, Terry Gilliam name, email id, phone number, which are in my database. Instead of just displaying the following line [<Author: Terry Gilliam>, <Author: Terry Jones>] -
Django - failed registration, displaying reason back to user
I'm using the built in django user model, but having trouble feeding back to the user why their registration details are failing. In this example, i'm trying to display the reason back to the user, for why there registration has failed. For example, not meeting the models password requirements, existing user etc. I have... # forms.py - so they supply their email address for verification class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ("email",) # views.py def register(request): if request.method == "GET": return render( request, "users/register.html", {"form": CustomUserCreationForm} ) elif request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_valid = False user.save() else: messages.info(request, 'invalid registration details') return render(request, "users/register.html", {"form": CustomUserCreationForm}) How do I find out why forms.if_valid() fails, and pass it back to the user? At the moment, it just gives a generic message back, with no user feedback as to why it didn't work. Thanks -
Foreign Key to two different Django Models
For my CRM I am trying to create an History model, that should store every change or action made on a specific Ticket (aka Customer Request). In this scenario two type of users are involved: Resources and Customers. Since both can make an action that should be stored in the History table (ex. Customers can open the ticket and Resources can close it) I was wondering what is the right way to achieve this as a Foreign Key (actor) class TicketHistory(models.Model): ticket = models.ForeignKey("Tickets", on_delete=models.PROTECT, related_name="ticket") action = models.ForeignKey("HistoryActions", on_delete=models.PROTECT, related_name="action") resourceActor = models.ForeignKey("Resources", ...) customerActor = models.ForeignKey("CustomerUsers" ...) date = models.DateTimeField(auto_now_add=True) As you can see I've initially decided to create two different fields, but I don't think it is the best solution. How would you do this? -
Storing TimeSeries data with a django application in addition to using PostresQL based on performance
I need some advice. After extensive research I still don't have a clear straightforward answer. I am runnning a django app with a PostgresQL DB (AWS RDS) and I am storing TimeSeries data there and I am using REST framework as API tech. Right now I am storing the time-series data with json-fields in the PostgresQl DB. My model could be simplified like this: class TimeSeries(..): data_json = JSONField( help_text="Data for time series in JSON format. Valid JSON expected." ) Let's say in a loop I send about 30 time-series objects with about 8760 (hours p year) values in the json field ({"1":"23.12", ... {"8760":"234.11"}) the script to create the objects needs about 3min. When I send 30 time-series objects with about 525 600 values (minutes p year) the script to create the objects takes about 1hour!! To query all this data back it also takes me roughly 3-4 minutes. This is by far too long. And it won't stay with 30 objects but will increase significantly. I will create/update the hourly/minute data every day or week. I want to reduce at least the query-time to seconds or even better be instantaneously. But also the creation time. But I don't …