Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fromset ModelChoiceField Initial value
When i edit formset the ModelChoiceField don't show initial value (it show the empty label). I use this example https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html demande\forms.py class LinkForm(forms.Form): etabz = forms.ModelChoiceField(empty_label="Choisir un établissement",\ queryset=Etablissement.objects.all().order_by('univ','etablissement').distinct(), ) # etabz = forms.CharField() def __init__(self, *args, **kwargs): dbz = kwargs.pop("dbz", None) super(LinkForm, self).__init__(*args, **kwargs) if dbz: self.fields["etabz"].queryset = Etablissement.objects.filter(univ__corps=dbz) class BaseLinkFormSet(BaseFormSet): def clean(self): if any(self.errors): return anchors = [] urls = [] duplicates = False for form in self.forms: if form.cleaned_data: dona = form.cleaned_data.get('etabz') anchor = dona.etablissement if anchor : if anchor in anchors: duplicates = True anchors.append(anchor) if duplicates: raise forms.ValidationError( 'Vous ne pouvez choisir le même établissement plusiuers fois.', code='duplicate_etab' ) def __init__(self, *args, **kwargs): super(BaseLinkFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False Demande\views.py @login_required def demande(request): user = request.user corpsorigine = user.profile.corps uz = get_object_or_404(session, active=True, destine = user.profile.corps) choice_links = choix.objects.filter(demandeur = user, session = uz ) link_data = [{'etabz': l} for l in choice_links] LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet, extra=1) if request.method == 'POST': link_formset = LinkFormSet(request.POST,form_kwargs={'dbz':corpsorigine }) if link_formset.is_valid(): new_links = [] for link_form in link_formset: dona = link_form.cleaned_data.get('etabz') try: univ = dona.univ etablissementa = dona.etablissement except: messages.error(request, 'Une exception à provoqué une erreur. veuillez ré-essayer ultérieurement') return redirect(reverse('blog:post_list')) if etablissementa and … -
How to fix reverse-matching URL error in Django?
I'm making a blog app using Django. The error appears when I click on save button on a new post and the 'Post-Detail' page is not just showing up. I'm trying debugging it since last 2 days but still unable to find the solution. I'm using Django(2.1.7) and the error I'm getting is NoReverseMatch at /post/new/ Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>\\d+)/$'] There are some other urls as well but I'm just giving the 2 path that most probably creating the errors. I've tried giving simply redirect_field_name='post_detail' in my CreateView but then I get error saying there's no get_absolute_url() method even when I've already added it in the model. Models.py class Post(models.Model): author = models.ForeignKey('auth.user',on_delete=models.PROTECT) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) objects = models.Manager() comments = models.Manager() def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absoulute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/',admin.site.urls), path('',include(blogapp.urls)), ] blogapp.urls urlpatterns = [ ... re_path(r'^post/(?P<pk>\d+)/$',views.PostDetailView.as_view(), name='post_detail'), re_path(r'^post/new/',views.CreatePostView.as_view(),name='post_new'), ... ] views.py class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin, CreateView): form_class = PostForm model = Post login_url = '/login/' def get_success_url(self): return reverse('post_detail') post_form.html <h1>New Post</h1> <form … -
How to fix failed sql create table auth_permission error
When trying to migrate using python manage.py migrate() I am facing this error: djongo.sq12mongo.SQLDecodeError: Failed SQL: Create table "auth_permission".... djongo version : 2.2.3 pymongo : 3.2.0 sqlparse : 0.2.4 python : 3.7 mongodb version: 4.0.11 mysqlclient : 1.4.2 error Settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'djangoproject1', } } -
How to setup celery worker to log all task function calls to one file
I have Django application with such logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'cron': { 'class': 'logging.FileHandler', 'filename': 'cron.log', 'formatter': 'default', }, 'admin': { 'class': 'logging.FileHandler', 'filename': 'admin.log', 'formatter': 'default', }, 'app': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'core': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'metrics': { 'class': 'logging.FileHandler', 'filename': 'metrics.log', 'formatter': 'default', }, 'pixel': { 'class': 'logging.FileHandler', 'filename': 'pixel.log', 'formatter': 'default', }, }, 'loggers': { 'cron_api': { 'handlers': ['cron'], 'level': 'DEBUG', }, 'main': { 'handlers': ['app'], 'level': 'INFO', }, 'admin': { 'handlers': ['admin'], 'level': 'INFO', }, 'spa_api': { 'handlers': ['app'], 'level': 'INFO', }, 'metrics': { 'handlers': ['metrics'], 'level': 'INFO', }, 'pixel': { 'handlers': ['pixel'], 'level': 'INFO', }, }, } Also I have a celery worker. I want to log every activity that happens inside the task to celery_worker.log, even if task calls a function from main or cron_api application. For example: If main.celery_tasks.task1.task1 calls main.service.google.get_campaign, I want all logs from get_campaign to be in worker.log. Also I want no logs related to this task to be in app.log. How to achieve this? P.S.: Also I'd like to have a scalable … -
is there any way to solve" project=Project.objects.get(pk=pk) "
why is it that when I visit http://127.0.0.1:8000/project/1/ an error occur it says DoesNotExist and when I try http://127.0.0.1:8000/project/2/ it works without any error.i think the problem is either in urls.py or views.py my url code : ` urlpatterns =[ url(r'^$', views.firstindex, name='firstindex'), url(r'^(?P<pk>[0-9]+)/',views.project_detail, name='project_detail'),] and this is the view.py `def project_detail(request,pk): project=Project.objects.get(pk=pk) context={ 'project':project } return render(request,'project/detail.html') . -
NoReverseMatch at /1/ipd/
I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/", One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id views.py @login_required def ipd(request, patient_id): object = get_object_or_404(Patient,pk=patient_id) if request.method == "POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save() return HttpResponseRedirect(reverse('ipd_list', args=[patient_id])) else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'object':object, 'form2': formtwo}) @login_required def ipd_list(request): ipdlist = Ipd.objects.all() return render(request, 'Ipdlist.html', {'ipd': ipdlist }) urls.py re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'), path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ), -
How to connect metamask to django through vscode?
I'm now working with blockchain project in hurry. This is my first project, and I have no idea where to start. All I want to do is Connecting Metamask with django web page. I want delicate description because I don't that much basic programming skills. I first started with this, https://django-web3-auth.readthedocs.io/en/latest/readme.html but is it OK to start in QUICK START menu without any settings in advance? I need your help desperately. Thank you! -
How do I get a background color to fill the entire page and fade into a picture with an svg on top?
I created a grey color background so I could overlay it on top of a picture I currently have. The picture is in a urls.py file and is passed as the background. I want the grey to fade into a picture but the grey background isn't covering up the entire screen just some of it. I know it has to do with the padding and margins probably but I am pretty new to html and css. I also have an animation I made with an svg I want to be on top of the grey background. It is doing the fading part but after 10 seconds the grey color comes back and doesn't disappear. I am also using my django server as my backend to run the website. I have tried making the margins and padding 0 which didn't work and also varying the numbers on the margins and padding which doesn't make it fill the whole website. Here's my code.pen so it's easier to see https://codepen.io/anon/pen/zgzxRz html code <html> <div id="header"> <div id="content"> <head> <style> body { font-family: 'Arimo'; height: 100%; margin: 0; } .animated { background-color:grey; background-repeat: no-repeat; -webkit-animation-duration: 10s;animation-duration: 10s; padding: 0 0; margin:10px; } @-webkit-keyframes fadeOut … -
I've stuck on this for days now gunicorn is using the old virtual environment even after unistalling it and deleting the directory?
I deployed a Django project on an ubuntu server using gunicorn and Nginx but I had to delete the project and use a new Github repo and set a new virtual env so I deleted the virtual env and deleted gunicorn.config and removed and installed Nginx and tried deploying the app it started giving weird errors and finally no when I ran sudo journalctl -u gunicorn i found that it still refers to the old env and gives a file not found error. How can I reset it correctly? -
Django null value in column "project_id" violates not-null constraint
So I can see why this is happening, the page is not linking to the project I am trying to update, but I don't know how this is done, I thought that was what "get_object" method was for, but I'm clearly not using it properly. I can get this working if I uncomment "project" in the form which lets me choose which project I am attempting to update from a dropdown, however, I would like to do away with that field and have the update dynamically linked to the project. Here is my models: class Project(models.Model): date_published = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) area = models.ForeignKey(Area, on_delete=models.PROTECT) title = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=64) summary = models.CharField(max_length=256) others = models.CharField(max_length=128, blank=True) deadline = models.DateField(null=True, blank=True) priority = models.ForeignKey(Priority, on_delete=models.PROTECT) closed = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def __str__(self): return self.title class Update(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='updates' ) category = models.ForeignKey(UpdateCategory, on_delete=models.PROTECT) update = models.TextField(max_length=240, blank=True) added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-added"] def __str__(self): return self.update forms.py class ProjectUpdateForm(forms.ModelForm): update = forms.CharField() class Meta: model = Update fields = [ # 'project', 'category', 'update' ] views.py … -
I want to add dynamic input box on button click and then save the value into database (postgresql)
This is my button <input type="button" value="add-entry" id="add"> This is the ajax call made on clicking the button <script> $(document).ready(function(){ $("#add").click(function(e){ event.preventDefault() var htmlAppend='<div><table><tr><td><input type="text" name="user-name"></td></tr>'+ // '<tr><td><input type="text" name="e-mail"></td></tr>'+ '<input type="button" value="delete" id="delete" /></table></div>' $('#items').append(htmlAppend); localStorage.setItem("htmlAppend", htmlAppend); }); var htmlAppend = localStorage.getItem("htmlAppend"); if (htmlAppend) { $("#items").append(htmlAppend); } $('body').on('click','#delete',function(e){ $(this).parent('div').remove(); }); }); </script> The problem is if I click on button 2 times then the name of the input field will be same then how can I fetch the value of two different text boxes with the same name. Please suggest any other way if possible. -
Child class post method to return different template and context
I want to be able to take the same form input and use it to do calculations (using different urls) for different products and send product results to a product template I tried having a base class with get and post methods from which child classes(different product urls) will inherit especially the post method to remain DRY from .models import InputForm class InputView(TemplateView): template_name = 'input.html' def get(self, request, *args, **kwargs): form = InputForm() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = InputForm(request.POST) if form.is_valid(): self.cleaned_data = form.cleaned_data a =cleaned_data['mbr_l'] b =cleaned_data['es_l'] c =cleaned_data['wic_l'] d =cleaned_data['br2_l'] length = a + b + c + d qty = 0.8*length return render(request, 'result.html', {'qty': qty}) else: return render(request, self.template_name, {'form': form}) class B(InputView): def post(self, request, *args, **kwargs): qty2 = super().post(self, request, *args, **kwargs) return super().render(request, 'result2.html', {'qty2': qty2}) I expect the url B in url conf to do calculation and send context(qty2) to results2.html but it always renders results.html with qty which is correct because B is inheriting InputView and all methods. -
ManyToOneRel field for Following functionality?
I read this question thread ( Difference between ManyToOneRel and ForeignKey? ) and I'm not understanding it completely. I need a many to one relationship so I can add in following functionality. Tried with a many to many and that makes two users follow each other even when one didn't want to (if one user clicks 'follow' then it acts as though the other did the same.) Question is, will I need to use a ManyToOneRel field for the followers (who follows the logged in user) and the same for who the user is following? Forgive me, I'm teaching myself everything and some stuff can be difficult to grasp at times. -
Django 1.8-1.11 upgrade error, AttributeError: type object 'DemoModel' has no attribute 'lower'
I am upgrading my app from Django 1.8 to 1.11. When I try to run migrations or tests I am getting the following error. On debugging I can see that method is_referenced_by_foreign_key is expecting f.related_model to be string, but in my case its actually an instance. Can some one please help with this. ipdb> c Traceback (most recent call last): File "formtastic/manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db run_syncdb=True, File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 163, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 81, in _create_project_state migration.mutate_state(state, preserve=False) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 92, in mutate_state operation.state_forwards(self.app_label, new_state) File "/home/vagrant/.virtualenvs/py3/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 209, in state_forwards not … -
Change button on "<a>" element. Bootstrap 4, html, Django
I am trying to add logout options in my bootstrap menu. After adding, an awful uneven button is created (as in the picture below). How to add the logout form below so that you do not create such a button. <form method="post" action="{% url 'account_logout' %}"> {% csrf_token %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/> {% endif %} <button type="submit">{% trans 'Sign Out' %}</button> </form> My template.html <div class="dropdown-menu dropdown-menu-sm dropdown-menu-right"> <h6 class="dropdown-header">Menu użytkownika</h6> <a class="dropdown-item" href="#"> <i class="fas fa-user"></i>Ustawienia konta </a> <a class="dropdown-item" href="#"> <span class="float-right badge badge-primary">4</span> <i class="fas fa-car"></i>Ogłoszenia </a> <a class="dropdown-item" href="#"> <span class="float-right badge badge-warning">2</span> <i class="far fa-times-circle"></i>Zakończone </a> <!-- I try change this element on my hidden log out form--> <div class="dropdown-divider" role="presentation"></div> <a class="dropdown-item" href="#"> <i class="fas fa-sign-out-alt">Log out</i> </a> </div> Any help will be appreciated -
Django login() doesn't persist after HttpResponseRedirect
I have custom Django login forms that, since upgrading from Django 1.8 to 2.2, no longer keep user logged in after HttpResponseRedirect. Here's is a generalized sample of the code: @render_with('users/login.html') def login_view(request, campaign_id=None): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] # Login user user = authenticate(request, email=email, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/redirect-user/') I know that login() is working properly because if I use render instead of HttpResponseRedirect, the user is logged in. However, I want to redirect the user to a different view after login. What is the best way to do this? -
From views, how do I pass both context and registration form to my registration template?
I'm fairly new to Django and I'm trying to pass both the context and my registration form. I know how to pass either the context, or the form, but not both. Check the last line of the code, that's what I'm trying to figure out. I've tried: return render(request, 'users/register.html', context, {'form': form}) and it doesn't work. There's something wrong with the syntax. from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): context = { 'title': "Register", 'page_title': "Golf App - Register", 'login_title': "Login" } if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account Created for {username}!') return redirect('golf-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) I'm trying to get it so that I can use both the context and form in the template. -
How can I find the hostname and port in the settings django for the full path of the image to be displayed in the email?
So I am trying to give the absolute path for the static folder. Can you point what I am doing wrong? My template looks like <img src="{{ALLOWED_HOSTS}}{% static 'assets/img/logo-ST.png' %}" alt="logo" border="0" width="102"> And in the Settings ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', str) I know I'm doing something wring with the hostname and port, can you please help? -
How to solve the problem of Application labels aren't unique, duplicates: users?
I am trying to makemigrations but it is giving me problem but where are duplicates? settings.py AUTH_USER_MODEL = 'users.User' INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'firstapp.apps.FirstappConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users' ] admin.py admin.site.register(User) models.py from django.contrib.auth.models import AbstractUser from django import forms class User(AbstractUser): Id_card_number = forms.CharField(max_length=15, required=True) -
Django- Dependent Dropdown Form results in "invalid choice" on POST
I'm using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html to add a dependent dropdown to my form, but when I post the data it comes back form invalid with an invalid choice error. In my form's init override, if I eliminate the dropdown queryset then it works, but that defeats the purpose. My view: def add_have(request, id=None): if request.method == "POST": print("User: {}".format(request.user)) for key, value in request.POST.items(): print('{}: {}'.format(key, value) ) form = HaveForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.profile = request.user model_instance.save() else: print(form.errors) print("FORM IS INVALID") return redirect('display_have_list') else: form = HaveForm() return render(request, 'add_have.html', {'form': form}) My form: class HaveForm(forms.ModelForm): class Meta: model = Have fields = ['category', 'item'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category'].queryset=Category.objects.all() self.fields['item'].queryset = Items.objects.none() The error message I'm getting implies that it's not loading the item: web_1 | User: <my_username> web_1 | csrfmiddlewaretoken: <my_token> web_1 | category: 1 web_1 | item: 4496 web_1 | <ul class="errorlist"><li>item<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> web_1 | FORM IS INVALID web_1 | [31/Jul/2019 09:01:24] "POST /trade/add_have/ HTTP/1.1" 302 0 web_1 | [31/Jul/2019 09:01:24] "GET /trade/display_have_list/ HTTP/1.1" 200 2638 web_1 | [31/Jul/2019 09:01:24] "GET /static/css/styles.css HTTP/1.1" 404 1767 If I elimitante the … -
Is it possible to set up a web app that runs a Python script on a schedule?
I have no experience in web app development, but I want to make a project like the following: My school dorm requires you to make a leave request online on Monday in order to leave the dorm on the weekends. My friends and I always forget to do this. I want to make a web app that basically if the user inputs their information, it would automatically make a leave request every Monday for that user. I have a leave request script written, and I'm sure I can figure out how to make a website and store user data in the database. My question is, is it possible in a Django web app to schedule a script to run once every week? I'm planning on deploying to Heroku, would I have to schedule it in Heroku or Django? If this isn't possible in Django, what would I use in order to go about implementing it? I'm sorry for such a vague question, I'm just not sure where to start and I'm very new to web app development. Any help is appreciated! -
How to create modal signup form in Django?
Home Page Screen Shot Modal Screen Shot I'm fairly new to Django so not sure how to solve my problem. I've created a simple UserCreationForm in a view function to sign up new users. However, I can't seem to display the form in a boostrap modal or in my index.html template. I'm thinking by creating a separate view for the sign up form I need to have a separate template and url path to register new users. I'd like to have the sign up modal on the home page and not direct the user to a separate signup page. {% extends "myapp/base.html" %} {% block navbar %} <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Log In</a> </li> <li class="nav-item"> <a class="btn btn-primary nav-item" href="#" role="button" data-toggle="modal" data-target="#myModal"> Sign Up </a> </li> <!-- The Modal --> <div class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Sign Up</h4> <button type="button" class="close" data-dismiss="modal"> &times; </button> </div> <!-- Modal body --> <div class="modal-body"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </form> <div class="border-top pt-3"> <small … -
How to: Run Django Project in Subpath
Okay, so I'd like to start by saying that I am not running NGINX like many of the other questions I've seen.I'm running Gunicorn alongside Whitenoise. My task is to implement scientific plots in a separate directory of an existing website. My problem is getting the django project to not run in the root directory of the website. I need it to run in a directory like 'example.com/app',so that I can call the plotting application from there as opposed to the main webpage. I tried changing the application urls.py to say 'example.com/app/pretty_plots' and navigating to the page that way, but it fails to load all of the resources. Everything works as expected if I change the web access path of the app to '/' (eliminating the original homepage), and navigating to example.com/pretty_plots, but I'd like to leave the home page intact. FORCE_SCRIPT_NAME = '/app' did not do the trick for me either. URLConf mysite/urls.py from django.contrib import admin from django.urls import path, include import plots.plotly_apps urlpatterns = [ path('admin/', admin.site.urls), path('plots/', include('plots.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] The above code works from the root, but not anywhere else. I see no options of configuring Whitenoise to run Django from a subpath. The … -
MultichoiceField in ModelForm for Django with DB relations
This is my first post ever on Stackoverflow so please ignore mistakes. Before posting I had tried a dozen solutions bun none worked. I have table relations in models for users. I need to create a ModelForm to let customer select multiple users for any project from the frontend. I am having hard time implementing it in code. Also for another field I need to limit the choice to one user. Following is the code. Models: class Project(models.Model): project_name = models.CharField(max_length=100) project_users = models.ManyToManyField(User) project_team_lead = models.OneToOneField(User, on_delete=models.CASCADE, related_name='lead') def init(self): return str(self.project_name) Form. class ProjectForm(forms.ModelForm) class Meta: fields = ['project_name', 'project_users', 'project_lead'] View: def projects(request): template = 'projects/projects.html' if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() else: form = ProjectForm() return render(request, template, {'form': form}) HTML: <form action='' method='post'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-primary'>Submit</button> </form> Some help is highly appreciated. -
Django/Python how to define different required fields for different actions?
I can't figure out the "best" way (or the way with least cons) to do this. For example I have a Realestate model and FlatProfile which has a ForeignKey to the Realestate. There are some actions in the system which can or cannot be done according to filled (not null) fields. For example, to be visible on presentation page, the fields name,seller,flatprofile.rooms_count must be filled. On the other hand, to be in a list of Realestates on brochure, different set of fields has to be filled and this set can contain even related fields like flatprofile.rooms_count. My solution: I define two methods on Realestate model. def can_be_on_presentation(self): lst = ["name","seller","flatprofile__rooms"] for fieldname in lst: # check if the field is not null # if null raise Exception Is there a built in way or some pattern to do such thing? This has many cons like the fields are in string format so static analysis won't show error if there is no such field etc...