Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i change the default primary key in django?
I'm new to learning django. I'm using PostgreSQL as my database. I created an app called gplus and a model I created looks something like this class Account(AbstractBaseUser): email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_of_birth = models.DateTimeField() I applied the migrations and then wanted to change the primary key field from default 'id' to 'username'. So, in the psql command line I ran the following commands ALTER TABLE gplus_account DROP CONSTRAINT gplus_account_pkey; ALTER TABLE gplus_account ADD PRIMARY KEY (username); ALTER TABLE gplus_account DROP COLUMN id; Then in the models.py, I edited the username field as username = models.CharField(max_length=50, primary_key=true) Now, when I try to apply the migrations, I get the error django.db.utils.ProgrammingError: column "id" of relation "gplus_account" does not exist It seems Django needs to know there is no 'id' field in the table anymore. How can I do that? Thanks -
Connecting to AWS Postgres Instance For Django Backend
I've created a PostgreSQL database on AWS, which I want to use for a Django project. I've modified settings.py so that it has DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': <db name>, 'USER': <user>, 'PASSWORD': <password>, 'HOST': 'projectdevelopment.foobar.us-east-1.rds.amazonaws.com', 'PORT': '5432', } } Which I would have thought seemed pretty straightforward. Except that when I try to make a migration I get this error: django.db.utils.OperationalError: could not translate host name "projectdevelopment.foobar.us-east-1.rds.amazonaws.com" to address: nodename nor servname provided, or not known The value projectdevelopment.foobar.us-east-1.rds.amazonaws.com has been copied directly from the value under endpoint in the RDS console. Am I missing a setting, or misconfigured? Or both? -
How can I save a UserProfile image (avatar)'s path in the database?
I am having trouble figuring out how I can store a user's uploaded image (their avatar) when they update their profile. The default image I have in the model works, but the update does not give a validationerror, but essentially nothing happens when i submit - the default image remains the same. Here is my code, any understanding of what I'm doing wrong is greatly appreciated. user_profile/views.py def update_user_profile(request, username): args = {} if request.method == 'POST': form = UpdateUserProfile(request.POST, request.FILES, instance=request.user) if request.user.username == username: if form.is_valid(): form.save() return HttpResponseRedirect(reverse('user-profile', kwargs={'username': form.instance.username})) else: raise Http404() elif request.method == 'GET': if not request.user.username == username: raise Http404() else: form = UpdateUserProfile(instance=request.user) else: form = UpdateUserProfile(instance=request.user) args['form'] = form return render(request, 'storytime/update_user_profile.html', args) user_profile/forms.py class UpdateUserProfile(forms.ModelForm): class Meta: model = UserProfile fields = ('first_name', 'last_name', 'email', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: width, height = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if width > max_width or height > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): … -
wrap all django apps in a apps folder
I am trying to wrap all the local apps into apps folder. The project structure I am wanting is apps app1 app2 static templates db.sqlite3 manage.py For this I tried using django-oscar way Here is my settings configuration import os import project_name PROJECT_DIR = os.path.join(os.path.dirname(__file__)) location = lambda x: os.path.join(PROJECT_DIR, x) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ]+project_name.get_core_apps() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': location('db.sqlite3'), } } project/init.py import os def get_short_version(): return '%s.%s' % (VERSION[0], VERSION[1]) def get_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) # Append 3rd digit if > 0 if VERSION[2]: version = '%s.%s' % (version, VERSION[2]) elif VERSION[3] != 'final': version = '%s %s' % (version, VERSION[3]) if len(VERSION) == 5: version = '%s %s' % (version, VERSION[4]) return version PROJECT_MAIN_TEMPLATE_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'templates') PROJECT_CORE_APPS = [ 'project_name', 'project_name.apps.checkout', 'project_name.apps.address', 'haystack', 'treebeard', 'versatileimagefield', ] def get_core_apps(overrides=None): if not overrides: return PROJECT_CORE_APPS from django.utils import six if isinstance(overrides, six.string_types): raise ValueError( "get_core_apps expects a list or tuple of apps " "to override") def get_app_label(app_label, overrides): pattern = app_label.replace('project_name.apps.', '') return app_label apps = [] for app_label in PROJECT_CORE_APPS: apps.append(get_app_label(app_label, overrides)) return apps I get ModuleNotFoundError: No module named 'project_name.apps' error … -
Create parent record with child many by django form
In my django project I have code as below: forms.py class addOrderForm(ModelForm): class Meta: model = Orders fields = [ 'shipvia', 'customer', 'employee', 'orderdate', 'freight', 'shipname', 'shipaddress', 'shipcity', 'shipregion', 'shippostalcode', 'shipcountry' ] views.py def addOrder(request): OrderDetailsFormSet = inlineformset_factory(Orders, OrderDetails, fields=('product', 'unitprice', 'quantity' , 'discount'), extra=3) order=Orders() if request.method == 'POST': f = addOrderForm(request.POST, instance=order) fs = OrderDetailsFormSet(request.POST,instance=order) if fs.is_valid() and f.is_valid(): f.save() fs.save() return HttpResponse('success') else: f = addOrderForm(instance=order) fs = OrderDetailsFormSet(instance=order) return render(request, 'orders/addOrder.html', context = {'fs': fs,'f':f,'order':order}) orders/addOrder.html {% block body %} <form action="/orders/addOrder/" method="post"> {% csrf_token %} <div class="row"> {{ fs.management_form }} <table> {% for form in fs.forms %} {% for field in form %} <tr><th>{{field.label_tag}}</th><td>{{field}}{{field.errors}}</td></tr> {% endfor %} {% endfor %} </table> </div> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker({ inline: true, sideBySide: true, format: 'YYYY-MM-DD', }); }); </script> {% endblock %} There are two tables in the database ORDERS table: orderid | smallint | not null default nextval('orders_orderid_seq'::regclass) customerid | bpchar | employeeid | smallint | orderdate | date | requireddate | date | shippeddate | date | shipvia | smallint | freight | real | shipname | character varying(40) | shipaddress | character varying(60) | shipcity | character varying(15) | … -
Edit view on Django not displaying object into page
I got a form page to edit my objects from database, but when I access them with the edit button it goes to the url http://localhost:8000/acoes/edit/1, but I cannot see the object details in the form field. It is just empty as if I was going to create a new object (and it creates if I try) Any suggestion? Every post and question that I found online states that the code would work being just like this, but it isnt. on the template acoes_form.html <form method="post"> <div class="form-group"> {% csrf_token %} {{form.as_p}} </div> <input type="submit" value="Gravar dados" class="btn btn-success" /> </form> on views.py @login_required(login_url="/login") def acoes_edit(request, pk, template_name='acoes/acoes_form.html'): if request.user.is_superuser: acoes= get_object_or_404(Acoes, pk=pk) else: acoes= get_object_or_404(Acoes, pk=pk, user=request.user) form = AcoesForm(request.POST or None, instance=acoes) if form.is_valid(): form.save() return redirect('acoes_list') return render(request, template_name, {'form':AcoesForm}) on forms.py class AcoesForm(ModelForm): #bunch of fields definitions #... # class Meta: model = Acoes fields = ['id_pedido','bl_msg','tb_msg','bl_shell','tb_shell','obs','ativo'] -
How to hide my website to the public so only I can see it?
Creating a Django website with Digital Ocean (Nginx, Guncorn) - and would like to know how to show a blank page until I've finished development. So when someone other than myself visits my website, I want them to see a page saying "Site under construction" or something. Advice appreciated. -
How to resolve FOREIGN KEY constraint failed
I am following a tutorial on a basic concept. How to customize a user in django. I want to use the built in auth user. I found this tutorial which seems to work until a point. I get through the whole tutorial with everything working. however when I run my project, log in and open the user in the admin area I click "Save and continue editing" This gives me the error The code I have in my project is EXACTLY the same as in the tutorial. I have tried removing my cache and migrations and starting again, even creating a new environment and reinstalling django. Nothing seems to work. Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/user/1/change/ Django Version: 2.0.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] 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: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit 239. return self.connection.commit() The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File … -
Django: Change formset error message(s)
Hello fellow programmers, I would like to change the min_num error message of a formset. My code creates a formset using an inlineformset_factory: formset_clazz = inlineformset_factory(MyParentModel, MyModel, MyModelForm, can_delete=True, min_num=1, validate_min=True) formset = formset_clazz(data=request.POST) print(formset._non_form_errors) if formset.is_valid(): print("yay!") else: print("nay!") return render(request, "mytemplate.html", {'formset':formset}) In the template I render the non_form_errors: {% if formset.non_form_errors %} <ul> {% for error in form.non_form_errors %} <li> {{ error }} </li> {% endfor %} </ul> {% endif %} The min_num validation works as intended and shows the error message Please submit 1 or more forms., when a user removes all forms and submits the formset. My question is: How do I change the error message? From [0] I learned, that it is stored in formset._non_form_errors, but without a way to override the too_few_forms [1] (ctrl-F validate_min) code's message. The BaseFormSet class itself uses ngettext to translate the message, but I do not really want to setup internationalization just for this (or is that easy and straight-forward?). Is there a more convenient way to achieve my goal? [0] Django: Displaying formset errors correctly [1] https://docs.djangoproject.com/en/2.0/_modules/django/forms/formsets/#BaseFormSet -
Creating Calendar table entries, but process currently is very limiting
I'm trying to take info from a few models and generate table entries in the model Calendar. I'd like to perfect this method so that It can be done on any day and will just extend from an entry in the Calendar object that has the future most date. Currently in the view as you can see, it just projects the current objects in the Calendar table, and projects it forward a certain number of days. Which limits me to doing this only on mondays, otherwise it falls out of sync with the TimeSlots table. Also depending on the max_jobs the TimeSlot table entry has I need to create multiple calendar entries... currently it only works with two but I guess I can increase it but the code is very repetative Template: <form action="{% url 'portal:custom_admin' %}" method="post"> {% csrf_token %} <div style="background-color:red; width:15%;"> <button name="submit">Project</button> DANGER! Only click on mondays, until future projecter can go based off futuremost monday generated into Calendar </div> </form> View with which I am struggling: @login_required def custom_admin(request): """ Displays MaxSettings, also Takes time_slots and create a week of it into the future (only should be done on mondays) Note:eventually this should be able … -
django duplicates in pagination with order_by() on manytomany field
I am sorting a query on a timefield from a manytomany object but have trouble during pagination. models.py: class Validated(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) views.py: results_list = Validated.objects.filter(job_id_list__user=request.user).\ distinct().order_by('-job_id_list__job_time') My problem is that pagination is messed up and I get duplicates in my pagination output, even when the query output is ok. (other have this problem too) I tried several solutions but my issue does not get solved as sorting is bases on a field from a many-to-many object order_by('job_id_list__job_time') I was thinking of a work-around through creating an annotation to my model by the use of a Model.Manager. Inside this annotation, i try to add the job_time which is a result of a function inside the model. In that way, the job_time would be easily accessible: for i in result_list: job_time_from_model = result_list[i].job_time I would do this as followed but I don't know how to incorporate the %%function logic%% inside the annotation. Is this even possible in this way or is another approach required? models.py: class ValidatedManager(models.Manager): **%%function-logic%%** def date(self, user, id): xlinkdatabase_validated_object = self.get(id=id) job_id_list = xlinkdatabase_validated_object.\ job_id_list.all().order_by('-job_time') date_added = None for item in job_id_list: … -
How to handle for/if loops from Jinja2 in Django Tempates
Working on a legacy project where we're using django templates. How can I translate this for/if syntax from Jinja2 to django: This Jinja example works as intended but syntax error out in django: {% for story in stories if story.status == "published" %} <h1> {{story.title}} </h1> {% empty %} <p>Nothing to see here</p> {% endfor %} This will not work with {% empty %} because the if statement is inside the scope of the for loop. {% for story in stories %} {% if story.status == "published" %} <h1> {{story.title}} </h1> {% endif %} {% empty %} <p> Nothing to see here</p> {% endfor %} -
Why django ugettext_lazy inside a set doesn't always work?
TL;DR I'm having a hard time to dynamically remove the whole Important dates section from django.contrib.auth.admin.UserAdmin when I take translation into account =( security/admin.py ... from django.utils.translation import ugettext_lazy as _ ... class CustomUserAdmin(UserAdmin): exclude_section_set = {_('Important dates')} ... def _filter_sections(self): result = deepcopy(fieldsets) return tuple( section for section in result if section[title_index] not in self.exclude_section_set ) return result django.po ... #: security/admin.py:17 msgid "Important dates" msgstr "Datas importantes" ... Translation is working as far as I can tell. This piece of code removes correctly the section when my browser uses the en language, but it doesn't when my browser is using the pt_BR language. I have (hopefully) isolated the problem. It seems to be the in operation of the set type using ugettext_lazy instances, but I don't understand the behavior. Results of my python console using pt_BR language: >>> _('Important dates') in {_('Important dates')} True >>> print({_('Important dates')}) {'Datas importantes'} >>> _('Important dates') in self.exclude_section_set False >>> print(self.exclude_section_set) {'Datas importantes'} Results of my python console using en language: >>> _('Important dates') in {_('Important dates')} True >>> print({_('Important dates')}) {'Important dates'} >>> _('Important dates') in self.exclude_section_set True >>> print(self.exclude_section_set) {'Important dates'} What am I missing here? PS: I'm using Django … -
Google API Discovery Build
I'm having some trouble with the google api discovery build. If I put the credentials from the flow.credentials into the discovery.build I can get the response from drive.files().list().execute(). However, if I put them into a dictionary like so: data = { "token": credentials.token, ...etc... } And then create the credential with: credentials = google.oauth2.credentials.Credentials(data) Then call the: drive = googleapiclient.discovery.build('drive', 'v1', credentials=credentials) list = drive.files().list().execute() I get an error like below: {'client_secret': 'example', 'token': 'example'...} could not be converted to unicode. Any Ideas? Im guessing one of the values is not a unicode? This is the basic example, I'm actually getting the results from the database but the error happens even if I dont save them to the db and just put them into the {}. Thank you, -
How to upload multiple files using FileField in Django?
So I have a model with this FileField. I was wondering if there is a way to let the user from admin panel, add as many files as he wants. file = models.FileField(blank=True, upload_to='documents') def file_link(self): if self.file: return "<a href='%s'>download</a>" % (self.file.url,) else: return "No attachment" file_link.allow_tags = True -
FORMVIEW and GET
I am trying to clean a FORMVIEW with very little success. I have the following form: FORMS... class BookRequestNumberSearch(forms.Form): q = forms.IntegerField(required=True) def __init__(self, *args, **kwargs): user = kwargs.pop('user') q = kwargs.pop('q', None) super(BookRequestNumberSearch, self).__init__(*args, **kwargs) self.fields['q'].widget.attrs['class'] = 'name2' def clean(self): cleaned_data = super(BookRequestNumberSearch, self).clean() request_number = cleaned_data.get('q')# if request_number: if Book.objects.filter(request_number__iexact=request_number).exists(): try: Book.objects.get(request_number__iexact=request_number) self.add_error('request_number',' Error.') except Book.DoesNotExist: pass return cleaned_data And the View.... class BookRequestNumberSearchView(LoginRequiredMixin,FormView): form_class = BookRequestNumberSearch template_name = 'Book/book_request_number_search.html' def get_form_kwargs(self): kwargs = super(BookRequestNumberSearchView, self).get_form_kwargs() kwargs['user'] = self.request.user kwargs['q'] = self.request.GET.get("q") return kwargs def get_initial(self): init = super(BookRequestNumberSearchView, self).get_initial() init.update({'q':self.request.GET.get("q")}) return init And the HTML <form method="GET" autocomplete=off action="{% url 'Book:procedure_request_number_search_detail' %}" > <div> <h1 class="title">Book Request Number Search</h1> </div> <div class="section"> {{ form.q }} </div> This code works, but I can't figure out how to get Django to invoke CLEAN. I suspect maybe because I'm doing a GET the CLEAN doesn't get recognized? I've spent most of the afternoon playing with variations but no matter what I do CLEAN is just ignored. Thanks for any thoughts. -
Connect Angular4 Frontend to API written in Python
I'm mostly looking for advice or direction to try to figure out a problem. I have a Python API and I need to connect it to an Angular 4 Front-end. Any advice or direction would be appreciated. I can always answer any questions on the subject. Thank you in advance. -
Django Website Not Updating
I have created a new html file in the static/partials folder of my project and trying to see it on my Django website. I can edit older html files in that folder and see those changes, but can not see the new html file, which is pretty annoying. In the main urls.py, I redirect the links to pages in the static/partials folder to the base file, which is redirected to a js file to retrieve template information. This is what the js file looks like that redirects links to the partials html pages (the essential parts): x = angular.module('x', []); . . . x.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when( '/', {templateUrl: '/static/partials/index.html'}). when( '/newpage', { templateUrl: '/static/partials/newpage.html', controller: "ControllerName" }); $locationProvider.html5Mode(true); }]); -
Using Foreign Key on Django model to populate select input
im having problems finding out on the documentation how to solve my problem so im posting here: I have 3 Models one for a class room with its attributes, one for students and the last one a relation of the room and the student. So on the template i want it to show a select button with a option value being the student id and the label being the student name on my models.py i have this: student_id = models.ForeignKey('Student', verbose_name=u"Student") on my template.html i just call the field: {{ field }} and the result that i get is: <select name='student_id'> <option value='1'>Student object</option> </select> is there a way that i can preset the value and label like its done using choices for static data? to something like this: STUDENT_CHOICES =( (model.student.id , model.student.name), ) student_id = models.ForeignKey('Student', verbose_name=u"Student",, choices=STUDENT_CHOICES) let me know if im not clear enough on the question since im fairly new to python and django -
PyCharm debugger disconnects from remote host after short idle time
I've been using the PyDev/PyCharm debugger's remote debugging feature for years, and it's worked just fine. I've been using it for a Django-based project which runs in a Docker container for the last year or so, and it worked just fine with that, too. But ever since a few months ago (possibly due to my code shop's switch to Python 3?), I've had no end of frustration with it because the debugger keeps disconnecting for no reason. I'll be in the middle of a debug session that's going just fine, but then if I let the system idle for about a minute, the debug session suddenly dies, and execution of the request goes on without me. When that happens, I'll see the console output change from: Connected to pydev debugger (build 173.3942.36) To: Connected to pydev debugger (build 173.3942.36) Waiting for process connection... And once this happens, the only solution to get the debugger to reconnect to the running Django server inside my container is to restart gunicorn, either through editing a file to make gunicorn reload itself, or through restarting the gunicorn application with kill -HUP. Further requests made against the server will not trigger any breakpoints unless I … -
Ajax client connecting to a Django (cross domain) works only with JSONP
We have a Django application running in tomcat with Basic Authentication. I want to make cross domain request but only with $.ajax({...dataType: 'JSONP',...}) it works. dataType: JSON doesnt work. Does that mean the server doesnt have CORS enabled. Any tips or pointers to enable CORS in Django -
Delete/Replace aditional items/images when an image is replaced, using an inlineformset
I have 2 models Product and Image: class Image(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) # we need this key to the original image because otherwise we can get/update individual cropped images parent = models.ForeignKey('self', blank=True, null=True, verbose_name='original image', on_delete=models.CASCADE) image = models.ImageField(upload_to=file_upload_to) image_type = models.CharField(max_length=50) The ImageForm is uploaded as Inlineformset in the Product ModelForm. Steps: I upload an image (original) - parent key in the model I crop starting from the original image, 2 other images(base on type) I replace the original Image with another Image (in form) In the database Django (inlineformset)deletes the old original Image record and a add a new record for the replaced Image crop and add in database: if crop_image(disk_path, new_disk_path, size): Image.objects.update_or_create(image_type=type_key, parent_id=parent_id, product_id=product_id, defaults={'image': new_db_path}) My problem is that, when Django change original image by deleting and adding (not updating) I remain in the database with two cropped imaged, linked to the original record that is not there anymore. If Django used an update, my function will work, but it is not. Also 'on_delete=models.CASCADE' doesn't work, because oterwise it should have deleted tem cropped image. So I need somehow do delete this images. -
Syntax for connecting models to admin, Django
I have been learning python for some months, and started tinkering with Django. Before posting this, I read up on the auto-generated 'admin.py'-code on github, as well as googled the matter. It appears my question is a little specific, and I was quite frankly very confused from that specific reading. Thus, I hope asking this adds value to this wonderful community. Question: When connecting a model to the admin page, in admin.py, you first import admin: from django.contrib import admin After this, you import your model. Then, you supposedly connect your model through: admin.site.register(MODEL) What I do not understand is what 'site.register' is. The fact that the line starts off with 'admin.' makes perfect sense, as you are specifying from where the following import (ex. 'admin.function' or 'admin.class') comes from. Had it only been 'admin.somefunctionfromadmin' I would have totally understood this. Now, instead, I am confused as to what 'sites.register' is. Is 'sites' a module, a file, and 'register' a function from within that module? If so, what does that make 'admin'? A package? I have seen lines similar to these throughout Django, and feel a bit confused. Thank you! -
How do I represent two models on the same webpage?
So I have my 3 models from the code below. I represented my courses as a list already and then generated the page below for each course. Now on the same page I want to represent, for that specific course, all course_category fields with their specific lecture_title and content, etc. I tried something.. but I can't figure it out. def courses(request, slug): con = get_object_or_404(Course, slug=slug) return render(request, 'courses/courses.html', {'course': con}) class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='') course_category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE) lecture_title = models.CharField(max_length=100) content = models.TextField() link = models.URLField(blank=True) file = models.FileField(blank=True, upload_to='documents') def __str__(self): return self.lecture_title class CourseCategory(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE) course_category = models.CharField(max_length=50, unique=True) def __str__(self): return self.course_category class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE) name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Course.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() {% block body %} <ul> <li>{{ course.study_programme }}</li> <li>{{ course.name }}</li> <li>{{ course.ects }}</li> <li>{{ course.description }}</li> <li>{{ course.year }}</li> … -
Is there an alternative way to request JSON REST API in django?
I currently have a fully working Serializers using the Django REST Framework. I want to be able to parse data or request data that can be used in my django app. I have been using import requests r = requests.get('django_api_url') data = json.loads(r.text) I have no problem using this, but I'm trying to see if there's a better/faster way.