Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting error in Chrome browser: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found
I realize I already posted on this same subject but I think that post was too long (and I didn't get a response) so this is a condensed version. Again, I'm trying to get this app to work, it was running fine, I logged in as a superuser, made a comment, but after that I just get the error: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)$'] it says that the problem is at line 10 in my base.html, here is my base.html file, is the bootstrap cdn link no longer valid? line 10: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> base.html: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Blogging!</title> <!-- Bootstrap --> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> {# MEDIUM STYLE EDITOR#} <script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"></script> <link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Montserrat|Russo+One" rel="stylesheet"> </head> <body class="loader"> <!-- NAVBAR --> <nav class="navbar navbar-default techfont custom-navbar"> <div class="container"> <ul class="nav navbar-nav"> <li><a class= 'navbar-brand bigbrand' href="{% url 'post_list' %}">My Blog</a></li> <li><a href="{% url … -
Is there a way to add my django-tenant schema name to MEDIA_ROOT?
I have modified my Geonode project, which is a GeoDjango project, to enable multi-tenancy using django-tenants. I am currently not able to view my thumbnails due to broken routing... How do I correctly route my generated thumbnails like this: http://d3.demo.com(current_tenant_domain_url)/uploaded/d3(tenant)/thumbs/document-8a72dc8c-0151-11eb-a488-1062e5032d68-thumb.png The thubnail url that is currently generated is as follows: http://localhost:8000/uploaded/thumbs/document-fcdea3a4-015c-11eb-a488-1062e5032d68-thumb.png?v=c1855f6a urls.py urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.LOCAL_MEDIA_URL, document_root=settings.MEDIA_ROOT) My current settings.py MEDIA_ROOT = os.getenv('MEDIA_ROOT', os.path.join(PROJECT_ROOT, MEDIAFILES_LOCATION)) MEDIA_URL = os.getenv('MEDIA_URL', '%s/%s/%s/' % (FORCE_SCRIPT_NAME, MEDIAFILES_LOCATION, MULTITENANT_RELATIVE_MEDIA_ROOT)) Any help will be appreciated -
Accept only some variables in form fields from CSV and not all in Django?
I have a Django model with 2 fields as latitude and longitude. I've declared them both as a CharField. My model needs to accept more than 1 coordinates (latitude and longitude), so while entering in the rendered form (in the UI), I'm entering these coordinates separated by commas. It's this char input which I'm then splitting in the function and doing my computations.. This is my models.py class Location(models.Model): country = models.ForeignKey(Countries, on_delete=models.CASCADE) latitude = models.CharField(max_length=1000,help_text="Add the latitudes followed by comma") longitude = models.CharField(max_length=1000,help_text="Add the longitudes followed by comma") This is my view.py function def dashboard(request): form = LocationForm if request.method == 'POST': form = LocationForm(request.POST) if form.is_valid(): form.save() latitude = list(map(float, form.cleaned_data.get('latitude').split(','))) longitude = list(map(float, form.cleaned_data.get('longitude').split(','))) ......... ......... return render(request, dashboard/dashboard.html, { 'form':form }) Now, I want my model to accept the coordinates as a CSV file too. I want an option in the UI to add a CSV file (having multiple latitudes and longitudes) which then populates these two char fields (as comma-separated values). Note that, my CSV file won't have the country name. I shall be entering the country using the form UI only. Thus, in short, I need to accept some of the form fields as … -
gitignore how to exclude a table
I have a questions. So im working on my Django project for school and its almost done. And also i have to include a gitignore file which looks like this: venv/* .idea/* db.sqlite3 Nothing fancy just simple. My problem here is, that i have a table in db.sqlite3, and i need those 3 entries my project. So when somebody merges my project, the entries in this table should exist. Otherwise u just have an emtpy table and then my function on my Website is not working. I already googled for this, but i just found how to exlude files or folders. So i hope there is a solution. Anyway thanks for your help. :) -
How to create an add favorite button with ajax in Django without reloading the page?
I want to create an add favorite button in my Django project I succeed in it b8ut I want to perform this action via ajax as I don't want to reload the page when the user clicks on add favorite can you help me to convert my code with ajax so that when anyone clock on the add favorite it does not reload the page. Here are the model, URL, views, and template. Profile Model with the field favorite: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,) bio = models.TextField(max_length=350) website_url = models.CharField(max_length=350) profile_pic = models.ImageField(default='images/profile_pics/default.png', upload_to="images/profile_pics/") date_joined = models.DateTimeField(auto_now_add=True, null= True) favorites = models.ManyToManyField(Fervid) likes = models.ManyToManyField(Fervid, related_name='fervid_likes') Url for add favorite: path('favorites/', views.favorites, name='favorites'), Views function for add_favorite : @login_required def favorite(request, fervid_id): user = request.user fervid = Fervid.objects.get(id=fervid_id) profile = Profile.objects.get(user=user) if profile.favorites.filter(id=fervid_id).exists(): profile.favorites.remove(fervid) else: profile.favorites.add(fervid) return HttpResponse('<script>history.back();</script>') Add favorite functionality in my template: {% if fervid.id in ffervids %} <a class="savehrt" href="{% url 'core:fervidfavorite' fervid.id %}"><img src="{% static 'images/saved.png' %}" width=26 height=26 alt="save picture"></a> {% else %} <a class="savehrt" href="{% url 'core:fervidfavorite' fervid.id %}"><img src="{% static 'images/unsaved.png' %}" width=26 height=26 alt="save picture"></a> {% endif %} Note:-> I request you to convert this algorithm with ajax capability so that it … -
Django REST Framework class-based views inheritance
I am using Django REST Framework and I found myself in the following situation: I have two APIViews that are identical to one another except for the ordering of the objects they return: # Route: "/new" class NewView(APIView): """ Returns JSON or HTML representations of "new" definitions. """ renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def get(self, request): # Queryset definitions = Definition.objects.filter(language=get_language()) definitions = definitions.order_by("-pub_date") # HTML if request.accepted_renderer.format == "html": context = {} context["definitions"] = definitions context["tags"] = get_tags(definitions) return Response(context, template_name="dictionary/index.html") # JSON serializer = DefinitionSerializer(definitions, many=True) return Response(serializer.data) # Route: "/random" class RandomView(APIView): """ Returns JSON or HTML representations of "random" definitions. """ renderer_classes = [JSONRenderer, TemplateHTMLRenderer] def get(self, request): # Queryset definitions = Definition.objects.filter(language=get_language()) definitions = definitions.order_by("?") # HTML if request.accepted_renderer.format == "html": context = {} context["definitions"] = definitions context["tags"] = get_tags(definitions) return Response(context, template_name="dictionary/index.html") # JSON serializer = DefinitionSerializer(definitions, many=True) return Response(serializer.data) As you can see, the only line that changes between these two views is the one that orders the Definition objects. How can I create a parent view to contain the shared code and a child view to sort objects? -
DB is overwhelmed by background periodic tasks in Django App
We have a Django application that has to consume a third-party API periodically to fetch a large amount of data for a set of users. The tasks are performing fine and fullfill their purpose. But after a period of time, we start getting too many connection errors from postgres FATAL: sorry, too many clients already Info The project is dockerized and all components are running in separate containers including the app and the database (postgres). The periodic tasks are performed with dramatiq and scheduled by periodiq. We also use redis as the system broker. I have tried various workarounds to make it stop but none of them worked including various solutions proposed here in SO. Attempt 1 I have used connection.closes() before and after each task execution to make sure no ghost connections are left open by the workers. Attempt 2 Add a task limiter in order to limit the number of active connections at a given time and prevent the database from being overwhelmed. While this solution is not even serving the actual scope of our implementation as it obviously, reduces the performance of the execution of the task It did not help with the problem. Attempt 3 Increase … -
Can't connect Django and my react native app... [Network request failed]
I can't get a response from the rest API that I have created to my React Native Applications. Eventhough, I run django server and the rest api is still running, but I cant get response from rest API. The request in working on postman and I can get response there but not in react native app.I have attached my code below. Kindly, go through it React Native Code useEffect(() => { fetch('http://localhost:8000/api/movies/') .then(res => console.log(res.json)) .catch(err => console.log(err)); }, []); settings.py """ Django settings for movietracker 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/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # 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 = 'v23d&&w#*&g4q+mse7nbby4rms79(r7@feg&j1d*wf=3vq8)&4' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'api' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', … -
SystemCheckError: System check identified some issues:
I am building a project to place an order. when I run makemigrations command then it gives an error of SystemCheckError: System check identified some issues and I have deleted the migration file from migrations ERRORS: order.Order.price: (fields.E304) Reverse accessor for 'Order.price' clashes with reverse accessor for 'Order.product'. HINT: Add or change a related_name argument to the definition for 'Order.price' or 'Order.product'. order.Order.product: (fields.E304) Reverse accessor for 'Order.product' clashes with reverse accessor for 'Order.price'. HINT: Add or change a related_name argument to the definition for 'Order.product' or 'Order.price'. My models.py is as follows: class Order(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.company + self.product + self.price -
How do I POST a json file to Django and MySQL containing a base64 image string? (also using NGINX and Angular)
I've been trying to post this for days but haven't had any luck. Post method: public postDict(name: any, postData: Object) { var key = localStorage.getItem("access") var httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key, }), }; return this.http .post<any>( 'http://example.com:80/images/', putData, httpOptions ) .subscribe((data) => { console.log("sup") }); /* The data I'm sending looks like this in Angular: let item = {key: imgTimeKey, url: this.imgURL , owner: 'idiot'} where url is: data:image/jpeg;base64,/9j/...( bout 5mb worth of characters after this D-8 ) I've gotten past the problem of transmitting so much data in one post, but now its giving me a 404 Bad Request error. (It works if I replace the url with a regular string.) Now I have been storing these as regular strings in indexeddb just fine and I figure it should work the same with Django and MySQL. It should be fine to store the url in a string no? Here is my data model in Django: from django.db import models class Image(models.Model): created = models.DateTimeField(auto_now_add=True) key = models.CharField(max_length=100, blank=True, default='') url = models.TextField() owner = models.ForeignKey('auth.User', related_name='images', on_delete=mod> class Meta: ordering = ['created'] And finally, my NGINX server configuration: server { listen … -
How to run .py files as cronjob in aws?
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.1.1). I have been trying to run a .py file as a cronjob that works at 4 a.m every day in AWS and I have created a .config file into .ebextensions for that such as below. cron.config file: files: "/etc/cron.d/cron_process": mode: "000644" owner: root group: root content: | 0 4 * * * root /usr/local/bin/task_process.sh "/usr/local/bin/task_process.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date source /var/app/venv/staging-LQM1lest/bin/activate cd /var/app/current python Bot/run_spiders.py exit 0 commands: remove_old_cron: command: "rm -f /etc/cron.d/cron_process.bak" run_spiders.py file: from first_bot.start import startallSpiders from .models import Spiders import importlib test = Spiders.objects.get(id=1) test.spider_name = "nigdehalk" test.save() I'm trying to change an attribute of one of my objects for testing but it didn't work. Am I missing something? How can I create this cronjob? -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(h_code): testhospital = HospitalList.objects.filter(code = h_code).values('code') print(testhospital) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'h_code' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I have to specify it? (Some code has been omitted to make it easier to see.) view.py (add) class ListDoctor(generics.ListCreateAPIView): queryset = DoctorList.objects.all().order_by('-d_code') serializer_class = DoctorListSerializer -
Celery task can't access volume file in docker
Admin page can get access to the image file saved in database but Celery task can't get access to that image file and shows error FileNotFoundError(2, 'No such file or directory'). docker-compose.yml version: "3" services: app: &app build: context: . ports: - "8000:8000" volumes: - ./backend:/backend command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - SECRET_KEY=mysecretkey - DB_HOST=db - DB_NAME=election - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db - redis db: image: postgres:12-alpine environment: - POSTGRES_DB=election - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword volumes: - postgresql_data:/var/lib/postgresql/data ports: - 5432:5432 redis: image: redis:6-alpine celery: <<: *app command: celery -A app worker -l INFO ports: [] depends_on: - app - redis - db volumes: postgresql_data: Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 # Face-recognition model RUN apt-get -y update RUN apt-get install -y --fix-missing \ build-essential \ cmake \ gfortran \ git \ wget \ curl \ graphicsmagick \ libgraphicsmagick1-dev \ libatlas-base-dev \ libavcodec-dev \ libavformat-dev \ libgtk2.0-dev \ libjpeg-dev \ liblapack-dev \ libswscale-dev \ pkg-config \ python3-dev \ python3-numpy \ software-properties-common \ zip \ # web3 libssl-dev \ # QR code zbar-tools \ libzbar-dev \ && apt-get autoremove \ && apt-get clean && rm -rf /tmp/* /var/tmp/* … -
django-parler-rest avoiding "translations" objects
While I'm creating an app by using django-parler-rest for internationalization support I realized that TranslatedFieldsField and TranslatableModelSerializer serialize the data in the following format: { "id": 528, "country_code": "NL", "translations": { "nl": { "name": "Nederland", "url": "http://nl.wikipedia.org/wiki/Nederland" }, "en": { "name": "Netherlands", "url": "http://en.wikipedia.org/wiki/Netherlands" }, "de": { "name": "Niederlande", "url": "http://de.wikipedia.org/wiki/Niederlande" } } } Is there any way to serialize the data in the following format? { "nl": { "id": 528, "country_code": "NL", "name": "Nederland", "url": "http://nl.wikipedia.org/wiki/Nederland" }, "en": { "id": 528, "country_code": "NL", "name": "Netherlands", "url": "http://en.wikipedia.org/wiki/Netherlands" }, "de": { "id": 528, "country_code": "NL", "name": "Niederlande", "url": "http://de.wikipedia.org/wiki/Niederlande" } } -
Why click on profile page, home page load as well using django jsonResponse and javascript API fetch to display the view
I want to display different data for the homepage and the profile page. The homepage should have all the posts while profile page has only the logged-in user's page. The data itself is ok. I have tested in django and javascript using print and console.log(). The problem is when I load the profile page, the homepage load again as well, so the profile view has both homepage and profile posts. And also if I click homepage twice, I get twice of the posts on homepage. Here below is my code. Any help is appreciated. Thanks! Javascript: document.addEventListener("DOMContentLoaded", function () { // Use button to toggle between views document.querySelector("#home").addEventListener("click", () => { load_view("home"); document.querySelector("#happening_form").style.display = "block"; document.querySelector("#home_view").style.display = "block"; document.querySelector("#profile_view").style.display = "none"; }); document .querySelector("#all_posts") .addEventListener("click", () => load_view("all_posts")); document .querySelector("#following") .addEventListener("click", () => load_view("following")); document.querySelector("#profile").addEventListener("click", () => { load_view("profile"); document.querySelector("#post_middle_container").style.display = "none"; document.querySelector("#happening_form").style.display = "none"; document.querySelector("#home_view").style.display = "none"; document.querySelector("#profile_view").style.display = "block"; }); // Prevent default upper submit document .querySelector("#upper_post_form") .addEventListener("submit", function (event) { event.preventDefault(); }); // Prevent default popup submit document .querySelector("#popup_post_form") .addEventListener("submit", function (event) { event.preventDefault(); }); // By default, load all posts view load_view("home"); // By default, load post composing form compose_post(); }); ...........// compose and submit functions … -
Access Django Admin with token instead of password
I use Django with Django Rest Framework as the backend for my site. Registration is disabled, and login with password is disabled. The only way a user can register and login is with Django Social Auth, that exchanges (in this case Discord) a social token for a Django token, and in that process the user is created if they don't exist for that email. So in Django, the user exists, with a username and email, but they don't have a password. How can these users login to the admin panel? -
How to filter data from Mongo DB in Django
I use Djongo as the connector for mongoDb with Django. But I dont know how to get all the data with filter. I get int error while trying to do that. class HomeView(LoginRequiredMixin, ListView): template_name = 'home.html' getter = PostModel.objects.filter(author='1') model = getter login_url = reverse_lazy('login') This is my code for getting the data. But it says. 'QuerySet' object has no attribute '_default_manager' What am I doing wrong here. Please help me. -
How to search query sets that have a specific value in a list in Django Rest framework
What I want to do Getting all query set which has a specific value in a list which is ManyToManyField. In short, if I type http://localhost:8000/api/pickup/?choosingUser=5, I would like to get all PickUp_Places that matches like choosingUser = 5. choosingUser comes from ManyToManyField so a PickUp_Places model has like choosingUser = [2,3,5,7]. Problem I cannot search query sets by a specific value in list. When I type http://localhost:8000/api/pickup/?choosingUser=5, I get all query sets that include ones don't have choosingUser = 5. I am using django_filters in order to filter query sets. I read the documentation but I couldn't find how to get query sets by a value in a list. If it is alright with you, would you please tell me how to do that? Thank you very much. ===== ========= ========== ========= My code is like this. models.py class PickUp_Places(models.Model): name = models.CharField(max_length=200, unique=True) choosing_user = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="pick_up") def __str__(self): return self.name class Meta: db_table = "pickup_places" serializers.py class PickUp_PlacesSerializer(serializers.ModelSerializer): class Meta: model = PickUp_Places fields = "__all__" views.py class PickUp_PlacesViewSet(viewsets.ModelViewSet): queryset = PickUp_Places.objects.all() permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] serializer_class = PickUp_PlacesSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = "__all__" -
Best way of checking whether a certain Model instance is in fact an instance of a certain Model
I am trying to write a class that takes an instance of a Model from my app as an argument in its __init__. While reading up on the subject, I stumbled upon this quesiton: django: best practice way to get model from an instance of that model which argues that simply using type(instance) would be the best way to go. As tempting as it may be to use this right away, wouldn't using isinstance(instance, model) be a better solution? Say, for example (from my own code): from app_name.models import Model1, Model2, ... ModelN MODELS = (Model1, Model2 ... ModelN) and then inside the class itself (in my case, Graph), do something like this: class Graph(): model_instance = None model = None def __init__(self, model_instance): if isinstance(model_instance, MODELS): for a_model in MODELS: if isinstance(model_instance, a_model): self.model = a_model self.model_instance = model_instance ... As a beginner, I thought this was the best way I could come up with but also assume there are smoother/better ways of doing this. Possibly an even more "readable" way maybe? Pros? Cons? Appreciate ALL feedback on this! Thanks! -
form errors do not show on the template
Non of my validation errors show, the template page just refreshes if there is something wrong. i placed the validation error code in my forms.py, i don't know if i am supposed to place it in my views, because nothing works. i also thought django had a default for errors, seems i was wrong. html <form method="post"> {%csrf_token%} <form method="post">{%csrf_token%} {{form.username}} {{form.first_name}} {{form.last_name}} {{form.email}} {{form.phonenumber}} {{form.state}} {{form.next_of_kin}} {{form.dob}} {{form.address}} {{form.password1}} {{form.password2}} <li class="btnn"><button type="submit" class="conf">Add</button></li> </form> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{error}} </p> {% endfor %} {% endfor %} {% endif %} forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class PatientForm(UserCreationForm): first_name = forms.CharField(max_length=100, help_text='First Name') last_name = forms.CharField(max_length=100, help_text='Last Name') address = forms.CharField(max_length=100, help_text='address') next_of_kin = forms.CharField(max_length=100, help_text='Next of kin') dob = forms.CharField(max_length=100, help_text='Date of birth') state = forms.CharField(max_length=100, help_text='State') phonenumber = forms.CharField( max_length=100, help_text='Enter Phone number') email = forms.EmailField(max_length=150, help_text='Email') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'placeholder': ('Username')}) self.fields['email'].widget.attrs.update( {'placeholder': ('Email')}) self.fields['address'].widget.attrs.update( {'placeholder': ('Address')}) self.fields['phonenumber'].widget.attrs.update( {'placeholder': ('Phone number')}) self.fields['first_name'].widget.attrs.update( {'placeholder': ('First name')}) self.fields['last_name'].widget.attrs.update( {'placeholder': ('Last name')}) self.fields['password1'].widget.attrs.update({'placeholder': ('Password')}) self.fields['password2'].widget.attrs.update({'placeholder': ('Repeat password')}) self.fields['dob'].widget.attrs.update({'placeholder': ('Date of birth')}) self.fields['state'].widget.attrs.update({'placeholder': ('State')}) self.fields['next_of_kin'].widget.attrs.update({'placeholder': ('Next … -
Django form submit button doing nothing
I'm trying to upload a csv file to insert into the model I created since the data in the csv is quite a lot I cannot manually input it all. I've watched a tutorial and I kinda copy pasted every detail the tutorial gave, the problem is when I'm click the upload button, nothing happens. Models.py class Dev(models.Model): projName = models.CharField(max_length=255) clientName = models.CharField(max_length=255) projDesc = models.CharField(max_length=255) projTask = models.CharField(max_length=255) userName = models.CharField(max_length=255) userEmail = models.CharField(max_length=255) projTag = models.CharField(max_length=255) billable = models.BooleanField() dateStart = models.DateField(auto_now=False, auto_now_add=False) timeStart = models.DateTimeField(auto_now=False, auto_now_add=False) dateEnd = models.DateField(auto_now=False, auto_now_add=False) timeEnd = models.DateTimeField(auto_now=False, auto_now_add=False) timeDuration = models.DateTimeField(auto_now=False, auto_now_add=False) duration = models.DecimalField(max_digits=4, decimal_places=2) billRate = models.DecimalField(max_digits=10, decimal_places=2) billAmount = models.DecimalField(max_digits=10, decimal_places=2) and here is the views.py from django.shortcuts import render from django.http import HttpResponse import csv, io from django.contrib import messages from django.contrib.auth.decorators import permission_required from .models import Dev # Create your views here. def homepage(request): return render(request, 'Home.html') @permission_required('admin.can_add_log_entry') def csv_upload(request): template = "upload.html" prompt = { 'order': 'Order of the CSV chuchu' } if request.method == "GET": return render(request, template, prompt) csv = request.FILES['file'] if not csv.name.endswith('.csv'): message.error(request, 'Not a csv file, please choose another file.') data_set = csv.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for col … -
How To Configure Apache To Point To Media Files
My website isn't finding my media files in production and I think it's because I need to configure my webserver to point to my media root file, I think with the following code: Alias /media /home/atms/atms/media <Directory /home/atms/atms/media> Require all granted </Directory> However I have no idea where to place this code? Apparently it goes in a file 'htaccess', but I can't find this file. I am using A2 hosting. Thank you. -
How to add Django model ImageField to ReportLab
I would like to add a media file to PDF generated by Reportlab. STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") output STATIC_ROOT --> project/static/ MEDIA_ROOT = os.path.join(BASE_DIR, "media") output STATIC_ROOT --> project/media/ when i draw static images are ok: logo = STATIC_ROOT + "img/dilains-logotipo-bg-white-290x100.jpg" self.canvas.drawImage(logo, self.x, self.y, w, h, preserveAspectRatio=True) but with media: output self.rejection.img_general_model_1 --> images/treatments/rejections/mouth.jpg picture = MEDIA_ROOT + str(self.rejection.img_general_model_1) self.canvas.drawImage(picture, self.x + text_x * 0, self.y, w, h, preserveAspectRatio=True, mask='auto') Throws error: Cannot open resource "/project/media/images/treatments/rejections/mouth.jpg" <class 'OSError'> Anybody know how to fix it ? And in production with AWS S3 configuration ? Thanks in advance. -
form submitted data from template is not saved in database in Django?
I was doing a small project on django where i create simple blog mini project. Everything worked for me but i am in issue now that i can create post form Django administration and i wanted to do it with in front-end with templates in create-post.html but i am no issue just my form is not working or it is not submitting any data or some error ? I'm using summernote rich text editor instead of textfield in Model. Expert please look my code and suggest me it is good or bad or where i am wrong ? my models.py class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) author_profile_pic = models.ImageField(upload_to='images',null=True) author_description = models.TextField(null=True) author_facebook_url = models.CharField(max_length=50,null=True) author_twitter_url = models.CharField(max_length=50,null=True) author_instagram_url = models.CharField(max_length=50,null=True) author_github_url = models.CharField(max_length=50,null=True) def __str__(self): return f'{self.user}' class Category(models.Model): # show string title in Admin panel title = models.CharField(max_length=30,null=True) def __str__(self): return self.title class Blogpost(models.Model): title = models.CharField(max_length=100,null=True) thumbnail = models.ImageField(upload_to='images') post_body = models.TextField() slug = models.SlugField(null=True,blank=True) posted_date = models.DateField(default=date.today) author = models.ForeignKey(Author, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) publish = models.BooleanField() and my form from django import forms from .models import Blogpost from django_summernote.widgets import SummernoteWidget class CreatePostForm(forms.ModelForm): class Meta: model = Blogpost fields = "__all__" widgets = { 'post_body': … -
How to count data from Another Model in Django?
I have 2 models and i want to count Foreignkey data, I am trying to count the number of records in related models, but I am unable to count the records, Please let me know how i can Count the data. I want to count this data after filter, I am filtering between 2 dates, it's giving me the current data of using model in filter,but i want to count related model data also using filter. Here is my models.py file... class Product(models.Model): name=models.CharField(max_length=225) customer=models.ForeignKey(Brand, related_name='product_customer',on_delete=models.CASCADE) user= models.ForeignKey(Supplement, related_name='product_user', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) here is my views.py file... def index(request): data = Project.objects.all() if request.method == 'POST': v1= request.GET.get('created-at') if v1: v2 = v1.split(' - ') s1 = v2[0] s2 = v2[1] result = Product.objects.filter(created_at__range=[s1,s2]) return render(request, 'index.html' {'result':result}) here is my index.html file.. <p>{{result.count}} product</p> <p>{{result.product_customer.count}} Customer</p> <p>{{result.product_user.count}} User</p> I want to display this data after filter, for product it's working perfect, but i want to display data for customer and user when user filter...