Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Heroku : python: can't open file 'manage.py': [Errno 2] No such file or directory
I am deploying a Django website on Heroku. My project is called mysite-project wich contains at its root manage.py and Procfile I can visit the heroku website after I run git push heroku master. And the website shows: I am assuming I do not see anything (navbar, initial page etc) because I did not run migrate. If I do: heroku run python manage.py migrate I get the error: python: can't open file 'manage.py': [Errno 2] No such file or directory Which makes no sense since I am in the right directory. In fact: I can run python manage.py runserver and locahost works git ls-files manage.py --outputs--> manage.py BUT If I do: heroku run bash ls manage.py I get: ls: cannot access 'manage.py': No such file or directory It seems that manage.py is in my local but not in my heroku. Procfile web: gunicorn mysite-project.wsgi -
HTML templates or React for Django front end?
I’m creating a big project with Django and wondering if it is sensible to use the HTML template structure for my front end or should I implement something like React? What are each of its benefits? Is it perfectly reasonable to use HTML templates for a big project? Any advice? -
Blog - How to fix being unable to see specific category group when category is clicked via drop down box?
I'm trying to organize the blog categories I have a few "Test Post" I created and when I start up the server, click on that relevant category tag to that post the page doesn't show that page relevant to that category. It's not rendering out anything but the header and the sidebar. Models.py from django.db import models from django.urls import reverse from tinymce import HTMLField from django.utils import timezone class Comment(models.Model): post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text class CategoryTag(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(unique=True) parent = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True, related_name='children' ) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = 'categories' def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField('Content') comment_count = models.IntegerField(default=0) post_img = models.ImageField() categories = models.ForeignKey('CategoryTag', null=True, blank=True, on_delete=models.CASCADE) featured = models.BooleanField() slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.categories breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i … -
Djoser doesn't work on endpoint create user
I am trying to implement djorse in my project with django-rest-framework, but when trying to create or delete a user, the endpoints do not work, since they are not configured. How can i fix that? I already configured the django settings file to integrate djoser, but it still doesn't work correctly. settings.py DJOSER = { "ACTIVATION_URL": "activate/{uid}/{token}/", "PASSWORD_RESET_CONFIRM_URL": urllib.parse.urljoin( WEB_APP_URL, "/password/reset/confirm/{uid}/{token}" ), "EMAIL": { "activation": "users.emails.ActivationEmail", "confirmation": "djoser.email.ConfirmationEmail", "password_reset": "users.emails.PasswordResetEmail", }, "PERMISSIONS": { "activation": ["rest_framework.permissions.AllowAny"], "password_reset": ["rest_framework.permissions.AllowAny"], "password_reset_confirm": ["rest_framework.permissions.AllowAny"], "set_password": ["djoser.permissions.CurrentUserOrAdmin"], "set_username": ["rest_framework.permissions.IsAuthenticated"], "user_create": ["rest_framework.permissions.AllowAny"], "user_delete": ["rest_framework.permissions.IsAdminUser"], "user": ["djoser.permissions.CurrentUserOrAdminOrReadOnly"], "user_list": ["crm.permissions.IsAdminOrCoach"], "token_create": ["rest_framework.permissions.AllowAny"], "token_destroy": ["rest_framework.permissions.IsAuthenticated"], }, "SEND_ACTIVATION_EMAIL": True, "SET_PASSWORD_RETYPE": True, "SERIALIZERS": { "current_user": "auth.serializers.CurrentUserSerializer", "user": "auth.serializers.CurrentUserSerializer", "user_create": "users.api.serializers.UserRegistrationSerializer", }, } users/serializers.py class UserRegistrationSerializer(UserCreateSerializer): email = serializers.EmailField( max_length=200, validators=[ UniqueValidator( queryset=User.objects.all(), message=USER_ALREADY_EXISTS_ERROR_MESSAGE ) ], ) class Meta(UserCreateSerializer.Meta): pass urls.py urlpatterns += [ path("crm/", include("crm.urls", namespace="crm")), path("workouts/", include("workouts.urls", namespace="workouts")), path("api/v1/auth/", include("auth.urls", namespace="auth-api")), path("api/v1/accounts/", include("djoser.urls")), path( "api/v1/accounts/users/activate/<str:uid>/<str:token>/", ActivateAccountView.as_view(), name="activate-user-account", ), path( "activation-failed", ActivateAccountFailed.as_view(), name="activate-user-account-failed", ), path("api/v1/", include("crm.api.urls", namespace="crm-api")), path("api/v1/", include("workouts.api.urls", namespace="workouts-api")), path("api/v1/documentation/", schema_view.with_ui("swagger", cache_timeout=0)), ] This is the error, when i {POST} request to endpoint api/v1/accounts/users/create { "detail": "Method \ "POST \" not allowed." } -
Django delete multiple ImageField files on model delete
I have an Image model with two ImageFields (one for regular image and one for the thumbnail). I'm trying to delete both files together with a post_delete receiver but I'm having difficulty chaining the operations. What I have throws a file does not exist error probably because only one delete saves. class Image(models.Model): path = models.ImageField(upload_to=photo_image_upload_path,blank=False, null=False) thumb = models.ImageField(upload_to='', editable=False, default=None, null=True) @receiver(post_delete, sender=Image) def photo_delete(sender, instance, **kwargs): # Pass false so FileField doesn't save the model. if instance.thumb is not None: instance.thumb.delete(True) if instance.path is not None: instance.path.delete(False) -
problems with this TypeError: save() missing 1 required positional argument: 'self' in pycharm django
I'm trying to save a query in the python shell in the terminal but it seems an error popped up saying this "Traceback (most recent call last): File "", line 1, in TypeError: save() missing 1 required positional argument: 'self'" I've no idea what to do. I'm trying to type this "post.save()" but the error above showed up after I pressed enter. All I am trying is to type this >>> from django.contrib.auth.models import User >>> from blog.models import Post >>> user = User.objects.get(username='admin') >>> Post.objects.create(title='One more post', slug='one-more-post', body='Post body.', author=user) >>> post.save() in the terminal I've already tried searching for the same problems that others are facing but none of it matches my problem. all of the codes in the models and the admin were correct. I've tried several websites and search for several problems that others have issues with but I couldn't find a solution for it. from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post (models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, … -
Page not found error 404 with django framework
I'm developing website for my resume using django framework and for styling i am using uikit css framework but facing problem with the url for contact template as it throws "page not found error" Request URL: http://localhost:8000/contact/ Using the URLconf defined in myresume.urls, Django tried these URL patterns, in this order: experience education contact admin/ The current path, contact/, didn't match any of these. i have tried using re url pattern and also trailing slash as mentioned in the official documentation. Contact template is available at myapp/templates/myapp/contact.html from django.urls import path from . import views urlpatterns=[ path('',views.home), path('experience',views.experience), path('education',views.education), path('contact',views.contact), ] i am expecting to render contact template in my browser -
Create db with django visual studio
Executing manage.py syncdb Unknown command: 'syncdb' Type 'manage.py help' for usage. The interactive Python process has exited. i have these archive in my enviroment package pip ptvsd pytz setuptools sqlparse -
How to Set Value for When Query is False
I am creating a list of IDs which corresponds to a set of records (opportunities) in the database. I then pass this list as a parameter in a RESTful API request where I am filtering the results (tickets) by ID. For each match, the query returns various JSON data. However, I want to handle when the query does not find a match. I would like to assign some value for this case such as the string "None", because not every opportunity has a ticket. For example, currently I pass opportunity_list = [1,2,3,4,5] and return presales_tickets = [a,b,c] when I want presales_tickets = [a,None,b,c,None]. How can I make sure there exists some value in presales_tickets for every ID in opportunity_list? views.py opportunities = cwObj.get_opportunities() temp = [] opportunity_list = [] cw_presales_engineers = [] for opportunity in opportunities: temp.append(str(opportunity['id'])) opportunity_list = ','.join(temp) presales_tickets = cwObj.get_tickets_by_opportunity(opportunity_list) for presales_ticket in presales_tickets: try: if presales_ticket: try: cw_engineer = presales_ticket['owner']['name'] cw_presales_engineers.append(cw_engineer) except: pass else: cw_engineer = '' cw_presales_engineers.append(cw_engineer) except AttributeError: cw_engineer = '' -
Publishing Data on Screen
I'm learning Django and did the exercise in this video and I get up about the 45 minute point and everything works fine: https://www.youtube.com/watch?v=D6esTdOLXh4 after that I can't ge the two blog posts to show up as it does in the video. I had named the new model "posts" unlike in the video which called the model "Posts" so I adjusted my code so instead of creating a variable "posts" I made it blogpost in view.py. Below I show the code for the model, view and index. THe problem is I can see the layout but it doesn't populate the blog posts in the jinja code. If I add static text, the static text shows fine. <h1>Model.py</h1> ''' /*from django.db import models from datetime import datetime # Create your models here. class posts(models.Model): title = models.CharField(max_length=200) body = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Posts"*/ ''' Views.py ''' def index(request): # return HttpResponse('Hello from Posts') blogpost = posts.objects.all()[:10] context = { 'title': 'latest posts', 'posts': blogpost } return render(request, 'posts/index.html', context) ... Index.html ''' {% extends 'posts/layout.html' %} {% block content %} <h1 class="center-align red lighten-3">{{title}}</h1> <ul class="collection"> {% for blog in blogpost … -
Django migration delete and update
I have already had some migration files, and I made some changes in the model and did python manage.py makemigrations python manage.py migrate After that in postgresql table django_migrations there is a row indicating I've applied that migration, let's call this migrationA. I deleted the new generated migration file (migrationA), modified a small piece in my model and then did python manage.py makemigrations python manage.py migrate This generate migrationB. I was hoping this can do the same as squashing migration files. Will this kind of flow cause any trouble? I didn't see any trouble now but want to make sure this is a safe way to do things. In addition, is there any way to revert postgresql to the time before I applied migrationA? -
Error when push files to heroku (error: failed to push some refs to ...)
When I try to type "git push heroku master" in the console, I have the following problem. This is my second approach to heroku and again I have a problem in the same place, I was looking for advice on the Internet, but nothing helps me (venv) C:\Users\patryk\Desktop\Django\MyPage>git push heroku master Enumerating objects: 33, done. Counting objects: 100% (33/33), done. Delta compression using up to 4 threads Compressing objects: 100% (27/27), done. Writing objects: 100% (33/33), 17.14 KiB | 1.90 MiB/s, done. Total 33 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python- runtimes remote: -----> Installing python-3.7.4 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to xxx. remote: To https://git.heroku.com/xxx.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/xxx.git' requirements.txt file: -r requirements-dev.txt gunicorn psycopg2 requirements-dev.txt file: dj-database-url==0.5.0 dj-static==0.0.6 Django==2.2.4 django-bootstrap-form==3.4 djangorestframework==3.10.2 Pillow==6.1.0 python-decouple==3.1 pytz==2019.2 … -
Django pagination for api response objects
I am building a blogsite and I am using a cryptonews api to display the news on the page. I want to display 10 api objects per page. When I tried it as shown below I get an error. from django.core.paginator import Paginator from django.shortcuts import render def home(request): import requests import json # Grab crypto Price Data price_request = requests.get("https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,EOS,LTC,XRP,BCH,XEC,BNB,BGG,TRX&tsyms=USD") price = json.loads(price_request.content) # Grab Crypto News api_request = requests.get("https://min-api.cryptocompare.com/data/v2/news/?lang=EN") api = json.loads(api_request.content) paginator = Paginator(api, 10) page = request.GET.get('page') items = paginator.page(page) return render(request, 'home.html', {'items': items, 'price': price}) -
My django application is not working in customdomain
I recently finished my django project and deployed it successfully without any errors in heroku. It works fine with the appname.herokuapp.com domain. But when i tried to add my custom domain, i got a very different problem. Only my machine can access the page. Weird right! Yes. The page can be accessed only by me in my machine. But i get DNS_PROBE_FINISHED_NXDOMAIN error. Really weird! I guess this is not the problem with the code and i know i'm missing somewhere in the dns configuration. I bought my domain in big rock. So please guide me through this weird problem. The development site is arr-coaching.herokuapp.com The deployed site is www.arccphysics.in (Which you cannot access) :( And any device connected to my WIFI can open the site. Some serious thing! Please help me out ! -
Django adding related object to instance of a parent
RoR refugee, learning Django here. I have an application with related models, Project and Workstream. I need to create new Workstream objects related to a Project (Project can have many workstreams). I have the logic and relations for this working fine, but when I try to create a method in the Project class to add a workstream to a Project instance and provide default values, I cannot get it to work. I have the function, but get an attribute error 'Manager' object has no attribute 'add'. When I research managers, I can find no references involving functions adding to a model, only involving limiting querysets. I suspect I am not doing things The Django Way in my approach. Wrote classes and functions, got errors, researched those, found nothing useful. class Project(models.Model): STATUS_CHOICES = ( ('NS', 'Not Started'), ('IP', 'In Process'), ('PR', 'Pending Review'), ('CP', 'Complete'), ) project_id = models.AutoField(primary_key=True) client_id = models.ForeignKey('clients.Client', on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=True) status = models.CharField(max_length=2, choices=STATUS_CHOICES) def __str__(self): # Return the name of the Project. return self.name @classmethod def add_workstream(self, ws_name='New Workstream', ws_desc='TBD'): """Add a workstream. Include optional arguments for name, description and status. """ from workstreams.models import Workstream new_ws … -
Heroku and Django : error "Couldn't find that app" from terminal/CLI
I am employing my Django website into Heroku. I followed: a) heroku login b) heroku create Which produces: Creating app... done, ⬢ enigmatic-ridge-36610 https://enigmatic-ridge-36610.herokuapp.com/ | https://git.heroku.com/enigmatic-ridge-36610.git c) heroku addons:create heroku-postgresql:hobby-dev Which produces: Creating heroku-postgresql:hobby-dev on ⬢ morning-gorge-61422... ! ▸ Couldn't find that app. I tried this guide: "Couldn't find that app." when running heroku commands in console But it did not work -
Dependency injection in django Views
I want to use dependency injection for my django project. For that I'm trying pinject package. Like in ASP.NET, all the dependencies are given in the constructor, and that's very nice because it's easy to test. I would also like to archive something similar in my django project. I have a simple View: class MySimpleView(View): def __init__(self, dependency1, dependency2, **kwargs): super().__init__(**kwargs) ... A place where I define the bindings # di.py class AppBindingSpec(pinject.BindingSpec): def configure(self, bind): # do the bindings here obj_graph = pinject.new_object_graph(binding_specs=[AppBindingSpec()]) And I expected to use it like this. # urls.py urlpatterns = [ path('path/to/my/view', obj_graph.provide(MySimpleView).as_view()), ] But unfortunately, django does not allow the .as_view() to be called from an instance. Is there any simple way to inject the dependencies into my view so I can easily mock and test? -
How to transfer some variable to form?
I want to make a custom form field validation to check if entered string is an email of user variable. Smth like this: class FullEmailOrPhoneForm(forms.Form): entered_string = forms.CharField() class Meta: model = User fields = ('entered_string',) def clean_entered_string(self): email = self.cleaned_data['entered_string'] if email == user.email: ans = email else: raise ValidationError('Incorrect email') return ans My view: def reset_password_with_username(request, user): if request.method == 'POST': form = FullEmailOrPhoneForm(request.POST) if form.is_valid(): pass else: form = FullEmailOrPhoneForm() return render(request, 'registration/password_reset_with_username.html') So how can I transfer user variable from view to form validation function? -
Django model is inheriting all super model Fields, except for IntegerField
I'm having a weird issue, I have a models' hierarchy, an abstract User class: class User(AbstractBaseUser): user_name = models.CharField(max_length=32, unique=True) email = models.EmailField(max_length=255, unique=True, null=True) phone = PhoneNumberField() access_token = models.CharField(max_length=255, unique=True, null=True) notifications_token = models.CharField(max_length=255, unique=True, null=True) photo = models.ImageField(null=True) person_in_contact = models.CharField(max_length=32, null=True) active = models.BooleanField(default=False) confirmedEmail = models.BooleanField(default=False) confirmedPhone = models.BooleanField(default=False) completedProfile = models.BooleanField(default=False) visible = models.BooleanField(default=True) @property def is_active(self): return self.active # def __str__(self): # return "Client : " + self.user_name + " Email:" + self.email def get_email(self): return self.email USERNAME_FIELD = 'user_name' REQUIRED_FIELDS = ['user_name', 'phone', 'password'] class Meta: abstract = True then a person class and a company (no issue with this one) class that inherit from this one: class Person(User): GENDER = (('F', 'FEMALE'), ('M', 'MALE')) name = models.CharField(max_length=50, null=True) surname = models.CharField(max_length=50, null=True) adress = models.CharField(max_length=255, null=True) birth_date = models.DateField(null=True) gender = models.CharField(max_length=1, choices=GENDER, null=True) age = models.IntegerField(null=True) def age(self): today = date.today() return today.year - self.birth_date.year # def __str__(self): # return super().__str__() + " Name : " + self.name class Meta: abstract = True as you can see, the only field that's IntegerField() is the age field. now i have a Traveller and a Driver classes that inherit from the person … -
Django is it safe csrf middleware token shows up in url?
when making GET requests, I've noticed that my csrf tokens gets appended to my url. Is this safe? -
dictsort gives no resuts
I use a queryset fields in 2 places on my view. One is ordered by another field, the other is ordered by facet. I'd like to order the dataset in 2 ways on the page, rather than passing the queryset twice. I am trying to use dictsort to do this as is outlined here and a few other questions. I have this in my code: {% for field in fields|dictsort:"facet_order" %} field.facet_order {% endfor %} But i see nothing rendered. The loop works fine without the dictsort, and as a sanity check i have run the below with no problem: {% for field in fields %} field.facet_order {% endfor %} It yields: None None None None 1 0 None ... My code looks to me like it strongly resembles django's documentation example below: {% for book in books|dictsort:"author.age" %} * {{ book.title }} ({{ book.author.name }}) {% endfor %} What am i doing wrong here? -
How to log all Django serializer validation errors?
Similar to this, I would like to get log lines on the server when serializer validation fails. What is the best approach to add logging to Serializers? -
TypeError: encoding without a string argument for razorpay webhook secret verification error
I am trying verify if the webhook came from Razorpay but getting following error. TypeError: encoding without a string argument Here is the code: webhook_secret = MY_WEBHOOK_SECRET signature = request.headers['X-Razorpay-Signature'] jsondata = json.loads(request.body) client = razorpay.Client(auth=(MY_KEY, MY_SIGNATURE)) verify = client.utility.verify_webhook_signature(jsondata, signature, webhook_secret) I'm getting error in the last line. Can someone help me with this? Thanks! -
Difference in version of python in docker compose services
I'm trying to make a docker image of my website made with django and channels. I have 4 services: redis, http server, channel worker and daphne server. However, I have an error on the daphne server. I've found that between service, there were different python version while the docker fiel is the same This is my docker-compose.yaml : version: '3' services: redis: image: redis command: redis-server ports: - '6379:6379' web: build: ./soundover command: bash -c "python --version && python manage.py runserver 0.0.0.0:8000" volumes: - ./soundover:/soundover ports: - "8000:8000" worker_channels: build: ./soundover command: bash -c "python --version && python manage.py runworker websocket" volumes: - ./soundover:/soundover links: - redis channels: build: ./soundover command: bash -c "python --version && daphne -b 0.0.0.0 -p 8001 soundover.asgi:application" volumes: - ./soundover:/soundover ports: - "8001:8001" links: - redis And the Dockerfile: FROM python:3.6 ENV WEBAPP_DIR=/soundover RUN mkdir $WEBAPP_DIR WORKDIR $WEBAPP_DIR ADD requirements.txt $WEBAPP_DIR/ ADD manage.py $WEBAPP_DIR/ RUN pip install -r requirements.txt RUN python -m pip install git+https://github.com/django/channels.git --upgrade I had the versions displayed and this is the result : https://prnt.sc/oq4cm5 I expect the output 3.6.9 for all services. Is there a way to force the use of python 3.6 for the service channels(with daphne server) ? -
Django Heroku - ModuleNotFoundError: No module named 'django_heroku'
I am deploying on heroku a website but I am experiencing some issue. My project is called mysite-project. I did the following: 1) Create a Procfile containing: web: gunicorn mysite-project.wsgi at the base root of my project (same level where manage.py is). 2) app/settings.py import django_heroku at the top django_heroku.settings(locals()) at the bottom of settings.py 3) pip install gunicorn pip install django-heroku pip freeze > requirements.txt 4) If I run python manage.py runserver I get: ModuleNotFoundError: No module named 'django_heroku'