Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically chained forms with AJAX
I have two models: class ModelA: field = models.ForeignKey(ModelB) class ModelB: group = models.CharField(choices=GROUPS) subgroup = models.CharField(choices=SUBGROUPS) I have a CreateView for ModelA which i'm trying to dynamically filter with AJAX: class ModelACreateView(CreateView): def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['groups'] = GROUPS // Populate fields in template context['subgroups'] = SUBGROUPS return context def get_form_kwargs(self, **kwargs): kwargs = super(ModelACreateView, self).get_form_kwargs() kwargs.update(request=self.request) // Pass request to a form return kwargs Then in forms: class ModelACreateForm(forms.ModelForm): def __init__(self, *args, request=None, **kwargs): super(ModelACreateForm, self).__init__(*args, **kwargs) group = request.GET.get('group') // Get data from AJAX request subgroup = request.GET.get('subgroup') qs = ModelB.objects.filter(group=group, subgroup=subgroup) self.fields['field'].queryset = qs Here's the script: $("#group_select, #subgroup_select").change(function () { var endpoint = "{% url 'new_model' %}"; // URL to CreateView var group = $("#group_select").val(); var subgroup = $("#subgroup_select").val(); $.ajax({ url: endpoint, data: { 'group': group, 'subgroup': subgroup, }, success: function (data) { $("#id_field").load(" #id_field"); } }); }); But i'm having a problem reloading the field: it renders empty. When i check logs, i see that the form gets the group, loads qs, but then i see another GET request, which doesn't have group from AJAX and i get rendered empty form field. How do i rewrite the AJAX correctly? -
ImportError: cannot import name 'python_3_unicode_compatible' [duplicate]
I upgraded my django to version 3, i have been using it with 2.0 earlier, the problem started after the upgrade then django-allauth is giving me the following error : ImportError: cannot import name 'python_3_unicode_compatible' -
Django - Modify a generic detail view to manage a form and post data - Django
On a webpage, i want to display information about a specific object and have a form to send a message about this object. At the beginning, i used a detail view to display the info about the object. Then a created a message form based on my Message Class I used get_context_data to pass the form in the context for the template. I would like to know if there is a way to manage the validation of the form in the same view or should i come back to a function view? My view: ' class LoanDetailView(DetailView): model = Loan def get_context_data (self, **kwargs): context = super(LoanDetailView, self).get_context_data(**kwargs) msg_form = MessageForm() context['msg_form'] = msg_form return context ' In my template: <form method="POST"> {%csrf_token%} <fieldset class="form-group"> {{ msg_form | crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Envoyer </button> </div> </form> -
Standardising get_success_url
For my classes PostCreateView and PostUpdateView I have the same get_success_url. Is there a way of standardising your get_success_url, I want to avoid writing the code twice? def get_success_url(self): return reverse('post-detail', args=[self.object.pk]) I was working through a tutorial. A limitation of the tutorial though was you were only shown how to load posts by using the posts primary key (https://rossdjangoawesomeapp2.herokuapp.com/post/6/). I modified the code in the tutorial so you could access posts using their title (https://rossdjangoawesomeapp2.herokuapp.com/post/another-test-please-let-it-work/). Which has resulted in me having duplicate code. models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url = models.SlugField(max_length=500, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def get_success_url(self): return reverse('post-detail', args=[self.object.pk]) def form_valid(self, form): form.instance.author = self.request.user # will save the form and redirect to the success_url return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def get_success_url(self): return reverse('post-detail', args=[self.object.pk]) -
Cleaner way to populate data while adding a record
I was wondering if there is a better way to create a record when you have to add data to a lot of fields. country.objects.create(name=name, population=population, code=code, mobile_code=mobile_code, ...) # imagine 10 more fields that have to be filled Moreover, if the field value is none, then use the default value as specified in the model. for example if population variable is None, then don't make population=None, use the default value. -
python 3 simplejson dumps turns django query dict keys to lowercase
python 3.7 I have a POST request that returns a query dict in django like this <QueryDict: {'tbl': ['[{"Unnamed: 0":"0","RecordID":"0","ID":"1","Site Ser ved":"51st Street Academy","Program":"Outreach","Boro":"Queens","Manager":"Steve Waters","Event Date":"2019-11-19","Address":"7605 51st Street ","Zip":"11373"," Activity":"Word on the Street\\n","Grc":"42","ErrorMsg":"ADDRESS NUMBER OUT OF R ANGE","Version":"18D","Suggested Corrected Address":"76-05 51st Ave, Elmhurst, N Y 11373"},{"Unnamed: 0":"1","RecordID":"2","ID":"3","Site Served":"Cardinal Spel lman High School","Program":"Outreach","Boro":"Brooklyn","Manager":"Lee Eastmond ","Event Date":"2019-11-04","Address":"1 Cardinal Spellman Place","Zip":"10466", "Activity":"Alive at 25","Grc":"EE","ErrorMsg":"1 CARDINAL SPELLMAN PLACE NOT RE COGNIZED. THERE ARE 009 SIMILAR NAMES.","Version":"18D","Suggested Corrected Add ress":"1 Cardinal Spellman Pl, The Bronx, NY 10466"},{"Unnamed: 0":"2","RecordID ":"37","ID":"38","Site Served":"St. Marks Day School","Program":"Outreach","Bor o":"Brooklyn","Manager":"Steve Waters","Event Date":"2019-11-06","Address":"1346 Presidnt Street","Zip":"11213","Activity":"My Safety Toolbox\\nSafety Smarts"," Grc":"11","ErrorMsg":"1346 PRESIDNT STREET NOT RECOGNIZED. THERE ARE NO SIMILAR NAMES","Version":"18D","Suggested Corrected Address":"1346 President St, Brookly n, NY 11213"}]']}> i then run simplejson.dumps(variable_holding_query_dict) and it for some reason lowercases the keys '{"tbl": "[{\\"unnamed:0\\":\\"0\\",\\"recordid\\":\\"0\\",\\"id\\":\\"1\\ ",\\"siteserved\\":\\"51st Street Academy\\",\\"program\\":\\"Outreach\\",\\"bor o\\":\\"Queens\\",\\"manager\\":\\"Steve Waters\\",\\"eventdate\\":\\"2019-11-19 \\",\\"address\\":\\"7605 51st Street \\",\\"zip\\":\\"11373\\",\\"activity\\":\ \"Word on the Street\\\\n\\",\\"grc\\":\\"42\\",\\"errormsg\\":\\"ADDRESS NUMBER OUT OF RANGE\\",\\"version\\":\\"18D\\",\\"suggestedcorrectedaddress\\":\\"76-0 5 51st Ave, Elmhurst, NY 11373\\"},{\\"unnamed:0\\":\\"1\\",\\"recordid\\":\\"2\ \",\\"id\\":\\"3\\",\\"siteserved\\":\\"Cardinal Spellman High School\\",\\"prog ram\\":\\"Outreach\\",\\"boro\\":\\"Brooklyn\\",\\"manager\\":\\"Lee Eastmond\\" ,\\"eventdate\\":\\"2019-11-04\\",\\"address\\":\\"1 Cardinal Spellman Place\\", \\"zip\\":\\"10466\\",\\"activity\\":\\"Alive at 25\\",\\"grc\\":\\"EE\\",\\"err ormsg\\":\\"1 CARDINAL SPELLMAN PLACE NOT RECOGNIZED. THERE ARE 009 SIMILAR NAME S.\\",\\"version\\":\\"18D\\",\\"suggestedcorrectedaddress\\":\\"1 Cardinal Spel lman Pl, The Bronx, NY 10466\\"},{\\"unnamed:0\\":\\"2\\",\\"recordid\\":\\"37\\ ",\\"id\\":\\"38\\",\\"siteserved\\":\\"St. Marks Day School\\",\\"program\\":\ \"Outreach\\",\\"boro\\":\\"Brooklyn\\",\\"manager\\":\\"Steve Waters\\",\\"even tdate\\":\\"2019-11-06\\",\\"address\\":\\"1346 Presidnt Street\\",\\"zip\\":\\" 11213\\",\\"activity\\":\\"My Safety Toolbox\\\\nSafety Smarts\\",\\"grc\\":\\"1 1\\",\\"errormsg\\":\\"1346 PRESIDNT STREET … -
Best way to store Machine Learning Models in a django app?
I am trying to build a Django app where a user can upload a CSV file and a sklearn linear model will be created and trained to that dataset. So, each time a new CSV file is uploaded a new model will be created. My question is what is the best way to go about storing these generated models for later use in Django so that users could later choose which model they wanted to use? I have seen some suggestions for pickling them using cpickle and also using Django's cache framework, how would these options affect performance? -
Combine two Django Querysets based on common field
I have two Querysets (actually, list of dicts) like: q1 = M1.objects.filter(id=pk).values('p_id', 'q1_quantity') # q1: <Queryset[{'p_id': 2, 'q1_quantity': 4}, {'p_id': 3, 'q1_quantity': 5}]> q2 = M2.objects.filter(p_id__in=[q1[x]['p_id'] for x in range(len(q1))]).values('p_id', 'q2_quantity') # q1: <Queryset[{'p_id': 2, 'q2_quantity': 2}, {'p_id': 2, 'q2_quantity': 5}, {'p_id': 3, 'q2_quantity': 1}, {'p_id': 3, 'q2_quantity': 7}]> q1 has distinct key:value pairs, while q2 has repeated keys. 1) I want to sum all the values of q2 by common p_id, such that q2 becomes: # q2: <Queryset[{'p_id': 2, 'q2_quantity': 7}, {'p_id': 3, 'q2_quantity': 8}]> 2) Then, merge q1 and q2 into q3, based on common p_id, like: q3 = ? # q3: <Queryset[{'p_id': 2, 'q1_quantity': 4, 'q2_quantity': 7}, {'p_id': 3, 'q1_quantity': 5, 'q2_quantity': 8}]> I have looked into union(). But don't know how to go about summing the queryset (q2) and then merging it with q1. Can someone please help me? -
Django shell does not let me query models
I am trying to query my customized user model "RmkUser" through the django shell, but it keeps raising an error when I try to command "from models import RmkUser": RuntimeError: Model class models.RmkUser doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am not sure why it does this, nor was I able to find out through other posts. I saw that there are a lot of posts which show problems with this error, too, but I can't find a solution for my specific case. I don't understand why django asks me to declare my customized user model "RmkUser" under INSTALLED_APPS. After all, its a model, not an app. My app (as opposed to the "RmkUser" model), however, is entered under INSTALLED_APPS and it also has an app_label. Also, I did set AUTH_USER_MODEL to my customized user model. Not only that, but my site is actually running completely fine when I "python manage.py runserver". I can create new users, log in, etc, no problem. Does anybody know how I can get the shell to let me query the "RmkUser" model? Thanks in advance! -
How to edit my views.py so that unauthorized users can see posts made public?
I have added a 'public' attribute to my models.py to allow users to make their posts public. I am trying to modify my views.py so that public posts are visible to unauthorised users. Here is my code: views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.http import Http404 from .models import BlogPost from .forms import BlogPostForm def check_post_owner(request, post): if post.owner != request.user: raise Http404 @login_required() def index(request): """Home Page for blogs""" posts = BlogPost.objects.filter(owner=request.user).order_by('date_added') context = {'posts': posts} return render(request, 'blogs/index.html', context) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): """A blog post""" title = models.CharField(max_length=30) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): return self.title -
django docs starter app - allow users to create a new poll
I am learning django and I have followed the starter poll app in the docs they provided. I have extended it and have added into a login / register system and I want to make it so that users who are logged in can create a new poll just like how I can do it in the admin panel (obviously without being able to set a date and amount of votes for each choice.) In the admin.py file admin.TabularInLine is used which does not seem right to use for anything else. I have tried looking around for answer and I have had to resort to asking here.Ive attached a screenshot of the admin panel to showwhat I mean. my admin.py from django.contrib import admin from .models import Question, Choice class ChoiceInLine(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['date_posted']}) ] inlines = [ChoiceInLine] list_display = ('question_text', 'date_posted', 'was_published_recently') list_filer = 'date_posted' admin.site.register(Question, QuestionAdmin) my models.py from django.db import models from django.utils import timezone import datetime from django.forms import ModelForm from django.forms.models import inlineformset_factory class Question(models.Model): question_text = models.CharField(max_length=200) date_posted = models.DateTimeField('Date published') def was_published_recently(self): now = timezone.now() return now - … -
Cannot reverse url in template Django
I got stuck with reverse url name in custom-text-form.html file. This is my custom-text-form.html. {% load rest_framework %} <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> </head> <html> <body> <form class="form-horizontal" action="{% url 'tool:custom-text' %}" method="POST" novalidate> {% csrf_token %} {% render_form serializer template_pack='rest_framework/horizontal' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> </body> </html> configs/urls.py. from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import url from django.views.static import serve from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), url(r'^run/media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), path('api/', include('apps.tool.urls')) ] urlpatterns += staticfiles_urlpatterns() tool/urls.py. from django.urls import path, include from django.conf.urls import url from rest_framework.routers import SimpleRouter from .views import CustomTextViewSet, UploadImageViewSet, FormCustomTextView app_name = 'tool' router = SimpleRouter(trailing_slash=False) router.register('upload-image', UploadImageViewSet) router.register('custom-text', CustomTextViewSet) urlpatterns = [ path('', include(router.urls), name='custom-text'), url('form-custom-text', FormCustomTextView.as_view()) ] I got this error NoReverseMatch at /api/form-custom-text when trying request url http://localhost:8000/api/form-custom-text error My TEMPLATES config TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_ROOT, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My folders structure: img1 img2 I was trying to add namespace='tool' in tool/url.py but still not working. Any one could help!! Thanks -
Django set form value equal to another form value in template
I want to get the following goal: I have two forms in one view, form1 and form2. The model are the following: Class Model1(models.Model): var_1=models.CharField() var_2=models.CharField Class Model2(models.Model): var_1=models.CharField() var_3=models.CharField I have just set both form in the same view with a single submit button. Now I want to have the possibility to set var_1 from the form1 also for the var_1 of the Model2 (becouse are equal) when the client fill the form1. It's possible to get it? This one my views.py def example(request): if request.method == 'POST': form1 = Model1Form(request.POST) form2 = Model2Form(request.POST) if form1.is_valid() and form2.isvalid(): print("Il form è valido") new_input1 = form1.save() new_input2=form2.save() else : form1 = Model1Form() form2 = Model2Form() context= { 'form1': form1, 'form2':form2, } return render(request, "", context) -
Error in starting django web app web application, error in passenger_wsgi.py
The Phusion Passenger application server tried to start the web application. But the application itself (and not Passenger) encountered an internal error. The stdout/stderr output of the subprocess so far is '''' stdin: is not a tty Traceback (most recent call last): File "/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 369, in app_module = load_app() File "/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/user/portfolioApp/passenger_wsgi.py", line 1, in import myportfolio.wsgi ImportError: No module named myportfolio.wsgi '''' -
Replace Django-CMS plugin instances with another plugin
Excuse me, if I'm not using the right "django terminology", but I am new to django. I am workin on a website which uses Django CMS and is not responsive. They use different plugins to layout the content. One of them is djangocms_columns to realize multicolumns. Those columns unfortunately are not responsive. I already brought Bootstrap to most of the site but would love to avoid having to replace the multicolumn element on every page. So my idea was one of the following and couldn't find out if it is possible at all. Idea 1 - Overwrite the templates of djangocms_columns The site currently works with width settings in percentage. I'd like to replace those with the col-*-classes of bootstrap. Is it somehow possible to overwrite the templates of a plugin? As far as I understand, this is not a good way to go, so I would prefer the following idea. Idea 2 - Replace the plugin instances with bootstrap-4 plugin instances I found this django cms bootstrap 4 plugins and looking forward to editing the website, I would prefer to replace the multicolumn plugin with this one. Is there a possibility to once replace all multicolumn instances with bootstrap4-row … -
how create booking by following model and with requirement in django
hi working on project …where user create a post and driver see that post and give the user a price of their ride ..when user accept their offer the page will show a order id and confirmation of booking but i tried some code to do that ,but its not working .. this is my models.py of booking class Booking(models.Model): order_id = models.AutoField b_price = models.ForeignKey(price, on_delete=models.CASCADE, related_name='b_prices') b_post = models.ForeignKey(Loader_post, on_delete=models.CASCADE, related_name='b_posts') booked_at = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') status = models.BooleanField(default=False) approved_price = models.BooleanField(default=False) so my question is what will be the view(class) of that model and create a booking confirmation with unique order id where user can track his/her order.how to do that -
Django Admin. Auto update read_only fields based on other fields
This is my model class: class House(models.Model): land_price_per_meter = models.PositiveIntegerField(default=0) land_area = models.PositiveIntegerField(default=0) land_price = models.PositiveIntegerField(default=0) build_price_per_meter = models.PositiveIntegerField(default=0) build_area = models.PositiveIntegerField(default=0) build_price = models.PositiveIntegerField(default=0) total_price = models.PositiveIntegerField(default=0) These fields are read_only : land_price build_price total_price I want Django to calculate the read_only fields itself in the admin change_form as the following (real_time): land_price = land_price_per_meter * land_area build_price = build_price_per_meter * build_area total_price = build_price + land_price -
How to show users own post along with post from users he follows in Django
as part of learning django, I am creating a blog website and also a user follow model. Here in the homepage I am able to see only the posts from the people I follow and not the users own posts. I tried using chained filter/ multiple filter but it seems it doesn't work in this case. Please have a look at this view code and let me know what changes I should make here. @login_required def myhome(request, tag_slug=None): current_user = request.user following_ids = request.user.following.values_list('id',flat=True) actions = Action.objects.filter(user_id__in=following_ids) #Action notification posts_list = Post.objects.filter(user_id__in=following_ids).filter(user=current_user).\ order_by('-post_date') #See only followed people post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts_list = posts_list.filter(tags__in=[tag]) paginator = Paginator(posts_list, 5) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) if following_ids: actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile').prefetch_related('target')[:10] context = { 'page':page, 'posts':posts, 'tag':tag, 'actions':actions, } return render(request, 'posts/users/myhome.html', context) Thanks in advance! -
Can I host a Python scrapping website on Heroku ? If yes , how?
I made a Python scrapping website. I tried hosting it on Pythonanywhere . Its a covid19 website that scrapes data from worldometer . But Pythonanywhere will not let me scrape data from any source that does not have a proper docs or api. Hence I am searching for an alternative and found Heroku to be the best possible one . However, I am facing some problem with the hosting on Heroku too. It would be great if someone could help me out with hosting this scrapping website on Heroku . Thanks in advance. Hoping to hear soon . -
Python (django) regular expression does not work
I have such expression: ^[0-9()|&~ ]*$ It should pass through strings like: '1 & 2 & 3' or '(4&1)|(2&3)' But when I type string: '1 & 2iuasjhdawiudjsa', It passes this string. So then I got an error: "Name 'Trueiuasjhdawiudjsa' is not defined". What's wrong? Why validators.RegexValidator doesn't raise an exception? Please, help! -
I have problems implementing the css and js animation files in my django
settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '@6qt%i+0&_=z0#zl^+!u3bw6c7dmg4e3khboj%7s7439z9#ky(' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hap.apps.HapConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'hookaparty.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'hookaparty.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] base.html <!DOCTYPE html> {% load static %} <html> <head> <title>hookaparty</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Noto+Serif+SC&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/hap.css'%}"> <link rel="stylesheet" href="{% static 'js/hap.js' %}"> </head> <body style="background-color:gray;"> <nav class="nav"> <a href="#" class="nav-item is-active" active-color="orange">Home</a> <a href="#" class="nav-item" active-color="green">About</a> <a href="#" class="nav-item" active-color="blue">Testimonials</a> <a href="#" class="nav-item" active-color="red">Blog</a> <a href="#" class="nav-item" active-color="rebeccapurple">Contact</a> <span class="nav-indicator"></span> </nav> </body> </html> I have posted a link to how i have arranged my files as well: This … -
Deploying Django REST API with Heroku [GET request, infinite loading]
So I'm currently working on a project which looks like: - project-d/ - api/ - app/ - web/ We're focussing on deploying everything inside the api/ folder onto Heroku first. This is where the Django project is located. Steps that I have taken so far: Created a new node on Heroku Added ENV variables (including: DISABLE_COLLECTSTATIC=1, since I don't have static files). My Database (PostgreSQL) is running on a Digital Ocean droplet inside a Docker container (the ports are open). Connect the git project to Heroku (heroku login, heroku git:remote -a special-park) Added the domain of the Heroku project in the ALLOWED_HOSTS in settings.py (see the file here: https://github.com/buzzzlightyear/special-park/blob/deployment/api/specialpark/settings.py) I used Pipfile so there was no need for requirements.txt Added runtime.txt containing python-3.7.6 Added Procfile containing web: gunicorn specialpark.wsgi --pythonpath=specialpark --log-file - Now I pushed everything on to Heroku, since we only want the subdirectory to be deployed I ran this command: git subtree push --prefix api/ heroku master Response: ➜ project-d git:(deployment) git subtree push --prefix api/ heroku master git push using: heroku master Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 12 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), … -
Django/Jquery.formset: how to leave space beetween form of fomrset when using 'add new' button?
I have a 'cosmetic' problem using Jquery.formset. I have a form with nested subform (formset) and I use JQuery to add (or remove) subform (remove and add new buttons) The 'problem' is that subform are added but collapse I would like new subform added inside or something like that but don't know how to proceed... html {% extends 'layouts/base.html' %} {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block extrahead %}{% endblock %} {% block title %}Utilisateurs | Mereva{% endblock %} {% block content %} <!-- Source code: https://codewithmark.com/easily-edit-html-table-rows-or-cells-with-jquery --> <!-- Source code: https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html --> <div class='container'> <br> <br> <h1 id="utilisateur" data-parameters="">Formulaire utilisateur</h1> <br><br> <div class="row"> </div> <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <br><br><div class="dropdown-divider"></div><br><br> <h2>Applications</h2><br><br> <!-- {{ application|crispy }} --> {{ application.management_form }} <div class="row"> <div class="col-6">Nom de l'application</p></div> <div class="col-5"><p>Droits</p></div> <div class="col-1"></div> </div> {% for application_form in application %} <div class="row link-formset"> {% if application_form.instance.pk %}{{ application_form.DELETE }}{% endif %} <div class="col-6"> {{ application_form.app_app_nom }} {% if application_form.app_app_nom.errors %} {% for error in application_form.app_app_nom.errors %} {{ error|escape }} {% endfor %} {% endif %} </div> <div class="col-5"> {{ application_form.app_dro }} {% if application_form.app_dro.errors %} {% for error in application_form.app_dro.errors … -
Django Rest Framework - Register User POST without providing Authentication credentials
I'm trying to write a simple code in my app to register users (it's a custom user that inherits from AbstractUser) using Django Rest Framework. If I post it using the web interface (through localhost:8000/api/v1/pacientes) it works perfectly, I can create normally. However if I try using POSTMAN, for example, I get a {"detail": "Authentication credentials were not provided."} as response. It seems like I'm not providing any Authentication, however this view is for the user to register himself in my app through the frontend, so he's not Authenticated yet. This is driving me crazy, so if anyone has a workaround for it, that would be amazing. urls.py: router = DefaultRouter() router.register('paciente', paciente.PacienteViewSet) urlpatterns = [ path('', include(router.urls)) ] views.py: class PacienteViewSet(viewsets.ModelViewSet): serializer_class = UsuarioPacienteSerializer queryset = Usuario.objects.all() serializers.py class UsuarioPacienteSerializer(serializers.ModelSerializer): def create(self, validated_data): user = Usuario.objects.create_user( username=self.validated_data['username'], email=self.validated_data['email'], tipo_usuario=Usuario.PACIENTE, ) user.set_password(validated_data['password']) user.save() return user class Meta: # model = Paciente model = Usuario fields = ('id', 'username', 'email', 'password') extra_kwargs = { 'password': { 'write_only': True, } } -
update an object with UpdateView and without DetailView Django
I'm looking for a solution to update an object without having to go to the detail page but, just edit it on the page itself. What I want to achieve is when I click on edit: the object becomes a field where I can edit and save it. All the YouTube tutorials show the edit->detail page version. I'm getting an error now because I'm trying to do the same approach as by the delete view and understand that it wants me to edit the object on a separate page. I would like to get some help or tips on this. The error urls.py from django.urls import path from .views import ( HomePageView, TaskCreateView, TaskDeleteView, TaskUpdateView, ) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('task_new/', TaskCreateView.as_view(), name='task_new'), path('<int:pk>/task_delete/', TaskDeleteView.as_view(), name='task_delete'), path('<int:pk>/task_edit/', TaskUpdateView.as_view(), name='task_edit'), ] views.py from django.views.generic import ListView from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.urls import reverse_lazy from .models import Task class HomePageView(ListView): model = Task template_name = 'home.html' context_object_name = 'all_tasks_list' class TaskCreateView(CreateView): model = Task fields = ['text',] class TaskDeleteView(DeleteView): model = Task success_url = reverse_lazy('home') class TaskUpdateView(UpdateView): model = Task fields = ['text',] home.html <!DOCTYPE html> <html> <head> <title>Todo app</title> </head> <body> <h1>Todo app</h1> <ul> {% for …