Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Media files not serving Django production
I built an app using Django with PostgreSQL as a database. After I finished it, I decided to deploy it on Heroku. Their documentation was too complex for me to understand, so I went to this post on Medium and did what they said. A Server Error (500) came in my application, and I found out that I removed the line STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' it worked properly when I ran python manage.py runserver on my local machine, but it doesn't serve the media files. After I pushed it to Heroku, it still shows a Server Error (500) there. I am showing few parts of my code. Could you please tell me how I could serve the media files properly and why the server error is coming only in the Heroku run app? If you need any code other than whatt I have given here, please inform me in the comments. I know that you can't serve media files when DEBUG = False and that you should use Nginx, but please tell me where I can find a good guide for Nginx deployment on Heruko. Thanks in advance. settings.py """ Django settings for btre project. Generated by 'django-admin startproject' using Django … -
Use external webpage to obtain JWToken for use by Django REST
Suppose you've got a Django REST server that has authentication setup. There are users, groups, permissions, etc. Now, suppose you want to enable a user to: access one of the REST endpoints have Django REST recognize that the user did not provide a JWToken in the AUTHENTICATION cookie redirect to an external page, and include the current URL, say www.getmyjwtoken.com/?redirect_back=www.mydjangorestserver.com/foo/bar/baz/1, and then read the AUTHENTICATION cookie from the result after the mydjangorestserver returns the user back to foo/bar/baz/1 with the cookie in hand. How do you go about enabling (1), (2) and (3)? That is, once the cookie is there, you already know how to read it (Step 4). How do you instruct Django to reference this external webpage to produce the JWT? -
Django-Plotly-Dash retrieving URL slug
I want to include plotly-dash within a Django framework. I want to have one app incorporated into one HTML template that will present line graphs read as pandas dataframe from csv based on the slug entered in the url. The csv files share the same name as the slug to make them easy (I thought) to open. I want to be able to pull the url path, or the slug, and use that to determine which csv file my app opens and uses to present the data for the line plot. This worked fine with only Dash. I could use the url and pathname in the callback and use the pathname as the name of the csv file and have the app dynamically open the proper csv file based on the url slug. @app.callback( Output('indicator-graphic', 'figure'), [Input('url', 'pathname'),]) def update_graph(pathname): df=pd.read_csv('path/to/file/'+pathname+'.csv) The above code worked fine in the Dash test server. When I incorporate this into Django, the url and pathname won't work anymore. I have tried everything I can think of to pass the slug or pathname as an Input to the Dash callback. I cannot get anything to work. Then, I tried to set the dataframe as global … -
How to implement a simple "like" feature in Django REST Framework?
I'm a beginner building the backend API for a social media clone using DRF. The frontend will be built later and not in Django. I'm currently using Postman to interact with the API. I'm trying to implement a "like" feature as you would have on Facebook or Instagram. I cannot send the correct data with Postman to update the fields which bear the many-to-many relationship. Here is some of my code: models.py class User(AbstractUser): liked_haikus = models.ManyToManyField('Haiku', through='Likes') pass class Haiku(models.Model): user = models.ForeignKey(User, related_name='haikus', on_delete=models.CASCADE) body = models.CharField(max_length=255) liked_by = models.ManyToManyField('User', through='Likes') created_at = models.DateTimeField(auto_now_add=True) class Likes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) haiku = models.ForeignKey(Haiku, on_delete=models.CASCADE) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'url', 'liked_haikus'] extra_kwargs = { 'password' : {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token = Token.objects.create(user=user) return user class HaikuSerializer(serializers.ModelSerializer): class Meta: model = Haiku fields = ['user', 'body', 'liked_by', 'created_at'] class LikesSerializer(serializers.ModelSerializer): model = Likes fields = ['haiku_id', 'user_id'] views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=True, methods=['get']) def haikus(self, request, pk=None): user = self.get_object() serializer = serializers.HaikuSerializer(user.haikus.all(), many=True) return Response(serializer.data) class UserCreateViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer … -
Django template does not exist @
I am using python 3.7.2 and Django 2.1 and every time I try to load the home url I get the following error. TemplateDoesNotExist at / ghostwriters/post_list.html Request Method: GET Request URL: http://localhost:8080/ Django Version: 2.1 Exception Type: TemplateDoesNotExist Exception Value: ghostwriters/post_list.html Exception Location: C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\Scripts\python.exe Doesn't make any sense because there really is no post_list.html and its not in my app level urls.py or my views.py so why is this happening? urls.py: from django.urls import path from .views import PostListView urlpatterns = [ path('', PostListView.as_view(), name='home'), ] views.py: from django.shortcuts import render from django.views.generic import ListView from .models import Post class PostListView(ListView): model = Post template = 'home.html' settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, -
NoReverseMatch at /videos/list/ Reverse for 'list_videos' not found. 'list_videos' is not a valid view function or pattern name
Well I am trying to create a Playlist quite similar with YouTube. But the Playlist can only create by superuser from admin panel and other user can only see that playlist and the videos within the playlist. When I thought that I am done than suddenly this error occured. I don't know where I am making mistake. Please help me to fix this problem. videos/models.py class VideosList(models.Model): list_title = models.CharField(max_length=255) list_cover = models.ImageField(upload_to='list cover', height_field=None, width_field=None, max_length=None,blank =True) create_date = models.DateField(default = timezone.now) def __str__(self): return self.list_title class VideosModel(models.Model): videos_lists = models.ForeignKey(VideosList,on_delete=models.CASCADE) video_title = models.CharField(max_length=250) video_url = models.URLField(max_length=1200) video_discription = models.TextField() create_date = models.DateField(default = timezone.now) def __str__(self): return self.video_title videos/views.py class VideosListView(ListView): model = VideosList context_object_name = 'videos_lists' template_name = "videos/videos_lists.html" def get_queryset(self): return VideosList.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class VideosModelListView(ListView): model = VideosModel template_name = "videos/list_videos.html" context_object_name = 'videos_list' def get_queryset(self,*args, **kwargs): videoslist = get_object_or_404(VideosList, list_title=self.kwargs.get('list_title')) return VideosModel.objects.filter(videos_lists=videoslist).order_by('-create_date') videos/urls.py app_name = 'videos' urlpatterns = [ path('list/',views.VideosListView.as_view(),name ='videos_playlist'), path('list/<str:list_title>/',views.VideosModelListView.as_view(),name ='list_videos'), ] videos/videos_list.html {% extends 'pages/videos.html' %} {% block content %} {% for all_lists in videos_lists %} <p style='text-align:center'><img src="{{ all_lists.list_cover.url }}" alt="No cover" height="450px" width="550px" ></p> #This h2 line generating error and I dont know how to fix it. <h2 style='text-align:center'>Title :<a href="{% … -
How to remove a many to many model field's instance from a particular model in Django
I have an e-learning website where students can enroll into courses and access contents within courses created are created and managed by instructors. But i don't how to make students unenroll from a particular course and then update the course list after unenrolling from a course. Note that the course model has a many to many model field to students. Here's the models.py file of courses app :- class Course(models.Model): owner = models.ForeignKey(User, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(User,related_name='courses_joined',blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title class StudentRegistrationView(CreateView): template_name = 'students/student/registration.html' form_class = UserCreationForm success_url = reverse_lazy('homepage') def form_valid(self, form): result = super(StudentRegistrationView, self).form_valid(form) cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password1']) login(self.request, user) return result Here are the student views in students app:- class StudentEnrollCourseView(LoginRequiredMixin, FormView): course = None form_class = CourseEnrollForm def form_valid(self, form): self.course = form.cleaned_data['course'] self.course.students.add(self.request.user) my_group = Group.objects.get(name='Enrolled') my_group.user_set.add(self.request.user) return super(StudentEnrollCourseView, self).form_valid(form) def get_success_url(self): return reverse_lazy('student_course_detail', args=[self.course.id]) class StudentCourseListView(LoginRequiredMixin, ListView): model = Course template_name = 'students/course/list.html' def get_queryset(self): qs = super(StudentCourseListView, self).get_queryset() return qs.filter(students__in=[self.request.user]) -
Is this the correct way to use a CreateView in Django with an inlineformset_factory?
I've got one master detail relationship beteen Article and Section, and wish to allow a user to add sections on the same page before creating the Article. It seems to work, but I'm also very new to Django, and wonder if I'm doing it right. class ArticleCreateView(LoginRequiredMixin,CreateView): template_name = 'articles/article_add.html' model = Article form_class = ArticleForm success_url = reverse_lazy('index') SectionFormSet = inlineformset_factory(Article, Section, extra=2, can_delete=False, fields=('content',)) def get(self, request, *args, **kwargs): print('get called on article create view') self.object = None #what does this achieve? return self.render_to_response( self.get_context_data(form=self.get_form(), section_form=self.SectionFormSet(), )) def post(self, request, *args, **kwargs): print('post called on article create view') self.object = None form = self.get_form() section_form = self.SectionFormSet(self.request.POST) if (form.is_valid() and section_form.is_valid()): return self.form_valid(form, section_form) else: return self.form_invalid(form, section_form) def form_valid(self, form, section_form): form.instance.author = self.request.user if section_form.is_valid(): print('section form is valid') self.object = form.save() section_form.instance = self.object section_form.save() return HttpResponseRedirect(self.success_url) #return super().form_valid(form) ''' return self.render_to_response( self.get_context_data(form=form, section_form=section_form, )) ''' def form_invalid(self, form, article_form): return self.render_to_response( self.get_context_data(form=form, article_form=article_form)) -
Django Cron package latest version not running on times specified
I am using Django Cron package in a docker container where I specify my cron functions like this: class CreateSnapshots(CronJobBase): RUN_EVERY_MINS = 15 # every 15 mins schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'crontab.cronjobs.CreateSnapshots' def do(self): print("Running CreateSnapshots now..") In my docker-entrypoint.sh for Kubernetes, I specify this: python manage.py runcrons The cronjob doesn't run every 15 minutes as instructed but when I do python manage.py runcrons in the bash of container, the cronjob runs immediately. Any idea why is it not running every 15 minutes as specified? I have specified this in my settings.py: CRON_CLASSES = [ "crontab.cronjobs.CreateSnapshots", ] -
DRF catch-all accept header values
I want DRF to use JSONRenderer for any Accept header, and when I send Accept: */* (or do not send this header at all), it responds with 406: Could not satisfy the request Accept header. How to make it use JSONRenderer in this case? -
How to best create a connection between two models for a booking app?
I am new to Django and relational databases coming from the Firebase world. I am having trouble figuring out the best modelling for a Doctor-Patient booking app and generally how relational dbs work best; I would like to minimize future problems by doing a great job now. I am going to use Django and Django Rest Framework at the backend to feed a React frontend. So far, I've created these models in an clinic app. Patients are going to be part of the users, and so are Doctors class Clinic(models.Model): name = models.CharField(max_length=200) description = models.TextField() accepted = models.BooleanField(default=False) class Doctor(models.Model): clinic = models.ManyToManyField( Clinic, related_name="doctor") first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=240, default="email") appointment_duration = models.IntegerField(default=20) class Secretary(models.Model): clinic = models.ForeignKey( Clinic, on_delete=models.CASCADE, related_name="secretary") name = models.CharField(max_length=200) email = models.EmailField(max_length=240, default="email") doctors_responsible_for = models.ManyToManyField(Doctor) class Patient(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField(max_length=240, default="email") date_of_birth = models.DateField() age = models.PositiveIntegerField(default=0) I'm wondering if I should create a new model for saving bookings but I'm not sure if this booking model should hold every single booking (from any patient to any doctor), considering this app will be used by a lot of people. Or should bookings … -
Django: How to pass user to models.py
I am writing an application where I want to show a list of courses and for each course, a progress bar with the percentage of lessons completed. I am running the logic to calculate this percentage in the models with a property called progress created for the model Course: models.py class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=50) description = models.TextField() allowed_memberships = models.ManyToManyField(Membership) thumbnail = models.ImageField(null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("courses:detail", kwargs={"slug": self.slug}) @property def lessons(self): return self.lesson_set.all().order_by('position') @property def progress(self): completed = lessonsCompleted.objects.filter(course_id=self.id) return int(completed.count() / self.lessons.count() * 100) I would need to take into account who is logged in currently in order to show the progress for that user in each of the courses. I don't know how to pass the user to my models.py so I can take that user into the algorithm and filter only the lessons completed by that user in order to calculate the progress completed on each course. If I had the user I could add that parameter to the filter and get the progress for that user for each course. Here: completed = lessonsCompleted.objects.filter(course_id=self.id, user_id=<somehow get user id of user logged in here>) Here is the template where … -
how can we separate templates like Django in express-handlebars?
I'm new in express-handlebars, and i need to replicate this Django template logic in it. Let's suppose we have this html file called index.html inside a folder called "base" in the template folder of Django: {% include 'base/header_and_search.html' %} {% include 'base/menu.html' %} {% include 'base/menu_filter.html' %} Html code 1 {% block page %} {% endblock %} if, in a html called "my_html2.html" inside "html_files" folder in django template folder, we do this: {% extends 'index/index.html' %} {% block page %} Html code 2 {% endblock %} {% include 'html_files/html3.html' %} How can we replicate this Django template separation logic in express-handlebars? -
Django rest framework - how to post extended user
I have some problem with django rest api and the User model extension by using OneToOneField. I try to send: { "username": "test1", "password": "test", "password1": "test", "profile": { "user": "test1", "test_field": "123", } } and got error: { "profile": { "user": [ "Incorrect type. Expected pk value, received str." ] } } So I suppose, I should create serializer properly - to get and set the current user (which I try to register) Is that kind of the right idea? Could someone give me any advice? My code below: models.py class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) test_field = models.CharField(max_length=640, blank=True) def __str__(self): return self.user.username def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=get_user_model()) views.py: class UserProfileViewSet(viewsets.ModelViewSet): serializer_class = UserProfileSerializer permission_classes = (IsAuthenticated,) # to get data only for current user. def get_queryset(self): return UserProfile.objects.filter(user=self.request.user) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = get_user_model() fields = '__all__' def create(self, validated_data): profile = ProfileSerializer.create(ProfileSerializer(), validated_data) user, created = get_user_model().objects.create(profile=profile) return user -
How do I display data from a database I made in my html website?
so I have this code: {% extends "admin-layout.html" %} {% block content %} <div class="container"> <div class="card"> <div class="card-header"> <h1>Your Profile</h1> </div> </div> <div class="card-body"> <h5>First Name</h5> <h5>Last Name</h5> <h5>Email</h5> <h5>Phone no.</h5> <h5>Age</h5> </div> </div> {% endblock content %} which basically displays te profile of a user to them once they click on profile using the @route The data that will be displayed is using this registration form: {% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> <div class = "row"> <div class="col-md-5 col-sm-12 align-self-center"> <div class="card"> <div class="card-header"> Register </div> <div class="card-body"> <div> {{ form.hidden_tag()}} {{ render_field(form.fname, class="form-control")}} {{ render_field(form.lname, class="form-control")}} {{ render_field(form.email, class="form-control")}} {{ render_field(form.phoneno, class="form-control")}} {{ render_field(form.password, class="form-control")}} {{ render_field(form.confirm_password, class="form-control")}} {{ render_field(form.account_type, class="form-control")}} {{ render_field(form.submit, class="btn btn-primary")}} </div> <a href="{{ url_for('auth.login')}}">Login</a> </div> </div> </div> </div> </div> </form> </div> {% endblock app_content %} Once they enter these details, a database is created with them called app.db with the following code: from peewee import * from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from flaskapp.app import login_manager @login_manager.user_loader def load_user(id): return User.select().where(User.id == id).first() db = SqliteDatabase("app.db") class BaseModel(Model): class Meta: database = db … -
Django - ImportError: No module named 'ws4redis' - Do I need to install django_websocket_redis
I am using django 2.1.1 . When trying to run my django project. I get the error File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'ws4redis' After looking this error up, I read that I needed to install django_websocket_redis I feel like I should not need to install django_websocket_redis because this project was working fine a while ago.Anyways so I tried installing django_websocket_redis using the following way This is what I did: $ pip install django-websocket-redis DEPRECATION: Python 3.5 reached the end of its life on September 13th, 2020. Please upgrade your Python as Python 3.5 is no longer maintained. pip 21.0 will drop support for Python 3.5 in January 2021. pip 21.0 will remove support for this functionality. Processing /Users/Operator/Library/Caches/pip/wheels/48/30/e8/d26a003f39bb60a0c3906a1892fc6f84bf5bbd763c296c6bd8/django_websocket_redis-0.6.0-cp35-none-any.whl Requirement already satisfied: six in ./lib/python3.5/site-packages (from django-websocket-redis) (1.11.0) Requirement already satisfied: greenlet in ./lib/python3.5/site-packages (from django-websocket-redis) (0.4.16) Requirement already satisfied: redis in ./lib/python3.5/site-packages (from django-websocket-redis) (2.10.6) Collecting gevent Using cached gevent-20.6.2.tar.gz (5.8 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Requirement already satisfied: setuptools in ./lib/python3.5/site-packages (from django-websocket-redis) (50.3.0) Requirement already … -
Developing a User Interface for a Twitter Bot
First-time poster here, and novice programmer so I apologize in advance for any stupid questions. I have created a python twitter bot with several uses for automating Twitter actions and help organically grow a user's account. What I would like to do next is develop a user interface for it where people can go and deploy their own versions of my bot by simply replacing the API keys with theirs in a secure manner. Would really appreciate if anyone could point me in the right direction as to any documentation/tutorials I can read up on to find the best way to: Develop and deploy the user interface (Flask or Django?) How to host the python script so each user that visits the site can run their own (this is what I'm really struggling to figure out) Thanks in advance for your time. -
How to serialize joined tables if there are 2 Foreign Key to join the same table with Django Rest Framework?
I have a short model to store football teams and results of their matches. The Match model has a home_team_id and an away_team_id to identify the 2 teams, both of them are the Foreign Key for the Team model. I want to serialize the data from these 2 tables to have the following output: [ { "home_team_id": 283584, "home_team_name": "FC Bayern München" "away_team_id": 61, "away_team_name": "Chelsea FC" "match_id": 12342 "home_team_goals": 1, "away_team_goals": 2, }, ... ] models.py from django.db import models class Team(models.Model): team_id = models.IntegerField(primary_key=True) team_name = models.CharField(max_length=200, blank=False, null=False) #category_id = models.IntegerField(blank=False) #value = models.IntegerField(blank=False) def __str__(self): return '%s' % (self.team_name) class Match(models.Model): match_id = models.IntegerField(primary_key=True) home_team_id = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home_team_id") away_team_id = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away_team_id") home_team_goals = models.SmallIntegerField(blank=False) away_team_goals = models.SmallIntegerField(blank=False) views.py @api_view(['GET']) def full_list(request): full = Match.objects.all() serializer = TeamMatchesSerializer(full, many=True) return Response(serializer.data) serializers.py class TeamMatchesSerializer(serializers.ModelSerializer): team_name = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = Match fields = ('match_id', 'home_team_goals', 'away_team_goals', 'team_name') I am receiving an error: 'Match' object has no attribute 'team_name', which is fair as in views.py the Match model has been selected,however I added team_name = serializers.StringRelatedField(many=True, read_only=True) in serializers. I tried this the other way around, with using the Team model in the … -
How to properly use POST with nested serializer in Django?
This is the first time I am working with Django Rest Framework and I am stuck on a general issue. I tried many other stackoverflow solutions and other solutions available on google but nothing worked for me. My Models: class Gender(models.Model): gender = models.CharField(max_length=10) def __str__(self): return self.gender class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100, default="") city = models.CharField(max_length=20, blank=True) state = models.CharField(max_length=50, blank=True) country = models.CharField(max_length=20, blank=True) zip_code = models.CharField(max_length=6, blank=True) mobile_number = models.CharField(max_length=10, blank=True) birthdate = models.DateField(blank=True, null=True) gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, related_name='user_gender') joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.first_name + ' ' + self.last_name I want when creating a new user, we use gender from only the available genders in the Gender Model My Serializers class GenderSerilizer(serializers.ModelSerializer): class Meta: model = Gender exclude = [ 'id', ] class UserSerializer(serializers.ModelSerializer): gender = GenderSerilizer() class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email_id', 'city', 'state', 'country', 'zip_code', 'mobile_number', 'birthdate', 'gender', ] def create(self, validated_data): gender_data = validated_data.pop('gender') user = User.objects.create(**validated_data) Gender.objects.create(user=user, **gender_data) return user My views class UserViewSet(viewsets.ViewSet): def list(self, request): """ """ queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk): """ """ … -
Get every m2m relation in model as different object in DRF serializer
I have a model ModelA that has M2M relation with ModelB. When I use ListAPIView on ModelA it shows me related models like this: { "id": 1, "ModelA_name": "string", "ModelA_phone_number": "00000000", "ModelB": [ 'modelB_name1', 'modelB_name2' ] } How I can get a list view of this as shown below: [ { "id": 1, "ModelA_name": "string", "ModelA_phone_number": "00000000", "ModelB": "modelB_name1" }, { "id": 1, "ModelA_name": "string", "ModelA_phone_number": "00000000", "ModelB": "modelB_name2" } ] -
Ckeditor is not running
ckeditor is not running because there is that error how can I solve error " render() got an unexpected() keyword argument 'renderer' " -
'path('polls/', include('polls.urls')),' in urlpatters I get 'ModuleNotFoundError: No module named 'polls'' and 'OSError: [WinError 123]
Before including path('polls/',include('polls.urls')) python manage.py runserver work well without error from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), -
cant make connections betwen uploaded image and template django
I'm trying to upload a picture for my post model by admin panel but I can't display it in my template, please help this is my post model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE ,null=True) title = models.CharField(max_length=200,default='a') text = models.TextField(default='a') Img = models.ImageField(upload_to='images/',null =True) and for urls.py i used this code: if settings.DEBUG: # new urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and views.py: def post_list(request): posts= Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'post/index.html', {'posts': posts}) and finally my index.html template: {% for post in posts %} <div class="blog-post-thumb "> <div class="blog-post-image "> <a href="single-post.html "> <img src="{{post.Img.url}}" class="img-responsive " alt="Blog Image "> </a> </div> <div class="blog-post-title "> <h3><a href="single-post.html ">{{ post.title }}</a></h3> </div> <div class="blog-post-format "> <span><a href="# "><img src="images/author-image1.jpg " class="img-responsive img-circle ">A</a></span> <span><i class="fa fa-date "></i> published: {{ post.published_date }}</span> <span><a href="# "><i class="fa fa-comment-o "></i> Comments</a></span> </div> <div class="blog-post-des "> <p>{{ post.text|linebreaksbr }}</p> <a href="single-post.html " class="btn btn-default ">Continue Reading</a> </div> </div> {% endfor %} -
Django app dependencies on Shared hosting(Cpanel)
I've been trying to deploy an Django app in a Shared hosting with Cpanel. But every time that I tried to install google-cloud-automl dependency I get this message on the server Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-vnlg73ta/grpcio/setup.py", line 212, in <module> if check_linker_need_libatomic(): File "/tmp/pip-build-vnlg73ta/grpcio/setup.py", line 172, in check_linker_need_libatomic stderr=PIPE) File "/opt/alt/python37/lib64/python3.7/subprocess.py", line 800, in __init__ restore_signals, start_new_session) File "/opt/alt/python37/lib64/python3.7/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: 'cc' Any idea how I may install this dependency? -
Django-tenants create user in a tenant only
I am currently setting up Django Tenants (https://django-tenants.readthedocs.io/en/latest/) with the Saleor Web Framework (https://github.com/mirumee/saleor-platform). I've managed to get the Saleor GraphQL endpoints up and running for two different sites. However, my users have to be created using the public schema or the login process does not work. For instance if run ./manage.py create_tenant --domain-domain=newtenant.net --schema_name=new_tenant --email=new@gmail.com this doesn't work. But running ./manage.py create_tenant --domain-domain=newtenant.net --schema_name=public --email=new@gmail.com works. The problem with creating in the public schema is that the created user will have access to all of the tenants. Extract from my settings.py SHARED_APPS = [ "django_tenants", "saleor.clients", # Django modules "django.contrib.contenttypes", "django.contrib.sites", "django.contrib.staticfiles", "django.contrib.auth", "django.contrib.postgres", "storages", # Local apps "saleor.plugins", "saleor.account", "saleor.discount", "saleor.giftcard", "saleor.product", "saleor.checkout", "saleor.core", "saleor.graphql", "saleor.menu", "saleor.order", "saleor.seo", "saleor.shipping", "saleor.search", "saleor.site", ] TENANT_APPS = ( # The following Django contrib apps must be in TENANT_APPS "django.contrib.contenttypes", "django.contrib.sites", "django.contrib.staticfiles", "django.contrib.auth", "django.contrib.postgres", "storages", # Django modules # Local apps "saleor.plugins", "saleor.account", "saleor.discount", "saleor.giftcard", "saleor.product", "saleor.checkout", "saleor.core", "saleor.graphql", "saleor.menu", "saleor.order", "saleor.seo", "saleor.shipping", "saleor.search", "saleor.site", "saleor.data_feeds", "saleor.page", "saleor.payment", "saleor.warehouse", "saleor.webhook", "saleor.wishlist", "saleor.app", # External apps "versatileimagefield", "django_measurement", "django_prices", "django_prices_openexchangerates", "django_prices_vatlayer", "graphene_django", "mptt", "django_countries", "django_filters", "phonenumber_field", ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = …