Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
done with website pages in html, now how to create user registration,views,urls to run website on loca host
how to write views, URLs to access shopping page on the localhost. italic_ and bold text, inline code in backticks, and basic links. -
GraphQL-"Unknown argument \"country\" on field \"allNews\" of type \"Query\".",
GraphQL newbie here. So I was trying to write a schema in Django using graphene which will take country parameter as a String & time parameter as Character. The query works fine with the "time" parameter, but whenever I add the "country" param. it throws the following error "Unknown argument \"country\" on field \"allNews\" of type \"Query\".",. Here is my Schema and Type: Type: class NewsType(DjangoObjectType): class Meta: model = News fields = ('id', 'site_name', 'title', 'link', 'content', 'thumbnail', 'status', 'upvote', 'downvote', 'published_date', 'paper', 'created_date') filter_fields = ['site_name', 'status', 'country'] interfaces = (CustomNewsNode, ) vote_status = DjangoFilterConnectionField(UserVoteNewsType) def resolve_vote_status(self, info, user_id): return self.uservotenews_set.filter(user_id=user_id) Schema: class NewsTypeFilter(django_filters.FilterSet): class Meta: model = News fields = ['id', 'site_name', 'title', 'link', 'content', 'thumbnail', 'status', 'upvote', 'downvote', 'published_date', 'paper', 'created_date'] class Query(graphene.ObjectType): all_news = DjangoFilterConnectionField( NewsType, filterset_class=NewsTypeFilter, time=graphene.String()) def resolve_all_news(self, info, **kwargs): print(kwargs['country']) env = environ.Env() environ.Env.read_env() HOURS_AFTER_NEWS_VISIBLE = env('HOURS_AFTER_NEWS_VISIBLE') timeDiff = datetime.now() - timedelta(hours=int(HOURS_AFTER_NEWS_VISIBLE)) if kwargs['time']: # if user clicks on sort by button if(kwargs['time'] == 'd'): time = 1 elif (kwargs['time'] == 'w'): time = 7 elif (kwargs['time'] == 'm'): time = 30 elif (kwargs['time'] == 'y'): time = 365 else: time = 1000 end_of_give_time_period = datetime.now( ) - timedelta(days=int(HOURS_AFTER_NEWS_VISIBLE)) start_of_given_time_period = end_of_give_time_period … -
Does anyone know how to make an ocr reader in django 3.0.0?
does anyone know any tutorials on how to turn get texts from pictures/ pdfs and display it onto Django forms? -
Is it possible to do end to end testing with a Django app and React app?
We have two separate apps, one is our API which is using Django 2.2.2 and a React 16.9 app. Currently the API is very well tested, but it's not tested with our react app. What I'd like to do is, prior to merging into our develop branch, a full end to end test. So when a PR is made into develop a script will run that would launch a test server and db and then the react app would be able to use something like Cypress to test against the API. -
Working with forms in Django and checking if all the input fields are entered
I have created a contact page and there I created a form that looks like this Now I want that 'submit' button to check whether all the input fields are entered. If it is then I want to activate the Otherwise no post method activation. Instead a popup message box will appear telling that "Please enter all the fields" If post method is activated, I want to go to the {% url 'contact' %} that is my views.py file and check if the system is able to retrieve all the values from the input fields. If it does it will render a fresh contact page return render(request, 'myapp/contact.html') And popup another message box to the browser that "Form is submitted successfully" Else another message box to the browser that "There is an error occurred submitting the form" I really can't find a way to implement this. I am a newbie is Django and Python. I have very minimum experience in html and CSS. But no JavaScript, though I used a small JavaScript code, I wish to completely use Python, HTML and CSS. Is that possible to implement this scenario using my desired language? If yes, please tell me how. -
apply a filter to a child in a loop in Django
This is driving me mad (I really have looked everywhere - but I know it must be easy and I'm just being a tad think) How do I add a filter to a child of a parent (one to many)? The code below provides a list of companies in a table, then on the same page/ table, each company has a list of "charges" which is attributed to that company; thanks to the ForeignKey and using "charge_set" it works great. However, I would like to add a filter to the "charges" for status (so exclude "outstanding" status) In ROR I would have simply placed the following <% company.charges.where(status: "Outstanding").each do |charge| %> AIUI, I can't do this with Python/ Django in the view; so how would I go about adding a simple filter to the child of the parent within this loop? from django.db import models class Company(models.Model): name = models.CharField(max_length=100) class Charge(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) charge_id = models.CharField(max_length=100) status = models.CharField(max_length=100) from django.shortcuts import render from companies.models import Company, Charge, Filing from django.http import HttpResponse def watch_list(request): companies = Company.objects.order_by('-data_date') return render(request,'company_watch/watch_list.html',{'companies':companies}) {% for company in companies %} <tr> <td>{{company.name}}</td> <td> <ul> {% for charge in company.charge_set.all %} … -
How to run django and wordpress with nginx
I'm having problem with configuring my nginx.conf file to run django server on main domain and a wordpress site on domain.com/blog this is my configuration file whitch my wordpress dir is /var/www/varzesh-kon/blog/ ''' upstream Main_Project_server { server unix:/home/amirfarsad/django_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 2n9l.s.serverhost.name; client_max_body_size 4G; access_log /home/amirfarsad/logs/nginx-access.log; error_log /home/amirfarsad/logs/nginx-error.log; location /static/ { alias /home/amirfarsad/Main_Project/static/; } location /media/ { alias /home/amirfarsad/Main_Project/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://Main_Project_server; break; } } location /blog/ { root /var/www/varzesh-kon/blog/; index index.php index.html index.htm; try_files $uri =404; } location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; root /var/www/varzesh-kon/blog/; } } ''' my django side works well but when I go to domain.com/blog url it gives me a 404 notfound nginx page -
How to bring div to front
I have a preloader I am trying to bring to the front but the content which is loaded as {% block content %}{% endblock %} as well as the <header></header> are showing up in front of this loader. This loader currently exists in the <head></head> of the page.. html: <div class="flex-center" id="preloader"> <div class="preloader-wrapper active"> <div class="spinner-grow text-warning" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> css: #preloader:before { content: ''; z-index: 999; display: block; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,1); } #preloader.loaded { opacity: 0; transition: .3s ease-in 1s; } jquery: $(window).on('load', function() { $('#preloader').addClass('loaded'); }); How do I make the preloader cover up everything during page load? -
how to install virtual environment in django and flask on same machine
I have already installed it(virtual environment) for django few days ago. I want to install it again separately for flask now. But it's not working. Please, help. Please note, it's windows os. -
over-riding django-rest-auth email_confirmation_message not working
I am trying to override the email confirmation message in my templates. when I created the email_confirmation_message.txt file, it successfully overrode it, but when I change it from txt to html. it goes back to all auths default txt template below is what my template looks like {% load account %} {% user_display user as user_display %} {% load i18n %} {% autoescape off %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Confirm Your E-mail</title> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% blocktrans with site_name=current_site.name site_domain=current_site.domain %} <p class="title">Email Verification</p> <p class="intro">Hello there,</p> <p class="main-body"> Simply click on the button to verify your cre8ive-mart email. </p> <a href="{{ activate_url }}" class="cta-button">Verify email</a> <p class="sub-body"> if you have any questions, please contact <a href=""></a> </p> <div class="outro"> <p class="outro-greeting">Sincerely,</p> <p class="outro-main">cre8ive-mart</p> <a href="#" class="outro-website">cre8ivemart.com</a> </div> {% endblocktrans %} </body> </html> {% endautoescape %} the file path and name is templates/account/email/email_confirmation_message.html I have no idea why it doesn't override it, please help. -
Django form is being validated before it is submitted
I have a custom bootstrap form which is displayed in the Dashboard. The problem is, that when the user goes to the dashboard, he sees validation errors right away, even though he did not submit the form yet (the text field should be required). I do not understand why this is happening, any help is appreciated! :) Picture of the problem (I do not want the red "The field is required" message to display now, only after submitting): Form: class MinitaskForm(forms.ModelForm): class Meta: model = Minitask fields = () def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, minitask=None): super().__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted, instance, use_required_attribute) assert minitask is not None self.fields["selected_choice"] = forms.CharField( widget=forms.RadioSelect(choices=[ (val, val) for val in minitask.choices ]), required=False, label="Which of these emotions best describes your day?") self.fields["reason"] = forms.CharField(label="Why?") Views: @login_required(login_url="login") def dashboard(request): task = request.user.current_weekly_task() user_id = request.user.id solutions = Solution.objects.filter(user_id=user_id) minitask = request.user.current_minitask() minitasks = request.user.minitask_set.filter(selected_choice__isnull=False) if request.method == "POST": if "minitask" in request.POST: form = MinitaskForm(request.POST, minitask=minitask) if "selected_choice" not in request.POST: form.add_error("selected_choice", "Can't be blank") messages.error(request, "You must pick your today's emotion") if form.is_valid(): minitask.reason = request.POST["reason"] minitask.selected_choice = request.POST["selected_choice"] minitask.user = request.user minitask.save() messages.success(request, … -
How to access model.field in template? django
I started learning django few days ago and trying to build my first blog. My problem is that I decided to add an extra field for my categories (subheading), which I want to be in my template, but can't understand how to do it. my models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=20) subheading = models.CharField(max_length=160) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() link = models.TextField() categories = models.ManyToManyField("Category", related_name="posts") def __str__(self): return self.title views.py from django.shortcuts import render from blog.models import Post, Category def blog_category(request, category): posts = Post.objects.filter( categories__name__contains=category ).order_by( 'title' ) context = { "category": category, "posts": posts } return render(request, "blog_category.html", context) The only way category.name or category.subheading are displayed in template (by the teacher) is inside {% for post in posts %} {% endfor %}: {% for post in posts %} {% for category in post.categories.all %} {{ category.subheading }} {% endfor %} {% endfor %} In this case, if there are 10 posts on category page, subheading repeats 10 times. I only need to print 1 to describe category. Is there a way to call category.subheading outside of {% for post in posts %} ? Or somehow … -
Django model FloatField error 'float' object has no attribute 'as_tuple'
I have a Django model with a FloatField, which I later base a form on. For some reason I get "'float' object has no attribute 'as_tuple'", and unfortunately I have no idea why do I get this error or how to fix it. models.py: class Course(models.Model): title = models.CharField(max_length = 200) author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT) description = models.TextField(max_length=1000, blank=True) tags = models.TextField(blank = True) duration = models.FloatField(validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2))) def __str__(self): return self.title forms.py: class CourseForm(ModelForm): class Meta: model = Course fields = ('title', 'description', 'price', 'duration', 'tags') views.py: @login_required def create_course(request): if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): form.save() messages.info(request, f"Course created succesfully!") else: messages.error(request, "Something went wrong, please resubmit!") form = CourseForm() return render(request, "main/createcourse.html", {"form": form}) html: {% extends 'main/header.html' %} <body> {% block content%} <div class="container"> <form method="POST"> {% csrf_token %} {{form.as_p}} <br> <button class="btn" type="submit">Create</button> </form> If you to modify an existing course, click <a href="/modify"><strong>here</strong></a> instead. </div> <br><br> {% endblock %} </body> -
How can I separate HH and MM in datetime in django
I saved the datetime in my model and now I have this ---> Feb. 1, 2020, 10:11 p.m. How can I reach this? ---> 10:11 p.m -
How to change the name or alias a python module
I am using a python app, via django, that requires Pillow, and I have installed it via pip. However, when the framework loads it complains that Pillow is not installed. I can verify this when trying import pillow fails. If I look at the directory that contains the python modules I see there is no "pillow", but there is "PIL". I understand that pillow is a fork of PIL, and I can import PIL (PIL appears in a list of modules within python >>> help() >>> modules). Without touching the framework, is there a way to convince the app/django that PIL == pillow. I tried import PIL as pillow in a settings file, but that didn't solve the problem. Thanks -
is django overkill for a contact us website?
I'm a complete beginner and a relative of mine asked me to build a simple 'contact us' website for them. It should include some information about his company and a form in which people that visit the website are able to send mails to my relative. I have been playing around with vue.js in order to build the frontend. I now want to know how to put the form to send mails and I read it has to be done with backend, so I thought I could use django as I have played with it in the past and I am confident using python. Is it too much for the work that I have to do? Should I use something simpler? I accept any suggestions please, Thanks. -
Django LoginView print user input
I want to print login that user input in login_form. I read in documentation link that LoginView contains field form. And tried to fetch data from this field. Also tried fetch login from request, but it contains only AnonymousUser views.py class BBLoginView(LoginView): template_name = 'vacancy_list/login.html' def post(self, request, *args, **kwargs): print("SSSS", self.form) log_to_file("{};{};LOGIN;\n".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), request.user)) return super().post(request, *args, **kwargs) login.html {% extends 'vacancy_list/base.html' %} {% load bootstrap4 %} {% block content %} <div class="container" style="margin-top:10px"> <h2>Login</h2> {% if user.is_authenticated %} <p>You are already registered</p> {% else %} <form method="post"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} <input type="hidden" name="next" value="{{ next }}"> {% buttons submit="Submit" %} {% endbuttons %} </form> {% endif %} </div> {% endblock %} -
What the last line in custom DRF permission mean
This is a snippet from the Django rest framework documentation on writing custom permissions. I don't understand the meaning of the last line here: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user -
User registered but not authenticated after login
i am creating simple website in Django, i am a beginner. Now i am creating registration and login options, but authentication does not work for me (i know it because in logged_in.html there is not displaying username name). views.py from django.shortcuts import render, render_to_response, get_object_or_404, redirect from django.http import HttpResponse from django.contrib import auth from django.contrib.auth import authenticate, login from django.template.context_processors import csrf from django.http import HttpResponseRedirect from django.template import RequestContext from MySite.forms import RegistrationForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User def register_user(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('register_success') args = {} args.update(csrf(request)) args['form'] = RegistrationForm() return render_to_response('register_user.html', args) def register_success(request): return render_to_response('register_success.html') def login_user(request): login_user = {} login_user.update(csrf(request)) return render_to_response('login_user.html', login_user) def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('logged_in') else: return HttpResponseRedirect('invalid_login') def logged_in(request): return render_to_response('logged_in.html', {'full_name': request.user.username})` urls.py from django.contrib import admin from django.urls import include, path from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('MySite/', include('MySite.urls')), path('accounts/', include('django.contrib.auth.urls')), ] MySite.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register_user', views.register_user, name='register_user'), path('register_success', views.register_success, name='register_success'), path('login_user', views.login_user, name='login_user'), … -
Django returning ManyToMany field as model name in database
I'm wonder if this is possible. Imagine that I have model with foreignkey to User and ManyToMany field holding some sort of objects from different model. Is it possible to display the particular name from ManyToMany in django-admin web, showing the name of the object with has been assigned to particular User ? -
Convert object data to html in python
i want to convert this to html tag with django template code in view: def selectbeds(request): """Docstring.""" try: all_beds = Beds.objects.all() all_beds_seri = serializers.serialize('json', all_beds) all_beds_json = json.loads(all_beds_seri) data = json.dumps(all_beds_json) table = json2html.convert(json=data) return render(request, 'beds_show.html', {'context': table}) except Exception as e: return HttpResponse(e.args) -
Getting "OSError: mysql_config not found" when trying to build a Docker image for my Python 3.7/Django project
I'm using Python 3.7 and Django 2. I have the following requirements.txt file, exported from my current project ... asgiref==3.2.3 Babel==2.8.0 Django==2.0 django-address==0.2.1 django-mysql==3.3.0 django-phonenumber-field==4.0.0 mysqlclient==1.4.6 phonenumbers==8.11.2 pycountry==19.8.18 pytz==2019.3 PyYAML==5.3 ruamel.yaml==0.16.6 ruamel.yaml.clib==0.2.0 sqlparse==0.3.0 I would like to create a docker image to run my Django virutal environment. I have this Dockerfile ... FROM python:3.7-slim RUN python -m pip install --upgrade pip COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY . . However I'm getting this error when I attempt to build the image. I'm not certain what it means. I can run the server (python manage.py runserver 8000) without problems so not sure why my virtual environment is dying ... (venv) localhost:web davea$ docker build . Sending build context to Docker daemon 132.5MB Step 1/5 : FROM python:3.7-slim ---> f2d2e1dc8c72 Step 2/5 : RUN python -m pip install --upgrade pip ---> Using cache ---> cf901765d254 Step 3/5 : COPY requirements.txt requirements.txt ---> Using cache ---> e4770d5b0c4a Step 4/5 : RUN python -m pip install -r requirements.txt ---> Running in d4d937c92f06 Collecting asgiref==3.2.3 Downloading asgiref-3.2.3-py2.py3-none-any.whl (18 kB) Collecting Babel==2.8.0 Downloading Babel-2.8.0-py2.py3-none-any.whl (8.6 MB) Collecting Django==2.0 Downloading Django-2.0-py3-none-any.whl (7.1 MB) Collecting django-address==0.2.1 Downloading django-address-0.2.1.tar.gz (16 kB) Collecting django-mysql==3.3.0 Downloading … -
call command wait for DB is failing
keep getting an errror wile calling this command for wai_for_db. im really lost on this. any advise ???? --------------error log from CMD------------------------------------------------------------------------- C:\Users\Ayman.Judeh\Desktop\API TDD\course\external_feed_api>docker-compose run app sh -c "python manage.py test && flake" Starting external_feed_api_db_1 ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). ...EE.... ERROR: test_wait_for_db (core.tests.test_commands.CommandsTestCase) Test waiting for db Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 102, in call_command app_name = get_commands()[command_name] KeyError: 'wait_for_db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/unittest/mock.py", line 1255, in patched return func(*args, **keywargs) File "/app/core/tests/test_commands.py", line 32, in test_wait_for_db call_command('wait_for_db') File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 104, in call_command raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'wait_for_db' ====================================================================== ERROR: test_wait_for_db_ready (core.tests.test_commands.CommandsTestCase) when we call the command the DB is already availabe Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 102, in call_command app_name = get_commands()[command_name] KeyError: 'wait_for_db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/core/tests/test_commands.py", line 23, in test_wait_for_db_ready call_command('wait_for_db') File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 104, in call_command raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'wait_for_db' Ran 9 tests in 1.055s FAILED (errors=2) Destroying test database for alias 'default'... … -
Diagnosing degraded postgresql performance
In a Django web app with a postgresql backend (and nginx reverse proxy with gunicorn application server), I'm seeing dozens of COMMIT messages in postgresql's slow log. Behold: 2020-02-01 17:56:16.335 UTC [19424] ubuntu@app LOG LOG: duration: 175.630 ms statement: COMMIT 2020-02-01 17:56:21.355 UTC [19435] ubuntu@app LOG LOG: duration: 107.735 ms statement: COMMIT 2020-02-01 17:57:22.592 UTC [19419] ubuntu@app LOG LOG: duration: 235.313 ms statement: COMMIT 2020-02-01 17:57:30.685 UTC [19419] ubuntu@app LOG LOG: duration: 249.875 ms statement: COMMIT 2020-02-01 17:57:30.688 UTC [19424] ubuntu@app LOG LOG: duration: 99.049 ms statement: COMMIT 2020-02-01 17:57:30.688 UTC [19435] ubuntu@app LOG LOG: duration: 115.772 ms statement: COMMIT 2020-02-01 17:57:30.688 UTC [19554] ubuntu@app LOG LOG: duration: 248.656 ms statement: COMMIT 2020-02-01 17:58:03.266 UTC [19435] ubuntu@app LOG LOG: duration: 780.232 ms statement: COMMIT 2020-02-01 17:58:03.270 UTC [19424] ubuntu@app LOG LOG: duration: 622.424 ms statement: COMMIT 2020-02-01 17:58:07.579 UTC [19435] ubuntu@app LOG LOG: duration: 75.658 ms statement: COMMIT The DB in question was just migrated from one dedicated server to another a day ago. In its previously environment, COMMIT never showed up in slow log. In the new environment, I made some changes: 1) I set checkpoint_completion_target = 0.7 (down from checkpoint_completion_target = 0.8 previously) 2) I switched to gevent … -
Possible to replicate this form in Django?
There is a form I'm trying to figure out the best way to replicate so that I can take the data and use it to create configurations. The form however has elements in which multiple ports and server names can be associated to a single item, say the FQDN in this case. I don't know what you would call this however so I am not sure what I need to search on for a better understanding of how to recreate this. I've been learning a little about forms in Django and taking some online classes but nothing has so far covered a similar scenario, it's all just single items associated together. They say a picture is worth a thousand words, so let me show you the form I'm hoping to recreate: Questions: 1) Technically possible to recreate in Django? 2) If technically possible, is Django a good choice for doing this? 3) When it comes to the ability to associate multiple ports, servers to a single entry (FQDN) what is that called in Django/Form speak? I need something I can search to learn more about. 4) Any suggestions of where I can find related examples possibly?