Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: How to set authentication in `urls.py`?
I'm developing a REST API using the Django Rest Framework. For authentication, I use, django-rest-framework-simplejwt dj-rest-auth I now know how to set up auth for a specific view of an endpoint. But I couldn't find a way of setting a URL pattern protected. For example, I have two apps named an_app and another_app. Here's my project's urls.py file. from django.conf.urls import url from django.urls import path, include urlpatterns = [ path('auth/', include('dj_rest_auth.urls')), path('auth/signup/', include('dj_rest_auth.registration.urls')), path('public_contents/', include('an_app.urls')), path('private_contents/', include('another_app.urls')), ] The two URLs - public_contents and private_contents are both accessible without authenication. I want to make the public_contents accessible by anybody, and want to make the private_contents accessible by the user who has a valid JWT token. How can I do it? -
Django get information from parent modell inline formset in html template
I have a two formsets in a view called ContactIndex, the parent model for this view is my CustomUser model. In this model i have CustomUser.firstname and CustomUser.lastname. I want to render these in my html template but the i cant access the model information by Writing the tag {{ CustomUser.first_name }} How do i render field from parent model in HTML template, can i render these in my view? def ContactIndex(request, CustomUser_id): customuser = CustomUser.objects.get(pk=CustomUser_id) if request.method == "POST": ContactFormset = ContactInlineFormSet(request.POST, request.FILES, instance=customuser) AddressFormset = AddressInlineFormSet(request.POST, request.FILES, instance=customuser) if ContactFormset.is_valid() or AddressFormset.is_valid(): AddressFormset.save() ContactFormset.save() # Do something. Should generally end with a redirect. For example: return redirect ('ContactIndex', CustomUser_id=customuser.id) else: ContactFormset = ContactInlineFormSet(instance=customuser) AddressFormset = AddressInlineFormSet(instance=customuser) return render(request, 'members/member_contact_form.html', {'ContactFormset':ContactFormset, 'Address Formset':AddressFormset }) -
i'm facing some Error during python manage.py makemigrations in django
Foreign Key mismatch Error Foreign Key Constrain Fail and many more error related foreign key and constrain and also delete all the stuff inside a database(Not table) -
How can I read data from huge datasets and achieve data visualisations in Django?
I'm building a Django application which reads data from a very huge dataset, applies various filters from the UI on that dataset, and then displays a visualisation based on the filtered data. The visualisations consist of drawing cluster maps, heatmaps etc, and plotting different types of graphs. Can someone tell me how to go about it? How to read data from datasets using Django, and use it to achieve the above? I found a great python library streamlit for data visualisation, can I integrate streamlit with Django? What other options are there? -
django on cpanel returnt 404 uploading file
i am having a problem uploading files to my server (shareserver) in cpanel. when I upload a file either by admin or by a view it responds 404 if someone has help I would be very grateful settings DEBUG = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static/'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ... urls ...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT, show_indexes= True ) + static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) model class Product(models.Model): name = models.CharField(max_length=50) produc_pic = models.ImageField(default = '',null=True, blank=True) .htaccess <IfModule Litespeed> WSGIScriptAlias / /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/ferre/wsgi.py <Directory /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/ferre> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media/ /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/media/ Alias /static/ /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/static/ <Directory /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/static> Require all granted </Directory> <Directory /home/ibhfrwld/ferre-bianconeri/ferreteria-bianconeri/media> Require all granted </Directory> </IfModule> *************** directory tree **************** -
Dynamic div creation in Streamlit
How do I create dynamic divs with StreamLit framework in Python? Basically I want to create as many divs as there are number of posts in my python list. I want something similar to what is happening in the below HTML code '<div class="mt-3 p-3 bg-white rounded box-shadow border border-gray"> <h6 class="border-bottom border-gray pb-2 mb-0">Verwandte Posts</h6> <div class="media text-muted pt-3"> {% load app_tags %} {% for post in posts.related_posts %} <a href="{% url 'post_detail' post.slug %}">{{ post.title }}</a> </p> {% endfor %} </div> </div>' -
How do I know when and when not to include the 'app_name:' in the django url tag
I was writing my first django program, following instructions from a book. The book wrote url tags like {% url 'learning_logs:index' %} (learning_logs is the app name) but when I tried to emulate that, I got an error until I went with just {% url 'index' %} after reading a post here. Later in my program, after I created another app on the same project called 'users', I was getting the error Reverse for '' not found. '' is not a valid view function or pattern name until I reverted to the initial method used in the book, adding "learning_logs:" before the page names {% url 'learning_logs:index' %}. I need some help on how to recognise when to add the 'name_of_the_app:' and when not to add it in a url tag. Here is some code sample with the 'learning_logs:' included: <h1> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> - {% if user.is_authenticated %} Hello, {{ user.username }} {% else %} <a href="{% url 'users:login' %}">log in</a> {% endif %} </h1> {% block content %}{% endblock content %} And here is how I wrote it with just the url name, which also worked sometimes (This was … -
Form Field is not shown and it can be accessible before just by pressing submit button
I still try to learn Django.I just want to make my form field stay continuously in my template but when ı try, it just can be accessible in my template after by push the submit button. How can ı fix this problem.I have not found any answer yet. At first as you can see in my views.py ı tried to do return render method for either form valid or not but not worked for me views.py class ItemDetailView(FormMixin,DetailView): model=Item template_name='product-page.html' form_class= CO def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: qs=Order.objects.filter(user=self.request.user,ordered=False) context['count'] = qs[0] return context def get_success_url(self): return reverse("shopping:product", kwargs={"slug": self.object.slug}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) return render_to_response(request,'product-page.html',{'form':form}) def form_valid(self,form): number=form.cleaned_data['qualt'] # create item in order_item which come from get_object_or_404 item = get_object_or_404(Item, slug=self.kwargs['slug']) order_item, created= OrderedItem.objects.get_or_create(ıtem=item,user=self.request.user,ordered=False) # create item in order_item which come from get_object_or_404 order_qs= Order.objects.filter(user=self.request.user,ordered=False) # there is any user who haven't had order yet if order_qs.exists(): # Is there any user who haven't had order yet order= order_qs[0] if order.ıtems.filter(ıtem__slug=item.slug).exists(): order_item.quantity += number order_item.save() messages.success(self.request, f'Item added to your cart ({order_item.quantity}) {item.title} in Cart ') else: … -
Django. To show seller's order in order page
Hey guys I am quite new to web development and working on this thing for some days now and I am not able to figure out how to implement it. I want to show all the orders of a particular seller in the seller order page. I was able to successfully implement the order page for customers where customers are able to see their orders. But here I need to show the orders which the seller has got in this page. The problem is its showing all the orders repetitively. How to properly implement it? here are my codes. class SellerOrderManagement(LoginRequiredMixin, View): def get(self, *args, **kwargs): user= self.request.user order = Order.objects.get(user=user, complete=False) seller= Seller.objects.get(user=user) s_order = seller.seller_order.all() orderitems = OrderItem.objects.filter(seller=seller, order__in=s_order) context = { 'seller':seller, 'order':order, 'orderitems':orderitems, 's_order':s_order, } return render(self.request, 'store/seller/seller_order_manage.html', context) html <tbody> {% for o in s_order %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> {% for item in orderitems %} <ol> {{ item.quantity }} x <a style="text-decoration: none; color: black;" href="{{ item.product.get_absolute_url }}">{{ item.product }}</a>&nbsp; </ol> </td> <td>$ {{ item.get_final_price }}</td> {% endfor %} model class Seller(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) seller_name = models.CharField(max_length=20, null=True) seller_description = models.TextField(max_length=1000, blank=True, null=True) class Order(models.Model): seller = models.ManyToManyField(Seller, related_name='seller_order', blank=True) … -
How to display video using Django Detail view?
The following is my model.py class VideoUpload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(null=False, upload_to='my_videos/videos/%Y/%m/%d/') video_thumbnail = models.ImageField(null=False, upload_to='my_videos/thumbnails/%Y/%m/%d/') video_title = models.CharField(null=False, max_length = 120) slug = models.CharField(null=False, max_length=50) date_uploaded = models.DateTimeField(default=timezone.now) the following is my views.py which has both listView and detailView #listView class VideoHome(ListView): model = VideoUpload template_name = 'videoTube/videoDetail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["my_video_list"] = VideoUpload.objects.filter(user=self.request.user) context["other_video_list"] = VideoUpload.objects.exclude(user=self.request.user) return context #detailView class VideoDetailView(DetailView): model = VideoUpload template_name = 'videoDetail.html' my url config is shown below path('<pk>/', VideoDetailView.as_view(), name='video'), Template <p> {{ videoupload.video.url }} {{ videoupload.video_title}} </p> Please let me know how to make the video display. Thank you in advance -
Unhashable type 'dict' after upgrading versions
I'm upgrading all libraries from old versions to newer ones. With the application already running on web, when i try to execute (run) any of the modules in it the following error appears: Environment: Request Method: POST Request URL: http://0.0.0.0:8000/tasks/run/ Django Version: 3.0.7 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'iluvatar.web'] Installed 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'] Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/javier/Documents/iluvatar-master/iluvatar/web/tasks_views.py", line 29, in run workflow_conf=workflow_conf File "/home/javier/Documents/iluvatar-master/iluvatar/core/tasks.py", line 78, in execute queue=module File "/usr/local/lib/python3.6/dist-packages/celery/app/task.py", line 568, in apply_async **options File "/usr/local/lib/python3.6/dist-packages/celery/app/base.py", line 776, in send_task with self.producer_or_acquire(producer) as P: File "/usr/local/lib/python3.6/dist-packages/celery/app/base.py", line 911, in producer_or_acquire producer, self.producer_pool.acquire, block=True, File "/usr/local/lib/python3.6/dist-packages/celery/app/base.py", line 1282, in producer_pool return self.amqp.producer_pool File "/usr/local/lib/python3.6/dist-packages/celery/app/amqp.py", line 623, in producer_pool self.app.connection_for_write()] File "/usr/local/lib/python3.6/dist-packages/kombu/utils/collections.py", line 34, in __getitem__ h = eqhash(key) File "/usr/local/lib/python3.6/dist-packages/kombu/utils/collections.py", line 25, in eqhash return o.__eqhash__() File "/usr/local/lib/python3.6/dist-packages/kombu/connection.py", line 668, in __eqhash__ repr(self.transport_options)) File "/usr/local/lib/python3.6/dist-packages/kombu/utils/collections.py", line 16, in __init__ self.hashvalue = hash(seq) Exception Type: TypeError at /tasks/run/ Exception Value: unhashable type: 'dict' amqp==2.6.0 appdirs==1.4.3 … -
invalid literal for int() with base 10: 'Name' Django
i was trying to create an api get data on excel sheet but getting this error class Task(models.Model): Name=models.CharField(max_length=50,null=False,blank=True,primary_key=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) #viewset def list(self, request): response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks') row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,columns[col_num],font_style) font_style=xlwt.XFStyle() rows=Task.objects.all().values_list('Name','Image1','Image2','Date') for row in rows: row_num+=1 for col_num in range(len(row)): ws.write(row_num,col_num,row[col_num],font_style) wb.save(response) return response -
No Markers show up in Google Map's JS API
So I've Scoured StackOverflow, and I have tried following a few guides on how I might go about it, but have more or less been stuck trying to accomplish this task. What I'm trying to do is document different trees near me on Google Maps, using latitude and longitude. I'm using django to make it a website (it will be especially helpful for easy database management if I ever want to add different tree metrics), and none of my markers are showing up on the map. When checking console on chrome, the only error is the google maps api billing error (which really doesn't matter in this case). Currently, this is my javascript file: var map; var myLatlng; var markers= []; function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: 40.622, lng: -96.948 }, zoom: 17 }); setMarkers(markers); } function addtomarkers(n,lat,long){ var myLatlng = new google.maps.LatLng(lat,lng); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: n }); markers.push(marker) } function setMarkers(){ for(var i = 0; i < markers.length; i++){ i.setMap(map); } } And the following is the code I am using in HTML. I am trying to make the models in my database into markers. <!--Google Map … -
Django relationship : how can I use one to many , since foreign key is working opposite to what I need
I have two models 1-user 2- business Once a user is created , it's business is automatically created. Business table have foreign key relationship to user I want that business can have multiple users linked to it but user should not have multiple business How do I accomplish this ? When I use forging key it doesn't allow me to add multiple user to business , but allow me to create multiple business for a user -
django url tag generating NoReverseMatch
When using the django url tag with a dynamic parameter in a Django template, the following snippet: <ul> {% for m in markets %} <li><a href="{% url 'core:market_detail' market_mic=m.mic %}">{{ m.mic }}</a></li> {% endfor %} </ul> is always generating a NoReverseMatch exception: Error during template rendering In template D:\X\django\project0\core\templates\markets\index.html, error at line 29 Reverse for 'market_detail' with keyword arguments '{'market_mic': ''}' not found. 1 pattern(s) tried: ['core/market/(?P<market_mic>[^/]+)/$'] It is configured like this in core/urls.py: from django.urls import path from . import views app_name = 'core' urlpatterns = [ # ex: /core/market/ path('market/', views.market_index, name='market_index'), # ex: /core/market/XPAR/ path('market/<str:market_mic>/', views.market_detail, name='market_detail'), # ex: /core/market/XPAR/all path('market/<str:market_mic>/all', views.market_all_udls, name='market_all_udls'), When trying to get the reverse with the shell (python manage.py shell), it works: In [5]: reverse('core:market_detail', kwargs={'market_mic': 'XPAR'}) Out[5]: '/core/market/XPAR/' It is likely Django is unable to resolve the market variable in the url tag while elsewhere it is rendering it as expected. -
Django get context data from template response using ajax
I am using ajax to convert my form data to json and sending it to my django view.After successful processing i am returning a template response with some context data which i am not able to refer back in my html.I am stuck getting this to work. Any help would be really appreciated. Below is my html code and my django view View: class CustomerAttributeView(View): """ Saves the attribute details for a user. Updates if already present """ page = 'customer_attributes.html' def get(self, request): return render(request, self.page) def post(self, request): try: user = User.objects.get(id=request.session['user_id']) data = json.loads(request.POST.get('data')) attribute_ids_mapped_to_customer = CustomerAttributeMapping.objects.\ filter(consuming_app_id=user.consuming_app_id).values_list('id', flat=True) #If no attributes mapped to the user then create and return if not attribute_ids_mapped_to_customer: insert_or_update_customer_attributes(user, data) context_data = { 'success_msg': 'Attribute details saved successfully' } return TemplateResponse(request, self.page, context=context_data) except Exception as e: logging.error("Error: " + str(e)) context_data = { 'error_msg': 'Error in saving customer attributes', 'status_code': 400 } return TemplateResponse(request, self.page, context=context_data) AJAX: $.ajax({ url : "customer_attribute/", // the endpoint type : "POST", // http method data : {data:JSON.stringify(attribute_data)}, // data sent with the post request }); urls: urlpatterns = [ url(r'^customer_attribute/',csrf_exempt(CustomerAttributeView.as_view())), ] My HTML code where i am trying to refer the context data i am … -
Lock strategy in Django migrations
I have faced the strange issue. When I run migrate command to run several migrations - it is locked the DB and never finish. But when I run the migrate in the loop for every not-run migration - all is good. Question: is there difference in locking table/DB in 2 cases above? Environment: heroku server, DB on Amazon. -
How to mock django settings attributes in pytest-django
When using Django default unittest it's trivial to patch settings attributes (using @override_settings decorator for instance.) How can I go about achieving this when I'm using pytest-django? -
Unable to send bulk emails in Django models
I have a model named Sample . In models.py, from django.core.mail import send_mass_mail a = Sample.objects.filter(app_id = instance.app_id).values_list('email', flat = True) b = Sample.objects.filter(app_id = instance.app_id).values_list('email', flat = True)[0] subject1 = ['Welcome'] message1 = " you have successfully submitted the request" message2 = " Kindly approve/Reject the request" msg1=(subject1,message1,'noreply@gmail.com',b) msg2=(subject1,message2,'noreply@gmail.com',a) send_mass_mail = ((msg1,msg2), fail_silently = False) The variable "a" has 5 email IDs: <queryset ['John@gmail.com', 'Paul@gmail.com', 'David@gmail.com', 'Mark@gmail.com', 'Justin@gmail.com']> The variable "b" has 1email ID: 'John@gmail.com' Now the problem is while sending email to "b", it is working. But , when I try sending to "a"(to 5 email IDs) , it is throwing error . I suspect it may be due to the queryset. Any idea on how to fix this issue? Thanks in advance! -
In Django, how can i pass information to the server without showing in the link?
i know we can pass information to the function that calls the template that way: from django.urls import path from . import views urlpatterns = [ path("domain/<str:u>/",views.pd) ] in views.py: from django.shortcuts import render def rt(req,u): print(u) return render(req,'teste.html') But how can we do this without showing the information in the link? -
CSS file not loading for django app on gpc
I am trying to run my Django app on gpc and for some reason, the CSS file is not loading for my server. I am getting the message in the image below. The CSS file seems to work properly when I run the server on my local through visual studio code so I am not sure why it's not working on gpc. What could be the reason for it not working and what can I do to fix it? -
Django clean validation firing on all fields instead of specified field?
I'm trying to put some custom validation on a specific field in my model form - following the Cleaning a specific field attribute in the django docs. I need to make sure that if the model instance only has one user with the role "admin" - you shouldn't be able to change that specific user to another role, e.g "admin" → "member" Here's my validation: class ProjectUserEditForm(ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean_role(self): role = self.cleaned_data['role'] user = self.user if ProjectUser.objects.filter(project_id=self.instance.project_id, role='admin').count() == 1: raise ValidationError("The project needs to have at least one admin") return role class Meta: model = ProjectUser fields = ["user_hour_cost", "role"] Now, even if I edit an unrelated field, e.g "user_hour_cost" - my validation is triggered. I want the validation to only be triggered when editing the "role" field (given that count == 1) - not the others. The ProjectUser model if it helps: class ProjectUser(Model): ROLE_CHOICES = ( ('member', 'Member'), ('admin','Admin'), ) user = ForeignKey("accounts.User", on_delete=CASCADE) project = ForeignKey(Project, on_delete=CASCADE) user_hour_cost = DecimalField(max_digits=6, decimal_places=2, default=0) role = CharField(max_length=10, choices=ROLE_CHOICES, default='member') class Meta: db_table = 'projectuser' ordering = ('user',) unique_together = ('project', 'user',) Where am I failing? -
Django Queryset Values of Children and Parent
I am looking for a way to retrieve a parent field during a query of the the children records. At this time I have the following example model. class Record(models.Model): event_title=models.CharField(max_length=500) event_description=models.CharField(max_length=4000) class SecondTable(models.Model): event_code=models.ForeignKey(Record, default=0, on_delete=models.CASCADE) wasfun=models.BoolField(default=True) When I view the values of the queryset and select_related below, the values from the parent don't seem to be included (i.e. event_description). However, the .query property shows all the fields being selected. SecondTable.objects.all().select_related("event_code").values() Is there a way to see all values from the joined tables? Sorry for a newbie question. Thanks! -
What is this Django "JSReverse" Route doing?
Working with a Django tutorial, i encountered a /JSreverse route. I don't know what is this for, it only returns this: this.Urls = (function () { "use strict"; var data = {"urls": [["admin:app_list", [["admin/%(app_label)s/", ["app_label"]]]], ["admin:auth_group_add", [["admin/auth/group/add/", []]]], ["admin:auth_group_autocomplete", [["admin/auth/group/autocomplete/", []]]], ["admin:auth_group_change", [["admin/auth/group/%(object_id)s/change/", ["object_id"]]]], ["admin:auth_group_changelist", [["admin/auth/group/", []]]], ["admin:auth_group_delete", [["admin/auth/group/%(object_id)s/delete/", ["object_id"]]]], ["admin:auth_group_history", [["admin/auth/group/%(object_id)s/history/", ["object_id"]]]], ["admin:auth_user_password_change", [["admin/users/user/%(id)s/password/", ["id"]]]], ["admin:exampleapp_choice_add", [["admin/exampleapp/choice/add/", []]]], ["admin:exampleapp_choice_autocomplete", [["admin/exampleapp/choice/autocomplete/", []]]], ["admin:exampleapp_choice_change", [["admin/exampleapp/choice/%(object_id)s/change/", ["object_id"]]]], ["admin:exampleapp_choice_changelist", [["admin/exampleapp/choice/", []]]], ["admin:exampleapp_choice_delete", [["admin/exampleapp/choice/%(object_id)s/delete/", ["object_id"]]]], ["admin:exampleapp_choice_history", [["admin/exampleapp/choice/%(object_id)s/history/", ["object_id"]]]], ["admin:exampleapp_question_add", [["admin/exampleapp/question/add/", []]]], ["admin:exampleapp_question_autocomplete", [["admin/exampleapp/question/autocomplete/", []]]], ["admin:exampleapp_question_change", [["admin/exampleapp/question/%(object_id)s/change/", ["object_id"]]]], ["admin:exampleapp_question_changelist", [["admin/exampleapp/question/", []]]], ["admin:exampleapp_question_delete", [["admin/exampleapp/question/%(object_id)s/delete/", ["object_id"]]]], ["admin:exampleapp_question_history", [["admin/exampleapp/question/%(object_id)s/history/", ["object_id"]]]], ["admin:index", [["admin/", []]]], ["admin:jsi18n", [["admin/jsi18n/", []]]], ["admin:login", [["admin/login/", []]]], ["admin:logout", [["admin/logout/", []]]], ["admin:password_change", [["admin/password_change/", []]]], ["admin:password_change_done", [["admin/password_change/done/", []]]], ["admin:users_user_add", [["admin/users/user/add/", []]]], ["admin:users_user_autocomplete", [["admin/users/user/autocomplete/", []]]], ["admin:users_user_change", [["admin/users/user/%(object_id)s/change/", ["object_id"]]]], ["admin:users_user_changelist", [["admin/users/user/", []]]], ["admin:users_user_delete", [["admin/users/user/%(object_id)s/delete/", ["object_id"]]]], ["admin:users_user_history", [["admin/users/user/%(object_id)s/history/", ["object_id"]]]], ["admin:view_on_site", [["admin/r/%(content_type_id)s/%(object_id)s/", ["content_type_id", "object_id"]]]], ["exampleapp:detail", [["exampleapp/%(pk)s/", ["pk"]]]], ["exampleapp:index", [["exampleapp/", []]]], ["exampleapp:results", [["exampleapp/%(pk)s/results/", ["pk"]]]], ["exampleapp:vote", [["exampleapp/%(question_id)s/vote/", ["question_id"]]]], ["js_reverse", [["jsreverse/", []]]]], "prefix": "/"}; function factory(d) { var url_patterns = d.urls; var url_prefix = d.prefix; var Urls = {}; var self_url_patterns = {}; Can someone help me understand what this route is doing? Is just a simple Polls app in Django with react. P.D: Is just some part of the code, there are more functions … -
IntegrityError at /notes/add NOT NULL constraint failed: notes_app_note.active
this is views.py page in django my code does not work because there is in the save() method erro message: 'IntegrityError at /notes/add NOT NULL constraint failed' def add_note(request): if request.method == 'POST': f=NoteForm(request.POST or None) if f.is_valid(): new_form=f.save(commit=False) new_form.user=request.user new_form.save() else: form = NoteForm() context = {'form':form} return render(request,'add.html',context)