Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth facebook not working with web.facebook.com
All auth is working fine with regular internet but whenever there's someone using a mobile data facebook works via web.facebook.com url and how do I fix my website to handle that subtle change in the url becuase authentication call back gives out error while login using facebook however google is working fine. -
Field 'id' expected a number but got <QuerySet [<Department: GEE>]>
I can't find the mistake here. I saw some similar questions but still can't fix it. here is my models.py class Department(models.Model): name = models.CharField(max_length=100) class CustomUser(AbstractUser): department = models.ManyToManyField(Department, blank=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) department = models.ManyToManyField(Department, blank=True) forms.py class StudentRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['department', ..] widgets = {'department': forms.CheckboxSelectMultiple()} def __init__(self, *args, **kwargs): super(StudentRegisterForm, self).__init__(*args, **kwargs) self.fields['department'].required = True def clean_department(self): value = self.cleaned_data.get('department') if len(value) > 1: raise forms.ValidationError("You can't select more than one department!") return value def save(self, commit=True): user = super().save(commit=False) user.save() student = Student.objects.create(user=user) student.department.add(self.cleaned_data.get('department')) <-- got error on this line return (user, student) When the CustomUser object is created, the Student object will also be created within save method. But for some reasons it gave me an error TypeError: Field 'id' expected a number but got <QuerySet [<Department: GEE>]>. Noticed that the Department objects were created within admin panel and also the department field within the Student model works just fine if I create it inside admin panel. -
TypeError: 'AnonymousUser' object is not iterable eventhough we are using LoginRequiredMixin
I am having a class based view from django.contrib.auth.mixins import LoginRequiredMixin class ProjectView(TemplateView, LoginRequiredMixin): template_name = 'project.html' def get_context_data(self, **kwargs): proj = Project.object.filter(user = self.request.user) context = super().get_context_data(**kwargs) context['project'] = proj return context Eventhough I'm using LoginRequiredMixin it is going to the get_context_data And it is throing one error like this "TypeError: 'AnonymousUser' object is not iterable" -
What is the better way to have Flutter app consume Python code?
The easier approach seems to be using Python as api(django/flask), but has anyone explored the starflut package and how it can be used to consume Python code. Saw an earlier question also on this but not much helpful responses on this? Import python module in flutter using starflut. Please share your experiences if you have tried this out and the limitations and approach for this. -
Django CSRF with Python's requests module
So I was trying to test one of my Django application's API using Python's requests module, and it's going to require a POST request. When I do that, I got the following error: Forbidden (CSRF cookie not set.) Despite I added @csrf_exempt on the route that I'm testing. -
Heroku django app template does not exist
Hi everyone I need help from you, i have created one blog for the project and it works well in the local server, but when i hosted on heroku it showing TemplateDoesNotExist, i don't know why it is, I surfed on the internet about this but I can't able to find the solution for this moreover i followed instruction said in other StackOverflow user comments. please help me to solve this Thanks in advance here is my code Error TemplateDoesNotExist at / main/home.html Request Method: GET Request URL: http://newsblog135.herokuapp.com/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: main/home.html Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.12 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Fri, 18 Sep 2020 03:52:10 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/Templates/main/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/main/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/main/home.html (Source does not exist) Settings.py import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # … -
How can I let my users update their post through a modal in django?
I have a view that allows users to update their post: class UpdatePostView(UpdateView): model = Post template_name = 'posts/post_update.html' form_class = PostUpdateForm success_url = '/posts' def form_valid(self, form): form.instance.author.user = self.request.user return super(UpdatePostView, self).form_valid(form) def get(self, request, *args, **kwargs): self.object = self.get_object() if self.object.author.user != request.user: return HttpResponseRedirect('/') return super(UpdatePostView, self).get(request, *args, **kwargs) Via a form to be rendered to a template: class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'image', 'category'] And the template itself: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button type="submit" value="submit">Update Post</button> </form> It is working okay but what I would like to do is, instead of sending the user to a separate page to update their post, allow them to update via a modal on the same page as their post. I have created a bootstrap modal which corresponds to the specific post for the user to update: <button data-toggle="modal" data-target="#edit{{post.id}}">Edit</button> <div class="modal fade" id="edit{{post.id}}" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title">Update your post</h3> </div> <form action="{% url 'posts:update_post' post.pk %}" method="post" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor … -
Unable to locate file while rendering tag 'sass_src' in template
trying to integrate sass into my django3.1 project. I have tried implementing sass with other methods such as Django-compressor, but couldn't get it to work there either. So any suggestions to get the end goal of sass working would be appreciated. following the steps on https://terencelucasyap.com/using-sass-django/ I tried implementing Django-sass-processor, but when I go to the home page it gives me the error Unable to locate file style.scss while rendering tag 'sass_src' in template app/index.html Settings.py INSTALLED_APPS = [ ... #SASS 'sass_processor', ] ... STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' #DJANGO SASS SASS_PROCESSOR_ROOT = STATIC_ROOT base.html {% load sass_tags %} {% load static %} ... <link href="{% sass_src 'style.scss' %}" rel="stylesheet" type="text/css" /> the site seems to work normally on the admin page. I ran collectstatic and the admin CSS is in the same folder as the style.scss so I don't think its an issue with STATIC_ROOT but I am not sure where the error is occurring. tree ../ROOT/ ├── db.sqlite3 ├── manage.py ├── README.md ├── requirements.txt ├── static │ ├── admin │ └── style.scss ├── PROJECT │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py … -
at=error code=H12 desc="Request timeout" in heroku
Please help me to solve this. Everything is working fine. The app is also perfectly launched. But at the time of prediction(Machine Learning Model). It shows error in log like this at=error code=H12 desc="Request timeout" method=POST path="/ImpactPrediction" host=incidentimpactprediction.herokuapp.com request_id=0ed43578-57cd-4353-bb10-2f8d0612bcf9 fwd="157.49.246.196" dyno=web.1 connect=5ms service=73606ms status=503 bytes=0 protocol=https In Procfile, I give like this web: gunicorn impactproject.wsgi --timeout 2000 --log-file - I give the timeout to solve the H13 error, But H12 error came in picture. I don't know what's the issue is going on... -
DJango getting static bootstrap stylesheet to apply in view
I am scratching my head on this because none of this is making sense. I am running a Django project in dev mode. I have a base.html that I include in many of my pages. Here is my file structure: Here is the simple base.html code: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>RAHQ Locations {% block head_title %} {% endblock %}</title> </head> <body style="background-color: #26272b; color: #fff"> {% include 'navbar.html' %} <div class='container-fluid'> {% block content %} {% endblock %} </div> {% include 'js.html' %} <br> <br> {% include 'footer.html' %} </body> </html> Everything is working PERFECT like this. But I want to make changes to the bootstrap css, so I download the bootstrap css file, rename it to styles.css, and place it in my static folder. so I replace the bootstrap href with everything I can to access my static styles.css I follow all the online guides that tell me to tweak my settings.py and url.py to allow the use of static files. I have tried bringing in the path from the view.py: url = staticfiles_storage.path('styles.css') I have tried even … -
How do i send user data from flutter app to django website (database)
Hi good people of Stackoverflow. I am new here, four months in, teaching myself to code. I think I am ready for my own side project. I have dabbled in Python, Django and Flutter. I think I am above beginner in all the three languages, except Flutter (maybe). I just need some directions to bring this idea to fruition. I understand that this application already exists on the market, I think. What I am trying to do is: Here's the flowchart Create a webpage (Django) that will: Generate random qrcode Plus the location of user that asked for this webpage. For example, A is trying to access this webpage and trying to log people into system, thus A give his/her location to webpage. Plus unique identifier. Just because Create an application (Flutter): Plus the location of user that asked for this webpage. For example, A is trying to access this webpage and trying to log people into system, thus A give his/her location to webpage. Use the camera phone to scan the qrcode. Plus the location of user that asked for this webpage. For example, A is trying to access this webpage and trying to log people into system, thus … -
How to add data from one manytomanyfield to another manytomanyfield in django
I have 3 models look like this models.py class Department(models.Model): name = models.CharField(max_length=100) class CustomUser(AbstractUser): first_name = models.CharField(...) department = models.ManyToManyField(Department, blank=True) class Teacher(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=100) department = models.ManyToManyField(Department) I have created Department objects inside admin panel. Now I Have a form for creating CustomUser object and when I create CustomUser the Teacher will also be created inside save method but How can I assign manytomanyfield from CustomUser into manytomanyfield inside Teacher? here is the form class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['first_name', 'department'] widgets = {'department': forms.CheckboxSelectMultiple()} def save(self, commit=True): user = super().save(commit=False) user.is_teacher = True user.save() first_name = str(self.cleaned_data.get('first_name')) department = self.cleaned_data.get('department') teacher = Teacher.objects.create(user=user, first_name=first_name, department=department) return (user, teacher) Currently I create teacher object by doing like it shown above but I can't create the department field. How can I do that? When I create I get this error TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use department.set() instead. I know we can't assign department to department but i really don't know what to do to make it works -
How to run a .py service withou stop on Django and docker-compose
i create a service that checks if my license its about to expire and then send email if the criteria are met. I created as a manage.py command, now i need to leave always running, and starts automatically when i start with the commando django-compose. What should i do ? Here is the command i created: from django.utils import timezone from django.core.management.base import BaseCommand, CommandError from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string from datetime import datetime, timedelta from time import sleep from license.models import License from license.models import Client class Command(BaseCommand): help = 'Email sender' def handle(self, *args, **kwargs): try: """ Logic for 1 week expire or already expired and is_send=false """ client = Client.objects.all() licenses = License.objects.all() clients_name = [] hoje = timezone.now() - timedelta(days=7) for date in licenses: if hoje >= date.expiration_datetime and date.is_send is False: clients_name.append(date.client) #license_instance = License.objects.get(pk=date.pk) #license_instance.is_send = True #license_instance.save() """ Logic for exactly 4 months """ for days in licenses: if (timezone.now() + timedelta(weeks=16) ) == days.expiration_datetime and days.is_send is False: clients_name.append(days.client) license_instance = License.objects.get(pk=date.pk) license_instance.is_send = True license_instance.save() """ Logic for within a month and if today is monday""" today = timezone.now() today = today.weekday() todays = … -
When i runserver in Django it not running as 127.0.0.0:8000 instead of this it is going to 127.0.0.0:8000/application
when i runserver from different projects also it is redirecting to 127.0.0.0:8000/application. I tried by creating new project but no use. i am getting same. Actually this started happening when i downloaded a project from github after that i am facing this problem. -
Failed to setup settings.AUTH_USER_MODEL in Django
Previously, I failed to setup the AUTH_USER_MODEL = 'apps.authuser.User' for my project. All my apps is combined in one folder, called with apps. the project structure is like this; ├── apps │ ├── authuser/ │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── models/ │ │ │ ├── __init__.py │ │ │ └── user.py │ │ ├── utils │ │ │ ├── backends.py │ │ │ └── __init__.py │ ├── blog/ │ │ ├── __init__.py │ │ ├── apps.py │ │ └── models/ │ ├── product/ │ │ ├── __init__.py │ │ └── apps.py ├── core/ │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── templates/ ├── db.sqlite3 └── manage.py 1. settings.py; INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', .... # major apps 'apps.authuser', 'apps.blog', 'apps.product', ] # Custom Auth User Model AUTH_USER_MODEL = 'apps.authuser.User' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'apps.authuser.utils.backends.CustomAuthBackend' ] 2. apps/authuser/apps.py; # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AuthUserConfig(AppConfig): name = 'apps.authuser' verbose_name = _('App Auth User') 3. apps/authuser/__init__.py; # -*- coding: utf-8 -*- from __future__ import unicode_literals default_app_config = 'apps.authuser.apps.AuthUserConfig' 4. apps/authuser/models/__init__.py; # -*- coding: utf-8 -*- … -
Changing the column header of a table in a postgres database
I am trying to rename a column in my database. I did heroku pg:psql ALTER TABLE discounts_discount RENAME COLUMN percentagediscountm TO percentagediscount And that had no impact. I looked on a few sites and to the best of my knowledge, what I wrote above should work. I tried making the change using make migrations and migrate but then got this error. django.core.exceptions.FieldDoesNotExist: discounts.discount has no field named 'percentagediscountm' I am really trying to avoid having to drop my database or rolling back Heroku to an earlier build. -
Vue and Django mustache templating conflict
I am planning to do a project with Vue in the frontend and Django in the backend, but they both use double curly braces {{ }} as their template tags. Is there an easy way to change one of the two to use some other custom templating tag? Thanks in advance. -
Docker-compose run issue
I am faced with the error below. I have no idea to solve it. If anyone knows the solution, please help me... Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: "django-admin.py": executable file not found in $PATH": unknown ■docker-compose.yml version: "3" services: nginx: image: nginx:1.13 ports: - "8000:8000" volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static depends_on: - python db: image: mysql:5.7 #MySQLの文字コードの設定です(defaultはlatin1が入っており、日本語入力ができないため) command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: todoList MYSQL_USER: user MYSQL_PASSWORD: mitsuki630 TZ: "Asia/Tokyo" volumes: - ./mysql:/var/lib/mysql #./sqlを/docker-entrypoint-initdb.dにマウントすることで、コンテナ起動時に./sql配下のsql文が実行される(DBの初期化) - ./sql:/docker-entrypoint-initdb.d python: build: ./python #uwsgiを使用してポート8001(任意のポート番号)を開放します。これが、後のnginxへの連携の際に必要な処理となります #app.wsgiのappはDjangoのプロジェクト名です #--py-autoreload 1はDjangoアプリ開発の際に、ファイル等に変更があった際は自動リロードするための設定です #--logto /tmp/mylog.logはログを残すための記述です。 command: uwsgi --socket :8001 --module app.wsgi --py-autoreload 1 --logto /tmp/mylog.log volumes: - ./src:/code - ./static:/static expose: - "8001" depends_on: - db ■Dockerfile #python3をインストール FROM python:3 #PYTHONUNBUFFEREDでバッファーを無効にするらしい ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN /bin/sh -c pip install -r requirements.txt COPY . /code -
Cannot upload images in React and Django Rest Framework
What I want to do Upload images and create new models by using them Problem Every time I send POST request to the server, I got 404 Bad Request. It seems like there's something wrong with the data I sent. Attempts 1. Adding header which is headers: { 'content-type': 'multipart/form-data' } Although I add this header to the third parameter of axios, I got the same error. 2. Adding parser_classes = [MultiPartParser] to my ModelViewSet I got the same error. I tried all solutions I found on the internet but there is nothing to solve my problems. Would you please tell me how to solve it?? I'll post my code below. If it alright with you, please give me advices. Thank you very much. Models.py class Item_Image(models.Model): image = models.ImageField(upload_to="images/") item = models.ForeignKey( Give_Item, on_delete=models.CASCADE, related_name="item_image") def __str__(self): return self.item.parent_item.name class Meta: db_table = "item_images" views.py class Item_ImageViewSet(viewsets.ModelViewSet): queryset = Item_Image.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = Item_ImageSerializer parser_classes = [MultiPartParser] And Add_Give_Item_Form.jsx, which is a file to send forms. class Add_Give_Item_Form extends Component { constructor(props) { super(props); this.state = { // #インプット情報用 info: { name: '', owner: '', keyword1: '', keyword2: '', keyword3: '', bland: '', state: '新品', … -
Django How Do I Add Buttons To Direct Me To My Pages. -- Beginner
I am learning Django and I was wondering how I could add buttons that will direct me to defferent pages I am fearly new to django and still learning I have 3 pages when I put /v1 and /v2 those are my 2 other pages and I have my main which I dont have to put any / -
My django commands wont run. Any advice would be appreciated
When I run python3 manage.py runserver it just returns Watching for file changes with StatReloader Performing system checks... and nothing else appears. when I run python3 manage.py migrate nothing at all happens it just blank. This problem just rose out of the blue. I have been able to run these commands before and I don't know why it has stopped working. Any help would be appreciated. -
How to use a Python function in Django
Good night guys!! I am in need of help from the specialists on duty in Django. I am currently having a problem where I have not found any solution that I have been able to understand and implement. I will summarize here the scope of what I need, otherwise it would be too extensive. In a work, I did some functions in Python that involve image processing in Python, in which I use libraries such as OpenCV and Pytesseract, to get a better idea on the subject, you can consult my question here on the Stack on the subject, as follows: Detecting warm colors in the Python image The function I created basically receives a directory containing images or an isolated image (in .jpg), does the necessary processes and returns the image with the indications of the hot spot location (as shown in the image below) and the temperature at this point (a float number). Results os my function Note: The blue circle, Coordinate and Value are the result of the function and are not part of the original image. With that, I would like to create a web application that applies these functions, using Django, as I already have … -
Django MEDIA_URL appending full MEDIA_ROOT
In Django 3 I have this in my settings: MEDIA_URL = '/media/' My MEDIA_ROOT echos out properly (/home/bradrice/source/repos/bb_backend/media ) and I have this in my urls: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am using a VersatileImageField and the image uploads to the proper media folder. However, I can't see the image in Admin and if I click the link it prepends the Url with the full MEDIA_ROOT instead of just the /media/ onto the display url. What am I doing wrong. -
Django ManyToMany add not wroking but remove working
I have below models. Model Person associated with Media thorough manytomany field. class Media(models.Model): """Media represents the medium where person(s) (entity?) can be identified in. """ persons = models.ManyToManyField( Person, blank=True, related_name="media", help_text="Persons identified in the media", ) source = models.ForeignKey( Source, on_delete=models.SET_NULL, blank=True, null=True, related_name="media", help_text="Source for this media", ) class Person(models.Model): """A Person represents an actual individual. """ # Settings STATUS_CHOICES = [ ("active", "active"), ("inactive", "inactive"), ("under_review", "under review"), ] status = models.CharField( max_length=64, choices=STATUS_CHOICES, default="under_review", help_text="The status of this model, influences visibility on the " "platform.", ) What problem I am facing is whenever I try to add any person (Irene) to media (5898008 scarlett johansson jerk off challenge) it is not getting added. And showing only one which is already present (Scarlett Johansson). >>> p <Person: Irene> >>> m <Media: 5898008 scarlett johansson jerk off challenge> >>> m.persons.add(p) >>> m.persons.all() <QuerySet [<Person: Scarlett Johansson>]> But when I try to remove it, it is working. >>> m.persons.remove(p1) >>> m.persons.all() <QuerySet []> Can anyone please guide me what I am doing wrong? -
Django model testing
I have a problem in trying to print information of a model while testing. This is my code: from django.test import TestCase from .models import User, Followed, Following, Post # Create your tests here. class User_test(TestCase): def setUp(self): a = User.objects.create(username="a", password="a", email='a@a') f = User.objects.create(username="f", password="f", email='f@f') Followed.objects.create(user=a) Following.objects.create(user=f) Followed.objects.create(user=f) Following.objects.create(user=a) def test_a(self): userA = User.objects.get(username='a') userF = User.objects.get(username='f') peopleFollowingF = Followed.objects.get(user=userF) peopleFollowingA = Followed.objects.get(user=userA) Afollowing = Following.objects.get(user=userA) Ffollowing = Following.objects.get(user=userF) userA.save() Ffollowing.follower.add(User.objects.get(username='a')) Ffollowing.save() print(Ffollowing.follower) when I run the test i get print network.User.None Someone can help me to print add succesfully the userA?