Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include dynamic data to django url template tag
Say i have a url in my template like this `<a href="{% url 'dashboard:clinic:users' %}">users</a>` Now in the aspect of clinic, it's not static but dynamic. That means it can also be like this: `<a href="{% url 'dashboard:laboratory:users' %}">users</a>` how can i include a variable inside the url template tag to replace clinic with the variable content. -
I am using Django filterset on 2 fields. Need to display distinct values in the second field and if possible only the dependent values
I have a model that has 2 fields which are FK to 2 different tables. I am writing a filter on these 2 fields. Field 2 has non-unique values. How can I do a distinct on the filter field? class SessionFilter(django_filters.FilterSet): module = django_filters.CharFilter(distinct="True") class Meta: model = Session fields = ['subject', 'module', ] Models.py class Module(models.Model): STATUS_TYPES = ( ('Active', 'Active'), ('Inactive', 'Inactive'), ) topic = models.CharField(max_length = 200) teacher_name = models.CharField(max_length = 100) status = models.CharField(max_length=30, default='Active', choices=STATUS_TYPES) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) created_dt = models.DateTimeField(default=datetime.now) def __str__(self): return self.topic class Meta: db_table = 'modules' class Session(models.Model): grade_level = models.CharField(max_length = 30) num_students = models.IntegerField(default=0) session_dt = models.DateTimeField(default=datetime.now) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) module = models.ForeignKey(Module, on_delete=models.CASCADE) school = models.ForeignKey(School, on_delete=models.CASCADE) def __str__(self): return self.school.school_name + ' on ' + self.session_dt class Meta: db_table = 'sessions' The filter form does not have any dropdown for module. However, if I remove the first line then I get duplicates in my search form. Ideally I want to restrict to the "topics" related to the subject and with no duplicates. I am a newbie to both Django and Python. -
How do I manipulate text submitted in a Django form?
I want the user to be able to input a word, click "submit", and then see their word in all caps on the next page. (This is not my final intention, just a useful way to progress). views.py: from django.http import HttpResponse from django.template import loader from .models import Word from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import WordForm def wordinput(request): if request.method == 'POST': form = WordForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = WordForm() return render(request, 'word.html', {'form': form}) def your_word(request): form = WordForm() if request.method == 'POST': # and form.is_valid(): word = WordForm(request.POST) word = str(word) word = word.upper() return HttpResponse(word) else: return HttpResponse("that didn't work") forms.py: from django import forms class WordForm(forms.Form): your_word = forms.CharField(label='Type your word here', max_length=100, required = True) word.html: <form action="/wordsearch/your-word/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Search"> </form> urls.py: from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('wordinput/', views.wordinput, name='wordinput'), path('your-word/', views.your_word, name='your_word') ] Result: TYPE YOUR WORD HERE: ASDF ((In this result, "ASDF" is in a box and manipulable)) Desired result: ASDF ((The desired result is simply on the screen)) -
ajax django login system not working, it returns user as none
I am new in django i am trying to create a user registration and login system. I can register users but somehow it does not log them in. the logout system also works out fine. I don't know what i'm missing here is my code def register(request): if request.method == 'POST': data={} firstname = request.POST['firstname'] surname = request.POST['surname'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm = request.POST['confirm'] if password == confirm: # check username, so that we do not repeat usernames if User.objects.filter(username=username).exists(): data['error'] = "This username is taken" print(data) else: if User.objects.filter(email=email).exists(): data['error'] = "This email is already assigned to another user" print(data) else: user = User.objects.create_user(username=username, email=email, first_name=firstname, last_name=surname) if password: user.set_password(password) else: user.set_unusable_password() user.save() user = authenticate(request, username=username, password=password) login(request, user) data['success'] = "You are successfully registered" print(data) else: data['error'] = "passwords do not match" print(data) return HttpResponse(simplejson.dumps(data), content_type = "application/json") def my_login(request): if request.method == 'POST': data = {} username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) print("it all checks out so far") if user is None: print('no user') if user is not None: if user.is_active: print("user exists") login(request, user) print("you are logged in") else: data['error'] = "username or password … -
Wagtail / CodeRedCMS: jQuery ReferenceError $ is not defined, can't determine reason why
I'm using CodeRedCMS which is built on Wagtail (which is built on Django), and I can clearly see that jQuery is properly getting imported into each page, however when trying to access my flipclock.js function I'm getting a ReferenceError and the clock isn't loading. HTML module in Wagtail Admin page: <div class="clock"></div> <script type="text/javascript"> var clock; $(document).ready(function() { // Grab the current date var currentDate = new Date(); // Set some date in the future. In this case, it's always Jan 1 var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1); // Calculate the difference in seconds between the future and current date var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000; // Instantiate a coutdown FlipClock clock = $('.clock').FlipClock(diff, { clockFace: 'DailyCounter', countdown: true }); }); </script> Base.html: {% extends "coderedcms/pages/base.html" %} {% load static %} {% block custom_assets %} {# Add your custom CSS here #} <link rel="stylesheet" type="text/css" href="{% static 'website/css/custom.css' %}"> {% endblock %} {% block custom_scripts %} {# Add your custom JavaScript here, or delete the line below if you don't need any #} <script type="text/javascript" src="{% static 'website/js/custom.js' %}"></script> <script type="text/javascript" src="{% static 'website/js/flipclock.min.js' %}"></script> {% endblock %} CodeRedCMS automatically imports Bootstrap and … -
Django rest framework PUT slow on large model
I am updating an entire Django model through the DRF API. The model has a large number of entries (> 2000). So far I have been doing the following: import requests for i in range(max_display): payload = {'a':name[i],'b':surname[i],'c':email[i]} r = requests.put('http://localhost:8000/api/v1/list/' + str(i+1) + '/', data=payload) But this loop is slow. I was wondering if there was a way to dump the whole database into the DRF API. Something where I can update all the a keys by the whole name vector without having to use a slow loop. I think this should be possible since I am updating all the model and I do not have unchanged exceptions. -
How can I configure my Django view class to have a file upload to a certain folder?
I am combining two Django apps, chunked_upload and filer, so I can have a file system that can upload large files via chunking. filer is based on ajax_upload which imposes file size limits. I am near completion, but I still need to direct my chunked_upload file to the folder I am currently in (for now, all files upload to unsorted uploads no matter the folder url I am in). Since the chunked_uploadupload button is ajax/javascript based, I must refer to my Django urls to then access a view. Is there a way to translate the old ajax-based upload button from filer into the new django-based upload button from chunked_upload to reference a folder_id? (or basically convert filer-ajax_upload to api_chunked_upload as seen in my urls) chunked_upload.views.py (where the new upload view resides) class ChunkedUploadView(ChunkedUploadBaseView): """ Uploads large files in multiple chunks. Also, has the ability to resume if the upload is interrupted. """ field_name = 'file' content_range_header = 'HTTP_CONTENT_RANGE' content_range_pattern = re.compile( r'^bytes (?P<start>\d+)-(?P<end>\d+)/(?P<total>\d+)$' ) max_bytes = MAX_BYTES # Max amount of data that can be uploaded # If `fail_if_no_header` is True, an exception will be raised if the # content-range header is not found. Default is False to match Jquery … -
PermissionError:Errno 13 Permission denied
My site should scrape some data from another, everything worked on my computer. I put my app on a server and this error occurs. I changed permission to 777 and didn't work. I'm using python3, apache 2.4 on ubuntu 18.10. PermissionError at /scrape/ [Errno 13] Permission denied: FILENAME Error log: [Tue Sep 24 20:54:41.981186 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] File "/home/matms/django_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner [Tue Sep 24 20:54:41.981190 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] response = get_response(request) [Tue Sep 24 20:54:41.981192 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] File "/home/matms/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response [Tue Sep 24 20:54:41.981195 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] response = self.process_exception_by_middleware(e, request) [Tue Sep 24 20:54:41.981198 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] File "/home/matms/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response [Tue Sep 24 20:54:41.981201 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Tue Sep 24 20:54:41.981204 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] File "/home/matms/django_project/news/views.py", line 96, in scrape [Tue Sep 24 20:54:41.981207 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] with open(local_filename, 'wb') as f: [Tue Sep 24 20:54:41.981211 2019] [wsgi:error] [pid 29114:tid 139877711529728] [remote 89.78.216.206:53391] PermissionError: [Errno 13] Permission denied: '4MsktkpTURBXy9kOWRiYWQ4Yzk2ZDkyYjk2YjNiYmRhZjNhNDdiMWQ2NC5qcGeTlQMARc0EAM0CP5MFzQEUzJuVB9kyL3B1bHNjbXMvTURBXy83MWUxOGYwMDNhYWE1ODk3NTIwMmFmNTk0OGZmNmZjMS5wbmcAwgA.jpg' [Tue Sep 24 20:54:41.981217 … -
Using Vue to filter dom objects
I have a list of items that are rendered on the server by Django. Them with the Django template language to render a list. The list is the list of dom objects. On that item in the list, I have two data attributes that are text strings. What I want to do is use Vue to filter the list based on those attributes. What I was doing was using v-if to display items based on what was selected from two lists that contained matching data variables to the data-attributes. The problem that I'm running into is, I can only get a two-part filter. So, I can only get this to work if I filter the first one thing and then the other. What I want to happen is filter the list by whatever dropdown is selected first and then further refined by the second one. So, my question is, should I recreate the list in Vue Data components and then filter them or am I thinking about the v-if wrong? Here' my dom object with the v-if: <div class="page" data-example-1="{{ product.value.example-1 }}" data-example-2="{{ product.value.example-2 }}" v-if="example-1 === '{{ product.value.example-1 }}' && example-2 === '{{ product.value.example-2 }}'"> <h3 class="is-title is-3">{{ product.value.title … -
django.jQuery $ is not a function message
in my django project i would to clean a field value based on an event in another field on a django admin add/edit form. i insert in the admin/change_form.html my call to js : {{ block.super }} <script type="text/javascript" src="{% static 'js/admin.js' %}"></script> {{ media }} {% endblock %} then my admin.js: (function($) { $(document).ready(function() { $("select[name='main_id']").change(function() { $("select['test_id']").val(''); }); }); })(django.jQuery); but when i open my django-admin page in console i get: Uncaught TypeError: $ is not a function on the "$(document).ready(function() {" line. Someone can help me with this error? So many thanks in advance -
How can I integrate Django Import Export and Wagtail?
I'm trying to add a model resource from django-import-export into the admin for Wagtail. The only documentation I can find says that you would do it through hooks. The problem is, I keep getting the error: missing 2 required positional arguments: 'model' and 'admin_site' The whole resource and ModelAdmin are: class AccountResource(resources.ModelResource): class Meta: model = Account fields = ('first_name', 'last_name', 'email', 'created', 'archived') class AccountsAdmin(ImportExportModelAdmin, ModelAdmin): resource_class = AccountResource model = Account menu_label = 'Accounts' # ditch this to use verbose_name_plural from model menu_icon = 'group' # change as required menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd) add_to_settings_menu = False # or True to add your model to the Settings sub-menu exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view list_display = ('first_name', 'last_name', 'email', 'created', 'archived') search_fields = ('first_name', 'last_name', 'email', 'created') # Now you just need to register your customised ModelAdmin class with Wagtail modeladmin_register(AccountsAdmin) Any suggestions? -
Pivotal/Django settings for user provided MSSQL database
I deployed a django application on Pivotal Cloud Foundry. While in development, I just stuck with the built in sqlite database while getting the UI together (didn't need to retain data so pushing/deleting wasn't an issue). I've since developed an MSSQL back end in an on-prem server (Azure..but on prem). My organization doesn't allow public IP services, so anything other than spring applications in Pivotal isn't allowed. On my Windows laptop, I have no issue speaking to the database (settings.py): ''' DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'xxx.database.windows.net', 'Port': '', 'NAME': 'Django_Admin', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', 'username': 'xxx', 'PWD': '***', 'Authentication': 'ActiveDirectoryPassword', } } } ''' When I deploy to PCF, however, I receive the error "('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")" And I get the error for any driver I try...17,13,w/e... I created a user provided service in PCF using my database's connection string. How do I call that user provided service in my settings.py? I found how to call it if it was a PCF provided services, but how would I call it since it's a user provided service? Thanks … -
Take data from database with javascript
In a Javascript function I need data from the database. What should I use XMLHttpRequest or fetch() or Ajax? I tryed the first one but somewhere I read is old and fetch() is to be prefered. I'm a beginner, anyway my file.js: function FilterBy(selezione) { ... var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { document.getElementById("test").innerHTML = this.responseText; } }; //xhttp.open("GET", "lists/getlistname/?m="+maschio+"&f="femmina+"&n="neutro+"&l="linguaggio+"&i="initial", true); //xhttp.open("GET", "/lists/getlistname/?maschio=True", true); xhttp.open("GET", "/lists/getlistname/", true); //xhttp.send("m="+maschio+"&f="+femmina+"&n="neutro+"&l="linguaggio+"&i="initial"); xhttp.send("maschio=True&femmina=False&neutro=False&linguaggio=romano&initial=a"); } I made some tentative but the parameters doesn't arrive to my view. Also can I use a url django style, like lists:getlistname? here my url.py: urlpatterns = [ ... path('getlistname/', views.getlistname, name='getlistname'), ] my views.py: def getlistname(request, maschio, femmina=True, neutro=True, linguaggio='tutti', initial='0'): ... return HttpResponse('hi') So, what happens? the view getlistname is called but the parameters aren't passed (it uses the default). -
design student results database with django
i'm looking for advice to improve my database design in order to get better result i'm trying to create an online system for a high school grade results with django something like that : the admin enter the marks for each subject in courses? teen = '10th' eleven = '11th' twelve = '12th' class_choices = ( (teen , teen), (eleven , eleven), (twelve , twelve),) male = 'male' female = 'female' gender = ((male , male), (female , female),) 1st = '20' 2nd = '30' 3rd = '20' 4th = '30' seasons = ((1st , 1st), (2nd , 2nd) (3rd , 3rd), (4th , 4th)) class ClassLevel(models.Model): class_level = models.CharField(max_length=20 , choices=class_choices , default='' , unique=True) courses = models.ManyToManyField(Courses) class StudentProfile(models.Model): student_id = models.CharField(blank=True , max_length=30) name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) image = models.ImageField(upload_to='profile_images/' , default='logo.png') class_level = models.ManyToManyField(ClassLevel) gender = models.CharField(choices=gender ,default=male, max_length=10) date_of_join = models.DateTimeField(default=datetime.datetime.now) class Courses(models.Model): season = models.CharField(choices=seasons , max_length=10) math = models.PositiveIntegerField() science = models.PositiveIntegerField() english = models.PositiveIntegerField() physic = models.PositiveIntegerField() chimestry = models.PositiveIntegerField() def pre_save_student_id(sender,instance , *args,**kwargs): if not instance.student_id: instance.student_id = generate_id(instance) pre_save.connect(pre_save_student_id,sender=StudentProfile) is it fine or there is a better design to achieve the absolute solution -
How do I delete sessions when a user logs out Django?
I'm learning Django. I created the Sign out function. But when I loop with for it gives an error. My Code: def logout(request): for key in request.session.keys(): del request.session[key] return redirect('login') But get this error ? I am using Python 3. Can you help me ? RuntimeError at /logout/ dictionary changed size during iteration -
How can I use a model instance to filter a queryset in django
I'm new to Django and I need to declare a field wich stores the number of trials of a delivery, and for that I need to verify how many delivery trials were attempted for a given package, but when I try to filter the objects where package_id is the same from the current certification I get an error Saying 'self' is not defined. what am I doing Wrong? I've tried before using models.F('package_id') instead of self.package_id, but this gives me all objects because it checks the package_id of each instance against itself. class Package(models.Model): content = models.CharField(max_length=150) weight = models.FloatField() destiny = models.ForeignKey(Company) class Certification(models.Model): def increment_trial(self): last = Certification.objects.filter( package_id=self.package_id).order_by('trial').last() if not last: return 1 else: return last.trial + 1 date = models.DateField(auto_now_add=True) package = models.ForeignKey(Package, on_delete=models.CASCADE) trial = models.IntegerField(default=increment_trial(self)) note = models.TextField() I want some way of referencing the instance itself inside of the filter, or other way to reproduce the described behavior. PS: I barely speak english. -
Filter a Django queryset based on specific manytomany relationships
I have models similar to the Django documentation's pizza example: class Pizza(models.Model): name = models.CharField() toppings = models.ManyToManyField('Topping') def __str__(self): return self.name class Topping(models.Model): name = models.CharField() def __str__(self): return self.name And a few toppings with the expected pizzas: >>> pepperoni = Topping.objects.create(name='pepperoni') >>> sausage = Topping.objects.create(name='sausage') >>> pineapple = Topping.objects.create(name='pineapple') >>> olives = Topping.objects.create(name='olives') >>> ... How can I create a query that will return only return pizzas that have a topping of pepperoni, or sausage, or both pepperoni or sausage? Something like this will include a pizza that has pepperoni and olives, which I don't want: >>> Pizza.objects.filter(toppings__in=[pepperoni, sausage]) I can create a list of all toppings except the two I want and use that as an exclusion: >>> toppings_i_do_not_want = Topping.objects.exclude(name__in=['Pepperoni', ['Sausage']) >>> toppings_i_want = Topping.objects.filter(name__in=['Pepperoni', ['Sausage']) >>> Pizza.objects.filter(toppings__in=toppings_i_want).exclude(toppings_i_do_not_want) That will result in what I want, but it seems like the performance of such a query would suffer greatly if I'm only interested in two toppings but I have to pass ~100,000 other toppings into the exclude filter. Is there a better way? -
How to use django orm in a project without django
I have the following files in my project folder: database.db model.py: import os import sqlite3 from django.db import models class provincias(models.Model): key = models.AutoField(verbose_name="id",primary_key=True,unique=True) provincia = models.CharField(max_length=100) settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } but when executing django-admin migrate I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. how can i do to use only the django orm connected to my sqlite3 database database bd -
Is the Django-cms addon, Aldryn news/blog; extensible?
I am using Django-cms to create a blog. In order to create the blog posts themselves, I am trying Aldryn news/blog. My question is, is there a way to add additional fields to the template for this particular addon? << Default news/blog template layout image >> What I am trying to do is to split each post into elements, which will be common across most/all posts for a given category. Then I could call each posts "elements" as such: {% if placeholder "contentElement_1" %} <some styling> {% placeholder "contentElement_1" %} </some styling> {% endif %} <some Style></> {% if placeholder "contentElement_2" %} <some styling> {% placeholder "contentElement_2" %} </some styling> {% endif %} <some Style></> etc... With this I have flexibility with regard to ad placement, accordions, cards and other styling within the html template, in and around the post elements. As I see it, with "Aldryn news/blog" I get one (% placeholder "content" %}, a title, and that's it. What Ive tried, future considerations: I'm assuming what I am looking for would create additional database fields for each "content element" as well. Which I would like for a later date to possibly be able to call for particular elements … -
Django Channels 2 - do I need to start a worker?
I've read where I only need to start a worker if somewhere in my code I use channel_layer.send(.... Is this correct? I thought the worker was the one handling all websocket requests. Please enlighten me. Thanks. -
django Filtering data from multiple tables having no foreign Key
model.py class Tas(models.Model): tas_id = models.AutoField(primary_key=True) date = models.DateTimeField(blank=True,null=True) ware_id = models.IntegerField(blank=True, null=True) taserid = models.CharField(max_length=100, blank=True, null=True) class Channels(models.Model): taserid = models.CharField(max_length=255, blank=True, null=True) type = models.CharField(max_length=255, blank=True, null=True) displayname = models.CharField(max_length=100, blank=True, null=True) class Ware(models.Model): ware_id = models.AutoField(primary_key=True) ware_name = models.CharField(null = False,max_length=255) taserid = models.CharField(null = True, max_length=255) views.py def index(request): assert isinstance(request,HttpRequest) display = Tas.objects.all(), cursor = connection.cursor() cursor.execute("select es.date,ew.ware_name,ec.type,ec.displayName from tas as es inner join ware as ew on ew.ware_id = es.ware_id inner join channels as ec on ec.taserId = es.taserId") I am facing problem in applying filters because there is no foreign key between Task,Channels,Ware. however there is a common field among these table.Please suggest how can i apply filter on the basis of Channels Table ---column type ,displayname and Tas Table--- column date -
Queryset question about base user model Django
Using the Django base User model. I'm getting a duplicate error using the base model pk. Not sure why my app can't seem to figure out which user is posting a comment. def view_api(request): user = request.user if request.method == 'POST': if request.user.is_active: price, created = Model.objects.get_or_create( user=User.objects.filter(pk=user.pk), anonymous_user=False, comments=request.POST.get('comments') ) Error: The QuerySet value for an exact lookup must be limited to one result using slicing. -
Using a function to create upload link of audio blob to send it to django server but not getting anything at sever end
I am using this function createDownloadLink which takes blob and create a download link to download the audio and also creates an upload link to upload the blob to the Django backend using xmlHttpRequest when I wrote a function in view to just see the blob data it is showing no POST data function createDownloadLink(blob) { var url = URL.createObjectURL(blob); var au = document.createElement('audio'); var li = document.createElement('li'); var link = document.createElement('a'); //name of .wav file to use during upload and download (without extendion) var filename = new Date().toISOString(); //add controls to the <audio> element au.controls = true; au.src = url; //save to disk link link.href = url; link.download = filename+".wav"; //download forces the browser to donwload the file using the filename link.innerHTML = "Save to disk"; //add the new audio element to li li.appendChild(au); //add the filename to the li li.appendChild(document.createTextNode(filename+".wav ")) //add the save to disk link to li li.appendChild(link); //upload link var upload = document.createElement('a'); upload.href="/show"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ let blob = new Blob(chunks, {type: media.type }); var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); fd.append("audio_data",blob, filename); //fd.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); xhr.open("POST","/show/",true); xhr.setRequestHeader('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); xhr.send(fd); }) … -
Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/
when i running the server i m getting error as Page NOT Found these are the snippets of my code can anyone help me with this project urls.py from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("<int:pk>/", views.project_detail, name="project_detail"), ] urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include("projects.urls")), ] views.py from django.shortcuts import render from projects.models import Project def project_index(request): projects = Project.objects.all() context = {"projects": projects} return render(request, "project_index.html", context) def project_detail(request, pk): project = Project.objects.get(pk=pk) context = {"project": project} return render(request, "project_detail.html", context) models.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") -
register function does not show up after admin.site in my pycharm django development
I am supposed to use admin.site.register to register a model to my website, but register function does not show up after admin.site. There is a register function showing up after admin though. Should I use admin.regsiter instead of admin.site.register? from django.contrib import admin from .models import Question admin.site. (register does not show up)