Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use custom User model on my existing Django project?
In my Django app, I've been using OneToOneField to have extra fields for User model. But, I feel like this way doesn't seem to be seamless as I have to access extra fields with extra JOIN by doing like user.profile.address even though I can minimize the number of queries with select_related. users/models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=50) Also, I need to use email instead of username for user authentication. In that regard, I feel like I should use custom User model by doing something like the below. But, I know that this way will have a conflict with the existing user model on my production database. users/models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) ... As it is up and running database, I can't start over. In that point, does anyone know if there's a way to have a custom User model, keeping existing data? -
Passing variables from Django view to template remains empty
I'd like to pass a variable from my Django view to my template, but the below code doesn't work. I don't get any errors, my template just remains blank. view def view_name(request): now = datetime.datetime.now() today = now.strftime("%A, %b %d, %Y") return render(request, "dash.html", {"today": today}) template <div class="row"> <div class="col-3"> <div class="card text-white bg-primary mb-3"> <div class="card-body"> <p class="card-text"> {{ today|safe }}</p> </div> </div> </div> What am I doing wrong? -
internal server error while trying to run django project with uwsgi
I'm trying to deploy a django app in my centos with nginx+uwsgi i created a fresh django app and set the relevant ini files and everything that was needed to get this new project up and running but when i try to get my main django app running with uwsgi i get the following errors : File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/apps/config.py", line 107, in create entry = module.default_app_config AttributeError: module 'ed' has no attribute 'default_app_config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./restapi/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/apps/config.py", line 110, in create return cls(entry, module) File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/apps/config.py", line 40, in __init__ self.path = self._path_from_module(app_module) File "/opt/python-virtual-env/demo/lib64/python3.6/site-packages/django/apps/config.py", line 73, in _path_from_module "with a 'path' class attribute." % (module, paths)) django.core.exceptions.ImproperlyConfigured: The app module <module 'ed' (namespace)> has multiple filesystem locations (['/srv/www/restapi/ed', './ed']); you must configure this app with an AppConfig subclass with a 'path' class attribute. unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** uWSGI … -
How to make the html file load the specific video
Okay so i'm creating a movie watching site for learning the django framework more, currently i've done that once the user submits their file and title on the django admin panel it will create a folder inside the templates folder where it will copy the movie.html, it will also create a folder named after the title inside the videos folder and then it will move the mp4 into there. Now my issue is actually making the movie.html specifically load that video and have that video title and not other video titles Tried a few things but nothing that made any difference nor that made sense. <body> <header> <div class="container"> <!-- Branding --> <a href="/"><span class="branding">Movies & Other</span></a> <a href="/admin"><span class="adminpanel">Admin panel</span></a> </div> </header> <h1 class="movietitle">Videotitle</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="/videos/" type="video/mp4"> </video> </div> </body> </html> class Video(models.Model): title = models.CharField(max_length=40, blank=False) video_file = models.FileField(name="Upload a mp4 file", upload_to=f"uploadvideos/videos", validators=[FileExtensionValidator(['mp4'])], blank=False) def __str__(self): return self.title @receiver(models.signals.post_save, sender=Video) def execute_after_save(sender, instance, created, *args, **kwargs): if created: # Create a directory in html directory. os.mkdir(f'uploadvideos/templates/uploadvideos/{instance.title}') # Make a copy of the movie.html shutil.copy(dst=f'uploadvideos/templates/uploadvideos/{instance.title}', src='uploadvideos/templates/uploadvideos/movie.html') # Create a directory in /videos os.mkdir(f'uploadvideos/videos/{instance.title}') # Move the uploaded video to the directory created … -
Django ManyToMany not stored
I wrote the following code: related_fixture = Fixture.objects.create(home=home, away=away, total_goals=total_goals, total_away_goals=total_goals_away, total_home_goals=total_goals_home, total_fh_goals=(fh_goals_home + fh_goals_away), total_sh_goals=(sh_goals_away + sh_goals_home), total_home_fh_goals=fh_goals_home, total_home_sh_goals=sh_goals_home, total_away_sh_goals=sh_goals_away, total_away_fh_goals=fh_goals_away, no_default_values=all_fields_populated, league=league, date=date) fixture.related_fixtures.add(related_fixture) fixture.save() print(fixture.related_fixtures) Related to the following model defined in models.py: class Fixture(models.Model): flashscore_id = models.CharField(max_length=200) home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home") away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away") league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True) date = models.DateTimeField() related_fixtures = models.ManyToManyField('self', blank=True) total_goals = models.IntegerField(default=0) total_fh_goals = models.IntegerField(default=0) total_sh_goals = models.IntegerField(default=0) total_home_goals = models.IntegerField(default=0) total_away_goals = models.IntegerField(default=0) total_home_fh_goals = models.IntegerField(default=0) total_home_sh_goals = models.IntegerField(default=0) total_away_fh_goals = models.IntegerField(default=0) total_away_sh_goals = models.IntegerField(default=0) no_default_values = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) When I run the code the print statement returns the following: project.Fixture.None Is there any way to fix this? -
How to save formwizard POST request to a database
How do I save the form_data to a database? forms.py class ContactWizard(SessionWizardView): template_name ='fitness/general.html' def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response('fitness/general2.html', {'form_data': form_data}) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] return form_data -
Why is this Django view being executed twice on post?
I have a Django view that signs a user up to a free trial through Stripe. When the view makes a POST request, it does so twice. I've tried idempotency keys, both after the if request.method == 'POST' line and in the initial rendering of the view. The customer in Stripe always ends up with two identical payment sources and two identical subscriptions to the plan. def start_trial(request): title = 'get started' description = title form = MembershipForm() key = settings.STRIPE_PUBLISHABLE_KEY trial_days = 30 coupon = None custom_message = '' subscription_idempotency = str(uuid.uuid4()) source_idempotency = str(uuid.uuid4()) try: vendor = Vendor.objects.get(user=request.user) custom_message = vendor.message coupon = Coupon.objects.get(vendor.coupon) coupon = coupon.stripe_coupon_id trial_days = vendor.trial_days except Vendor.DoesNotExist: pass try: partner = Partner.objects.get(user=request.user) custom_message = partner.message coupon = Coupon.objects.get(partner.coupon) coupon = coupon.stripe_coupon_id trial_days = partner.trial_days except Partner.DoesNotExist: pass if request.method == 'POST': form = MembershipForm(request.POST) if form.is_valid(): user = request.user plan = Membership.objects.get(type_of=form.cleaned_data['plan']) # stripe needs to attempt to create a customer # TODO what if there's already a membership/subscription? user_membership = UserMembership.objects.get(user=request.user) stripe_subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id, items=[ {"plan": plan.stripe_plan_id} ], trial_period_days=trial_days, coupon=coupon, idempotency_key=subscription_idempotency, ) subscription = Subscription.objects.create( user_membership=user_membership, stripe_subscription_id=stripe_subscription.id) subscription.save() stripe.Customer.create_source(user_membership.stripe_customer_id, source=request.POST.get('stripeToken'), idempotency_key=source_idempotency) user_membership.membership = plan user_membership.save() user.is_subscriber = True user.save() # if … -
Select in template does not update in edit
I have the following code below, which would be the editing of a form of a request I made here for my work, as I had to change some of the views my update has to be manual, and the select field is not getting the result that I'm bringing it from the db, all fields are working except the select. class EditPedido(View): def get(self, request, venda): data = {} venda = fixa.objects.get(id=venda) data['filial'] = venda.regional return render(request, 'fixa/fixa_update.html', data) <select name="filial" class="select form-control" required="" id="filial"> <option value="" selected="">---------</option> {% for filial in filiais %} <option value="{{ filial.id }}">{{ filial.nome }}</option> {% endfor %} </select> -
Is it possible to change username to email on an existing Django project?
I have an existing Django project which is already running on production server. I recently found that I had to re-configure if I want to use email instead of username that is default in Django by doing Custom User Model. Since I already have a running database on production. That doesn't sound like an option for me anymore as it is gonna have a conflict between the default Django User model and the new custom User model. Without having a conflict with the currently running database on production, is there any way to use email over username for user authentication? -
Paginator in Django ListView does not work with get function
Paginator in Django ListView does not work with get function. The forward and backward button appears on the html page, but in no way divides the data into pages. also tried using page_obj instead of page views.py class LessonListView(ListView): model = Lesson template_name = 'edms/lesson/list.html' success_url = '/lessons' paginate_by = 10 def get(self, request): if request.user.is_authenticated: user = request.user if user.is_department_manager or user.is_assistant_department_manager or user.is_dean_manager: documnets = Requested_Documents.objects.filter( lesson__user=user ).order_by("lesson") lessons = {} all_lessons = Lesson.objects.all() for lesson in all_lessons: lesson_id = str(lesson.id) lessons[lesson_id] = { 'lesson': lesson, 'docs': [] } for doc in documnets: lesson_id = str(doc.lesson.id) lessons[lesson_id]['docs'].append(doc) return render(request, self.template_name, { 'lessons': lessons, }) elif user.is_academician: documnets = Requested_Documents.objects.filter( lesson__user=user ).order_by("lesson") lessons = {} for lesson in Lesson.objects.filter(user=user): lesson_id = str(lesson.id) lessons[lesson_id] = { 'lesson': lesson, 'docs': [] } for doc in documnets: lesson_id = str(doc.lesson.id) lessons[lesson_id]['docs'].append(doc) return render(request, self.template_name, { 'lessons': lessons, }) else: return redirect(reverse('edms:login')) list.html <div class ="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_page_obj }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Next</a> {% endif %} </span> </div> ouput all courses listed and written at the bottom of … -
How to check whether all fiels are filled in django register.html?
I am trying to create blog app with Django.I have a register page in my app to create account.But the problem i face is if i leave all field empty and clicko n register is returns ValueError at /register.I need to display message instead of that.I dont know how to procced? #views.py def register(request): if request.method == "POST": email=request.POST['email'] User_name=request.POST['User_name'] Password1=request.POST['Password1'] Password2=request.POST['Password2'] if Password1 == Password2: if User.objects.filter(username=User_name).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') else: user = User.objects.create_user(username=User_name, password=Password1,email=email) user.save(); return redirect('/') else: messages.info(request,'Password Not Matching') else: return render(request,'register.html') -
Serve multiple Django applications from one server
Good morning. I have a dedicated ubuntu server behind my company's firewall. It is using Django, Gunicorn, and Nginx to serve an Intranet application to employees. The original app responds to the URL [server_name]/[original_application_name]. I want to serve additional apps from this server. I have followed this tutorial as I did when setting up the original app. I can run Gunicorn and serve the app, I have created a second systemd service file that appears steady (copied from the original app with paths changed - service runs), same for a new 'sites-available' file in Nginx (copied from original and modified), new .sock file exists, binding appears successful. However, I have yet to hit on the right configuration combination between settings.py [allowed_hosts], [new_app].service, and nginx etc. The original app is running and when I try a URL related to the new app it gives an error saying it cannot find the request in the url.py of the original app. The new app would be used by the IT dept. Ideally, the new URL would be something like: it.[server_name]/[new_application_name]. I have looked through other cases with this problem but most use Apache or are on a public hosting site. I have seen … -
No module named 'django.db.migrations.migration'
recently I pulled from my git the new version of the project, unfortunately I made a mistake and my settings.py file was completly overwrite. I fix it but when I run my apache server and tried to make a request in the logs I found this: [Tue Jun 18 08:47:20.777042 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "<frozen importlib._bootstrap>", line 677, in _load_unlocked [Tue Jun 18 08:47:20.777047 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "<frozen importlib._bootstrap_external>", line 728, in exec_module [Tue Jun 18 08:47:20.777052 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [Tue Jun 18 08:47:20.777057 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "/home/admin/Mefid/venv/lib/python3.7/site-packages/django/contrib/contenttypes/apps.py", line 9, in <module> [Tue Jun 18 08:47:20.777060 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] from .management import ( [Tue Jun 18 08:47:20.777066 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "/home/admin/Mefid/venv/lib/python3.7/site-packages/django/contrib/contenttypes/management/__init__.py", line 2, in <module> [Tue Jun 18 08:47:20.777069 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction [Tue Jun 18 08:47:20.777074 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] File "/home/admin/Mefid/venv/lib/python3.7/site-packages/django/db/migrations/__init__.py", line 1, in <module> [Tue Jun 18 08:47:20.777077 2019] [wsgi:error] [pid 7542] [remote 200.116.66.129:60805] from .migration import Migration, swappable_dependency # NOQA </br> [Tue Jun 18 08:47:20.777112 2019] [wsgi:error] … -
python3 manage.py makemigrations No changes detected
(fcdjango_venv) Subinui-MacBook-Pro:Impassion_community subin$ python3 manage.py makemigrations No changes detected I'm learning Basic Django right now, and was following the lecture, but got problem. I followed the lecture, so first I typed the code on models.py from django.db import models # Create your models here. class Impassionuser(models.Model): username=models.CharField(max_length=64, verbose_name='사용자명') password = models.CharField(max_length=64, verbose_name='비밀번호') registered_dttm = models.DataTimeField(auto_now_add=True, verbose_name='등록시간') class Meta: db_table = 'Impassion_Impassionuser' and then on Terminal, I typed (fcdjango_venv) Subinui-MacBook-Pro:Impassion_community subin$ python3 manage.py makemigrations but the result was No changes detected In the lecture, after typing python3 manage.py makemigrations it shows Migrations for "User" : user/migrations/0001_initial.py - Create model User how can I get the same result? -
Why is my submit button relocated outside Django form when the form is reloaded from invalid post?
I have a template which includes a ModelForm, a ModelFormSet, and a submit button which is supposed to submit all form data from both the Form and FormSet. The problem is, when I submit the data, if the data is invalid, sometimes the template will reload with the submit button relocated outside the form container - how does that even happen? - and though the user can edit the data in the forms to be valid, they are no longer able to submit the form(s). Also, the submit button is not floated. Template: <form method="post" class="form-horizontal"> {% crispy incident_form %} <input type="button" id="delete_field_data" class="btn btn-outline-danger" value="Delete Field Incident Data"> <div id="form_set_class"> {{ incident_formset.management_form }} {% for form in incident_formset %} {{form.non_field_errors}} {{form.errors}} {% crispy form %} {% endfor %} </div> <div id="add_field_data_div"> <p>If the incident occurred in the field, add field incident data.</p> <input type="button" id="add_field_data" class="btn btn-outline-warning" value="Add Field Incident Data"> </div> <p>Add a part deficiency report for each component which needs repair or replacement</p> <input type="button" id="add_def_report" class="btn btn-outline-dark" value="Add Part Deficiency Report"> <div id="empty_form" style="display:none"> <div id="incident___prefix__"> <fieldset> <legend>Part Deficiency Report</legend> {{incident_formset.empty_form}} <br> <input type="button" id='delete_incident___prefix__' class="btn btn-outline-danger" value="Delete Part Deficiency Report" onclick="delete_def_report()"> </fieldset> </div> </div> <input … -
How to pass a variable from Django to TypScript?
In Django I have a template file that looks somewhat like this: my_template.html: <script> let config = '{{ my_config_variable }}'; </script> <script src="{% static 'script.js' %}"></script> script.ts: // do something with the config variable: console.log(config); This would work in JavaScript, because JavaScript doesn't care. But if I try to compile this in TypeScript, I, of course, get error. So, what the right way to pass some variables from Django to TypeScript (and maintain some type safety if possible)? -
How can I combine these two model fields into one?
Let's say I have this model: class ParticipationCount(models.Model): female = models.PositiveIntegerField() male = models.PositiveIntegerField() I would like to combine them permanently into: people = models.PositiveIntegerField() I would like for all the existing male and female ones to both be combined into "people." As we already use this model and have data. Here is the admin: class ParticipationCountAdmin(admin.ModelAdmin): list_display = ("shift_datetime", "shift", "location", "female", "male") search_fields = ["location", "female", "male"] form = ParticipationCountForm So, in summary: How do I combine the "male" and "female" into one field, and continue using this field from here on out, because we don't refer to genders anymore. -
PUT multipart-formdata containing PNG with XMLHttpRequest in vanilla javascript
I'm trying to PUT svg, a string and a png together to a Django REST api from a pure javascript client. I'm currently stuck with error 400 "Upload a valid image. The file you uploaded was either not an image or a corrupted image." response from the backend. The png comes from Pablo's "toImage"-function, which converts the svg to png. The file itself doesn't appear to be corrupt, it opens with python pillow (Which is also used by Django). var formData = new FormData(); var file = new Blob([svgData], { type: 'text/xml'}); var img = Pablo(document.getElementById('stage')).toImage('png', appendImgToFormAndSend); var xhr = new XMLHttpRequest(); xhr.open("PUT", "http://myapi.local/upload_all_the_data"); function appendImgToFormAndSend() { var picture = new Blob([img[0].src], { type: 'image/png'}); formData.append('picture', picture, 'picture1.png') formData.append('rawdata', file, 'rawdata'); formData.append('url', location.href); xhr.send(formData) }; xhr.onload = function() { console.log("ANSWER"); console.log(this.responseText); var data = JSON.parse(this.responseText); console.log(data) } Have I got a conceptual misunderstanding here? -
object has no attribute 'POST'
I am just trying to capture values from a HTML form to MySQL DB using Django framework in Python. Here is the problem I am facing I am getting this error, Error Log, Request Method: POST Request URL: http://127.0.0.1:8000/pages/submitUser Django Version: 2.1.4 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'POST' Exception Location: D:\\...\DjangoApps\commondata\views.py in create_user, line 25 Python Executable: C:\\...\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.7 'User' object has no attribute 'POST' This is what I have in my models.py file, from django.db import models class User(models.Model): user_name = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) user_id = models.CharField(primary_key=True, max_length=255) user_department = models.CharField(max_length=100) email = models.CharField(max_length=70) digital_signature = models.FileField(upload_to='uploads/') In urls.py, path('pages/createUser', commons_views.display_user_form, name='create_user'), path('pages/submitUser', commons_views.create_user, name='submit_user'), In views.py, def display_user_form(request): return render(request, "pages/user_registration.html") def create_user(request): // from the error log line 25 => userdata = User(user_name=request.POST['user_name'], password=request.POST['password'], user_id=request.POST['user_id'], user_department=request.POST['user_department'], email=request.POST['email']) return render(request, "pages/thankyou.html") I refereed stackoverflow and found 2 similar answers but still I am facing the error, 'WSGIRequest' object has no attribute 'Post' Django 'WSGIRequest' object has no attribute 'Post' All of my POST are in capital letters Django Error in Post Request: 'module' object has no attribute 'POST' I have request in create_user function. What would be the problem … -
Trying to update the post in database.But getting Page not found (404)?And want to know how to update the data in database?
I'm trying to create a blog app with django.When clicked on a post it displays that post in separate page.In that i created edit and delete option.When i click on edit it returns edit option.But when i change some content and click on update it returns page not found error. #urls.py from django.urls import path,include from . import views urlpatterns=[ path('',views.homepage), path('register',views.register,name='register'), path('login',views.login,name='login'), path('logout',views.logout,name='logout'), path('newpost',views.newpost,name="newpost"), path('<int:pk>', views.post_detail, name='post_detail'), path('<int:pk>/edit', views.edit, name='edit'), path('update', views.update, name='update'), ] <!---update.html page---> {% extends 'layout.html' %} {% block content %} <div class="box"> <form action="updated" method="POST"> {% csrf_token %} <h3>Title of Post</h3> <input type="text" maxlength="100" name="title" class="inputvalues" value={{post.title}}> <h3>Description</h3> <textarea name="desc" style="width: 500px;margin: 0 auto;padding: 5px;height:40%" >{{post.desc}}</textarea> <a href="update"></a> <button type="submit" id="lg" >Update</button> </a> </form> </div> {% endblock %} #views.py def edit(request,pk): post=Post.objects.get(pk=pk) return render(request,'update.html',{'post': post}) def update(request): post=Post.objects.get(pk=pk) title=request.POST['title'] desc=request.POST['desc'] update = Post(title=title,desc=desc,author_id=request.user.username) update.title= title update.desc= desc update.save(); return redirect('indpost.html') the url for displaying individual post is http://127.0.0.1:8000/48 where 48 is pk_id the url when i click on edit is http://127.0.0.1:8000/48/edit the url when i click on update is http://127.0.0.1:8000/48/updated -
How do i run two command lines in AWS simultaneously?
I have a Django app that I am trying to deploy to AWS. I need two command lines to run the app. One command line will be used to runserver and another one to run a background task. That is how the app runs in my localserver. How do I start two command lines in AWS? Thanks -
Django render() - Reverse for '' not found. '' is not a valid view function or pattern name
This is yet another question involving paths in Django. I have not been able to find my answer anywhere and have done lots of searching on this. The return() function in my view is throwing the error django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name.. Here is my code. When I hit enter on the search bar it will route to the proper view function and do all the necessary computations, but it fails on the render() function. The url I have in my browser is: http://localhost:8000/siren-search/search/?query=jobsite9. Here is a link to my traceback: http://dpaste.com/2KFAW9M# -
Django Admin includes folder templates not customizable
I have a custom model admin template in: ./templates/admin/myapp/mymodel/change_form.html I also want a custom version of ./templates/admin/includes/fieldset.html which, according to the path logic, should be put in: ./templates/admin/myapp/mymodel/includes/fieldset.html My app now loads the specific change_form.html for myapp/mymodel but not the custom fieldset.html. What is the correct path? Ref: https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/includes/fieldset.html https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ -
How to set certain permissions to different "Groups" in Django REST framework
I am trying to let only users in say group 1 to be able to read the api, and then users in group 2 to read or write. I was able to do a very basic version with using permission_classes = (permissions.IsAuthenticatedOrReadOnly,) I'd like to make that functionality more specified to groups instead of just users that login. -
Issue is probably caused by a circular import showing after running django server
i'm trying to runserver for a django project and it shows me this error : django.core.exceptions.ImproperlyConfigured: The included URLconf 'hello.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.` path('articles/', include('articles.url')) --> This line causes the problem, whenever i comment this line django server run appropriately. my urls file of the project : hello.urls from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/',views.about), path('',views.homePage), path('articles/', include('articles.url')), ] my urls for my apps : articles.urls from django.urls import path from . import views urlpatterns = [ path('',views.articleList), ]