Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Opinion on inheriting a previous model
I am looking at my code and see that that two models have mulitple similar fields. I was wondering if my ParentProfile model could inherit my User model in order to shorten the code and remove overlap. This is quite a beginner question and would like someone elses opinion on this matter. Thank you! models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser objects = UserManager() # takes email as username | removes email USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def has_perm(self, perm, onj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app 'app_label'?" return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class ParentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) … -
How to make a simple pastebin with django
Where I can find any documentation/examples to make a simple pastebin on django? What are the first steps to start with? I just need to be able to type into a textarea and save that paste with the short link I've barley made and share it to others. -
Wagtail Custom API
I am trying to use Wagtail API to feed my D3 plugin. I want to sent a JSON output of my nested ClusterableModels. I have created 2 sets of Snippets in my models.py. One is graph containing the nodes and the other for the nested nodes: @register_snippet class Graph(ClusterableModel): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), InlinePanel('graph_nodes', label='Select Nodes'), ] def __str__(self): return '{}'.format(self.name) class Meta: verbose_name = 'Graph' verbose_name_plural = 'Graphs' @register_snippet class Node(ClusterableModel, Orderable): name = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) panels = [ FieldPanel('name'), FieldPanel('body'), InlinePanel('node_to_node' , label='connect to ...'), ] def __str__(self): return '{} ({} links)'.format(self.name, self.node_to_node.count()) class NodeRelations(Orderable, ClusterableModel): parent = ParentalKey(Node, related_name='node_to_node', null=True, blank=True) node = models.ForeignKey(Node, related_name="+", on_delete=models.CASCADE, blank=True, null=True) panels = [ SnippetChooserPanel('node'), ] class GraphNodeRelations(Orderable): parent = ParentalKey(Graph, related_name='graph_nodes', null=True, blank=True) node = models.ForeignKey(Node, related_name='+', on_delete=models.SET_NULL, blank=True, null=True) panels = [ SnippetChooserPanel('node'), ] The problem is that Wagtail does not have a standard API for ClusterableModel or Snippets. However, it offer custom endpoints using 'BaseAPIEndpoint'. I was successful finding the built-in 'PagesAPIEndpoint' code that give insight about the process yet I struggle to come up with a working code that simply fetchs the requested graph(my graph) and its nested children(Nodes) -
Variable Queryset filter by using a string as input
im working on creating a variable queryset by using a string and im not reaching the solution. This is my method output = "entradaid__in=[" for x in carrito_entradas: output+=x+"," temp=len(output) output = output[:temp - 1] output += "]" peliculas = Pelicula.objects.filter(output) What I want is create a queryset of "Peliculas" that can filter more than one value. My intention is this: output=entradaid__in=[1,2,5]. Pelicula.objects.filter(entradaid__in=[1,2,5]) Is there a way where I can do this? -
Wrapping content with the same tags multiple times in Django templates
Given a base.html file containing the following: <div class="foo some-content"> ... </div> <div class="bar some-content"> ... </div> I would like to wrap each of the .some-content divs to achieve a nested structure when using base.html in certain places: <div class="row"> <div class="foo some-content"> ... </div> </div> <div class="row"> <div class="bar some-content"> ... </div> </div> I tried extending base.html to wrap the divs with a .row div: {% extends base.html %} {% block wrapper %} <div class "row"> {{ block.super }} </div> {% endblock %} But that didn't work as I got a TemplateSyntaxError for using block wrapper twice in base.html: # Throws TemplateSyntaxError {% block wrapper %} <div class="foo some-content"> ... </div> {% endblock %} {% block wrapper %} <div class="bar some-content"> ... </div> {% endblock %} I realize that I could break up the .some-content divs in to their own files, and reuse those in other places, but I would prefer another route. I also looked at Django template macros as suggested in this SO post, but I think middleware will be overkill in this situation. Is there any way I can extend or reuse my current base.html file so that the .some-content divs are sometimes wrapped in a … -
Build an auto complete feature in django framwork
I am trying to build an autocomplete feature in Django framework. I was going through trie. I found a lot of docs about the same but no one explained about hosting the trie on the server. My question is how do build a trie and host on a server. I am using Django framework for my backend. any help would be appreciated. -
How to return HTTP response with file content and also re-render page
I have simple page that displays a form. When the 'submit' for the form is clicked, a file is downloaded in the browser. Here's what my view looks like (I stripped out much of the actual code to help highlight what I'm trying to ask): from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from django import forms # My custom form from .forms import CalendarForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request form = CalendarForm(request.POST) # check whether it's valid if form.is_valid(): # Fetch the form data here # Build HTTP request containing contents of static file to download with open('test.pdf', 'rb') as fh: resp = HttpResponse(fh.read(), content_type="application/pdf") resp['Content-Disposition'] = ('attachment;filename=test.pdf') # Return HTML response containing file contents: I also # want to re-render the calendar.html page here but don't know how return resp else: # Do error stuff # if a GET (or any other method) we'll create a blank form else: form = CalendarForm() # Re-render the page return render(request, 'calendar.html', {'form': form}) In the case where … -
how to Upload zip File on Heroku, Django
Hello i try to upload zip file on heroku but after code execute i got error from my worker logs. FileNotFoundError: [Errno 2] No such file or directory: 'fama/static/resources/rafaln/badanie2009_2017' I check my project root on heroku by git ls-files | grep static and there is no file such as badanie2009_2017 this is the code from my upload method def upload_zip(request): if request.method == 'POST' and request.FILES['myfile']: my_file = request.FILES['myfile'] fs = FileSystemStorage() settings.MEDIA_ROOT = 'fama/static/resources/' + request.user.username filename = fs.save(my_file.name, my_file) uploaded_file_url = fs.url(filename) str = my_file.name var = str.replace(".zip", "") z = zipfile.ZipFile(my_file) zip = zipfile.ZipFile(my_file) zip.extractall('fama/static/resources/' + request.user.username + '/') dataset_array = os.listdir('fama/static/resources/' + request.user.username + '/' + var) os.remove('fama/static/resources/' + request.user.username + '/' + var + '.zip') return filename And this is a task method @task(name="zip_awesome") def zip_to_db(user, filename, resarch_name): file_name_unzip = filename.replace(".zip", "") data_set_array = os.listdir('fama/static/resources/' + user + '/' + file_name_unzip) user = User.objects.get(username=user) research = ResearchModel.objects.get(research_name=resarch_name, author=user) for x in data_set_array: df = pd.read_csv('fama/static/resources/' + user.username + '/' + file_name_unzip + '/' + x, sep=';', encoding='utf-8', engine='python') for index, row in df.iterrows(): if('Data' in row.keys()): file_name_unzip_x = x.replace(".csv", "") data = {'author': user, 'file_name': file_name_unzip_x, 'date': row['Data'], 'price': row['Zamkniecie'], 'research_name': research} p = StudyDataModel.objects.create(**data) … -
AttributeError: module 'myapp' has no attribute 'startswith' in Django
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x046E1780> Traceback (most recent call last): File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\BS146\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 117, in import_module if name.startswith('.'): AttributeError: module 'myapp' has no attribute 'startswith' -
Dynamic url in django doesn't read Bootstrap
I really do not know where I made a mistake. I run "python manage.py collectstatic" correctly and there is no error on the running server, but for some reason my navbar looks totally messed up like there is no connection with Bootstrap. Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "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', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static-storage"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static-serve") base.html {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>{% block title %}Tweetme.co{% endblock title %}</title> <!-- Bootstrap --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> <body> {% include "navbar.html" %} <div class='container'> {% block content %} {% endblock content %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> --> </body> </html> navbar.html <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped … -
Django (DRF) Boolean Field missing in JSON
I'm writing a rather simple REST API using Django REST Framework. I am trying to add a boolean field to my model that would show if it is publicly accessible or not. In my models.py, my model looks like this: class BlogPost(models.Model): title = models.CharField(max_length=20, default='', blank=False) description = models.CharField(max_length=140, default='', blank=False) is_public = models.BooleanField(default=True, blank=False) Then in my serializers.py, my serializer for the model looks like this: class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ('title', 'description', 'is_public') However, when I create an instance of that model, and run my development server, the JSON only returns the title and the description. The is_public field is missing from the JSON. I've searched everywhere and can't find the reason for this odd problem. Any help would be much appreciated! -
Django multiple ModelForms in template
It would be highly appreciated if you could advise how template should be modified to scale modelforms as per code below. There are around 30 item models which are the same as parent model. Also, those modelform have to be saved to database separately so I assume there should be same amount of modelforms as there are models. Thank you very much in advance and looking forward to your insights. forms.py from django import forms from django.forms import modelformset_factory, ModelForm from .models import Assumptions class AssumptionsForm(ModelForm): class Meta: model = Assumptions fields = ['Bad', 'Likely', 'Best'] exclude = () models.py from django.db import models from django.forms import ModelForm class Assumptions(models.Model): Bad = models.FloatField(null=True, blank=True, default=None) Likely = models.FloatField(null=True, blank=True, default=None) Best = models.FloatField(null=True, blank=True, default=None) class Meta: abstract = True class Item1(Assumptions): pass class Item2(Assumptions): pass class ItemN(Assumptions): pass views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Item1, Item2, Assumptions model_names = [item1, item2 ... itemN] def get_assumptions(request): for name in model_names: AssumptionsFormSet = modelformset_factory(name, form = AssumptionsForm, extra = 5) if request.method == 'POST': formset = AssumptionsFormSet(request.POST, prefix = str(name)) if formset.is_valid(): print('valid form') for form in formset: print('in for loop after valid form1') … -
How to render page template from db?
I have mezzanine project, and I want to put templates into database as blocks and then I want to build custom page by adding those blocks (in different sets). In pure Django it's simple, something like this: s = TemplatesModel.objects.get(name='news_block').content t = Template(s) t.render(Context(dict(var_a='something', var_b=1))) But I would like to use the mezzanine functionality - with this feature. How to do it? -
Pass form fields to function parameters Django
I want pass form to function parameters, when user submits "foo" i want to use that as "test1" parameter in def funcion(test1): print(test1) (This is just simplified version) All i could find is posting data to database of forum or something My html <input type="text" name="field1" /></br> <input type="text" name="field2" /></br> -
How do I send an XML request by substituing values in the XML over SOAP?
I have an XML file in my template directory and this XML file has a few placeholders. I need to fill these placeholders with values from the database and calculations of other values (based on user input) and then send it over to a URL that will process this XML and return an XML response as well. This is how my XML file looks: my_file.xml <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://some_url.api.com" xmlns:web1="http://another_url.api.com"> <soapenv:Header> <web:AuthenticationToken> <web:licenseKey> string </web:licenseKey> <web:password> string </web:password> <web:username> string </web:username> </web:AuthenticationToken> </soapenv:Header> <soapenv:Body> <web:Shipping> <web:ShipRequest> <web1:dtnCtry> string </web1:dtnCtry> <web1:dtnZC> string </web1:dtnZC> <web1:details> <!--Zero or more repetitions:--> <web1:ShipRequestDetail> <web1:class> string </web1:class> <web1:wt> string </web1:wt> </web1:ShipRequestDetail> </web1:details> <web1:orgCtry> string </web1:orgCtry> <web1:orgZC> string </web1:orgZC> <web1:shipDateCCYYMMDD> string </web1:shipDateCCYYMMDD> <web1:shipID> string </web1:shipID> <web1:tarName> string </web1:tarName> </web:ShipRequest> </web:Shipping> </soapenv:Body> Each of those string values will have to be substituted with an actual database value. How do I go about this process? I have checked multiple forums, sites and multiple questions inside of SO and each one recommends a different approach. As a newbie, it is difficult for me to select one and it is extremely overwhelming. Could someone here please explain a process from scratch? Thanks! -
I cant makemigrations in django 1.11.9
Python3.6.5 migrations problem python3 manage.py makemigrations I cant makemigrations and migrate in python3 version and Django==1.11.9 -v i already delete 0001_initial.py files but it doesnt work for me help me!! DEBUG 2018-06-17 16:38:58,008 utils 5154 140704182478656 (0.000) SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name; args=None DEBUG 2018-06-17 16:38:58,010 utils 5154 140704182478656 (0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=() Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/tugu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/tugu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tugu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/tugu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/tugu/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 244, in build_graph self.graph.validate_consistency() File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/tugu/.local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0010_auto_20180524_1306 dependencies reference nonexistent parent node ('auth', '0009_alter_user_last_name_max_length') -
Installing GCC (gfortran) on Heroku-16 stack
I am developing a python app on Heroku server (Heroku-16 stack) using Django framework. I would like to use gfortran on the server. However, this stack version of Heroku does not include a C compiler as stated in https://devcenter.heroku.com/articles/stack-packages Can I install a buildpack to overcome this problem or do I have to downgrade to cedar-14 version which includes GCC? -
SystemCheckError (slug in django)
I got this error (what is wrong here? I can't find the root cause of this. I tried to search for this answer but it didn't applied to this case.): django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'rango.admin.CategoryAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slugs', which is not an attribute of 'rango.Category'. My admin.py from django.contrib import admin from .models import Category, Page class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slugs':('name',)} class PageAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'url') admin.site.register(Category, CategoryAdmin) admin.site.register(Page, PageAdmin) My models.py from django.db import models from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __str__(self): return self.title -
Django: create a model that has a set of values for each day of month
Suppose I want to create a form that allows a user to enter 2 numeric values for each day of the month. (e.g. count and rate). Since each month has a different number of days, how do I best create this. Should I create a model that has all of the days prepopulated? class myModel(models.Model): user = ... day1 = models.DateField(default=None, blank=True, null=True) day1_count = models.IntegerField(default=9, min=0, max=100) day1_rate = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) day2 = models.DateField(default=None, blank=True, null=True) day2_count = models.IntegerField(default=9, min=0, max=100) day2_rate = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) ... day31 = models.DateField(default=None, blank=True, null=True) day31_count = models.IntegerField(default=9, min=0, max=100) day31_rate = models.DecimalField(default=0.00, max_digits=100, or should I create some kind of onetomany field? class myDate(models.Model) day = models.DateField(default=None, blank=True, null=True) day_count = models.IntegerField(default=9, min=0, max=100) day_rate = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) class myModel(models.Modle) user = ... date = models.OneToMany(myDate) I feel like the later option is better, but I don't know how to flesh it out. -
creating my own login form django
Been looking for 2 days now, I simply need to create my own login form .. I need to create the form in forms.py then connect to a view in views.py and call it from an URL in urls.py and all use my custom user model as backend here are my models.py that contains user model : class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name -
Is Django able to handle large number of requests?
I am developing a online market place and expect largish number of requests coming to the server. I have the option to choose between the following two: Django REST API Node.js I being a python fanboy had started developing in django, when I came across this blog, according to which the number of requests/sec that django is able to handle is abysmally low as compared to node.js stack. I have the following two main doubts: How can we increase the efficiency of django. I am aware about caching, having the media, django and database(maybe sharded) on separate servers. What other things can help to increase the request handling rate? Can incorporating those make it perform not this badly(as seen in the medium link above) as compared to node.js. Scaling of django. How much effort in comparison to node.js(more, less, significant more, significantly less) would it take scale the application, if the need arises in future. Thanks in advance. -
Termux and Django
I installed Termux on my Samsung Galaxy S6 Edge. I installed Python, Django, virtualenv - everything needed to create a website using Django. Then I started the server after creating a project only for me to get Error: Port request not allowed in my browser. How do I get through this? -
how can i make models unique in Django together
i wanted to have 3 models TvSeries, Season and Episode. any Episode should be only for one season if a specific TvSeries, and that specific Season should be only for one TvSeries i'm defining my models like this class Movie(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Season(models.Model): season = models.PositiveIntegerField() title = models.CharField(max_length=255, blank=True) movie = models.ForeignKey(Movie,on_delete=models.CASCADE) class Episode(models.Model): episode = models.PositiveIntegerField() title = models.CharField(max_length=255, blank=True) season = models.ForeignKey(Season,on_delete=models.CASCADE) movie = models.ForeignKey(Movie,on_delete=models.CASCADE) but in this case any season can be for any episode and every espisode i make i can choose a season and a complete difference TvSeries like this: testfilm1 -> season1(id=1) -> episode 1 testfilm2-> season(id=1) -> episode 2 the season that is for testfilm1 can be user in any other movie. i tried this with unique_together but no chance. -
Django Rest Framework POST and GET Nested Serializers
I've been developing my own API for a Kanban-Style Project Board. I have attached a UML diagram to show how the "boards" application is organised. My Application's Model UML Diagram My problem is that when I want to create a new Card I want to be able to create the card with a list of Labels by Primary Keys passed in the POST parameters, like so: { "title": "Test Card", "description": "This is a Test Card!", "created_by": 1, "labels": [1,2] } Another requirement I have is that I would like to retrieve the serialized labels as part of the card object, like so: { "id": 1, "board": 1, "title": "Some Card", "description": "The description of Some Card.", "created_by": 1, "assignees": [ { "id": 1, "username": "test1", "email": "test1_user@hotmail.co.uk" } ], "labels": [ { "id": 1, "board": 1, "title": "Pink Label", "color": "#f442cb" } ], "comment_set": [] } I am going to assume that to achieve this difference in POST and GET functionality I am going to have to have 2 different serializers? However, the main question of this post has to do with the creation logic from the POST data as mentioned above. I keep getting errors like this: { … -
Django add link after slice
i have the following in my html template: <h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1> <p>{{ post.content|slice:":1000"|linebreaksbr }}</p> i want that after the slice to 1000 chars a href to the full article gets displayd. e.g.: <h1><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h1> <p>{{ post.content|slice:":1000"|link:"... read on" href= url 'post_detail'|linebreaksbr }}</p> any idea?