Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect data automatically from server to Client
I am working on a web application using python3.5 for the backend, javascript +react/redux for the frontend and a Django server. The goal of the application is to display in real time data sent by some raspberry PI running under different protocols (MQTT, XMPP and CoaP). I tell my django server to make get request to differents servers which handles different protocols, then save those data into a database that i can finally retrieve into my redux store and then display those on my client. I would like to be able to remove the saving in database part which means that my Django server has to forward data it receives directly to the client side. I've made some researches and it seems that websocket programming is the best way to do it but i have such a different architecture so i'm not sure that i will be able to use this except if i restart from scratch which would be awful. If you have any other ideas to do what i want or if you have some advice to transform my app it would be great. -
Django Foreign Key relationship and trying to filter to it
Devices Model: class Devices(AbstractFCMDevice): user = models.ForeignKey('User', on_delete=models.CASCADE) JobTags Model: class JobTags(models.Model): name = models.CharField(max_length=40, blank=True, null=True) # Name of the tag job_base_rate = models.DecimalField(decimal_places=2, max_digits=10, blank=True, null=True) # Amount we take to escrow before a job begins job_unit_rate = models.DecimalField(decimal_places=2, max_digits=10, blank=True, null=True) # Rate per unit unit = models.CharField(max_length=50, blank=True, null=True) # Name of the unit providers = models.ManyToManyField(User) User Model: class User(AbstractBaseUser): email = models.EmailField(unique=True) password = models.CharField(max_length=200) REQUIRED_FIELDS = ['password'] USERNAME_FIELD = 'email' objects = UserManager() The line of code that's actually causing the error: device = Devices.objects.filter(user__jobtags__name__contains=name) Actual error I'm getting... AttributeError: 'Devices' object has no attribute 'providers' I feel like... of course Devices doesn't have a field called providers... but what am I doing wrong with my filter? For some reason the code doesn't stop it actually runs through and does what I need it to, but it still gives me a 500 error... it's really weird. is my filter query incorrect? Obviously, but is there a better way? -
DjangoRestFramework-User Logout Implementation
I am using ObtainAuthToken for assigning tokens to users and here is the views.py code for logging in: class LoginAPIViewSet(viewsets.ViewSet): ''''Checks email and password and return an authToken''' serializer_class = AuthTokenSerializer def create(self,request): ''''Use the obtainAuthToken APIVIewto validate and create a Token .''' return ObtainAuthToken().post(request) My Question is how do i implement Logout for an user I've been reading docs and other blogs but everyone is using jwt or something else and i couldn't get any answer for this -
Javascript LaTeX "preview" field not displaying properly
I'm currently working on a math related website, as such, LateX format is required. I have a form with textarea in which the text is going to be written and I also have a "preview" div just like the one here in stackoverflow, so you can see how the actual text is going to look like. To make this I used this code which I found in another quiestion. It works but it won't change things into LaTeX format so the whole "preview" concept is not working. I know nothing about Javascript so don't really know how I can make this work. Here is the code I have in HTML, this is also in a django template: <textarea name="statement" required rows="10" cols="40" id="excer"> </textarea><br> <br> Excercise number:<br> <input type="number" name="excercise_number" required id="id_excercise_number" /><br> <input type="submit" name="submit" value="Add Excercise" /> </form> <div id="pre_excer"></div> <script type="text/javascript"> var excer = document.getElementById("excer"); excer.onkeyup = excer.onkeypress = function(){ document.getElementById("pre_excer").innerHTML = this.value; } </script> And this is what I'm using to change regular text into LaTeX, it is inside the head tag: <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML' async></script> which I got from mathjax -
Return back processed file to the user using django
if i have a website running in windows 2012 server to serve a program that i created using Django(localhost:8000/myprogram) that program takes 2 files (.csv/.txt) and combine it together, produce it as an output (output.csv/output.txt), now how do i make the program spits/sends back the processed file to the user so they can download the output? -
how to get flat value from muitiple values_list? Django database
I am getting postgresql data from my server and fill out the table down below. I was able to join 3 different tables and get columns I want from them. However, it gives me none-formatted object. Is there any way I can fill out the table using joined query one by one..? enter image description here enter image description here views.py vlan_query_results = Vlans.objects.select_related('vlan_id').values_list('name', 'gateways__vip', 'gateways__backup', 'gateways__master', 'gateways__nat', 'gateways__vhid', 'subnets__dhcp', 'subnets__dns').order_by('vlan_id') template {% for object in vlan_query_results %} <tr #id='items-table'> <th scope="row" class="checkbox-row"><input type="checkbox" name="item" /></th> <th scope="row">{{ forloop.counter }}</th> <td class="item"> {{object }}</td> <td class="item"> </td> </tr> {% endfor %} -
How to set up double nested serializer in Django Rest Framework
I am trying to figure out how to set up my nested serializers. # models.py class Product(models.Model): sku = models.CharField() product_name = models.CharField() class Order(models.Model): name = models.CharField() address = models.CharField() class OrderProduct(models.Model): order = models.ForeignKey( Order ) product = models.ForeignKey( Product ) quantity = models.IntegerField() So I want to have an api that can create an order in the form of the following: { "name" : "James", "address" : "100 Main St", "products" : [ { "sku" : "1234", "quantity" : 1 } ] } I understand that I would need nest OrderProductSerializer inside OrderSerializer, but how do I implement it here when the "products" data use the field "sku" which is not found in the OrderProduct model. Do I do double-nesting? How does that look like? # serializers.py class OrderProductSerializer( serializers.ModelSerializer): class Meta: model = OrderProduct exclude = () class OrderSerializer(serializers.ModelSerializer): products = OrderProductsSerializer(many=True) class Meta: model = Order exclude = () -
Django FileUploadField Always Flunks Validation with "No File Uploaded" Error
I am using a django ModelForm and CreateView with AJAX form submission to allow a user to upload a file. Even after selecting a file, upon clicking submit, the field is set to blank and form fails validation claiming that no file has been selected. I believe I have taken care of the normal culprits for this sort of behavior. I have set enctype="multipart/form-data and method=post in my form. ModelForm save method includes files, so I'm not sure why the uploaded file is not going through. Here is the form html: <form id="application_form_id" method="post" action="{% url 'jobs:submit_application_form' job_pk=job.pk %}" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" id="applicationModalLabel">Apply</h5> <button type="button" class="close" id="applicationClose" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div id="application_form_content" class="modal-body"> {% include 'jobs/basic_form.html' %} </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> And here is the CreateView: class JobApplicationFormView(LoginRequiredMixin, generic.edit.CreateView): model = JobApplication user_model = User context_object_name = 'application' form_class = JobApplicationForm template_name = 'jobs/student/student_job_detail.html' success_url = reverse_lazy('jobs:student_job_detail') def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): valid = False data = { 'form': render_to_string('jobs/basic_form.html', request = self.request, context = {'form' : form}), 'valid': valid, } return JsonResponse(data) else: return response def form_valid(self, form): form.instance.student_user = self.request.user form.instance.job = … -
no such table: Schedule_playerweightlifting
migrations.CreateModel( name='PlayerWeightLifting', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('time', models.IntegerField(default=-1)), ('medal', models.CharField(blank=True, choices=[('GOLD', 'GOLD'), ('SILVER', 'SILVER'), ('BRONZE', 'BRONZE'), ('FOURTH', 'FOURTH')], max_length=256)), ('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Schedule.Player')), ], options={ 'ordering': ['time'], }, ), This is my model PlayerWeightLifting from 0001_initial.py file. But when i am running it, it is showing "no such table: Schedule_playerweightlifting", Below is my corresponding model: class PlayerWeightLifting(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) weightlifting = models.ForeignKey(WeightLifting, on_delete=models.CASCADE, default='') time = models.IntegerField(default=-1) medal = models.CharField(max_length=256,blank=True, choices=MEDAL_CHOICES) def __str__(self): return str(self.weightlifting) + str(" ") + str(self.player) class Meta: ordering = ['time'] I have an another similar type of model class, which is working fine, i am stuck in this database thing. Help me! This is the portion from admin.py : admin.site.register(PlayerWeightLifting) There is no type of error showing on terminal while running python manage.py makemigrations and python manage.py migrate command, but when i am opening admin, it is just showing, no such table, what can be the probable causes? I even tried Python manage.py migrate --run-syncdb Any help will be appreciated!Thanks :) -
Connecting Django and Three.js geometry
I am developing a web application where the user should be able to change the geometry dimensions through the three.js (dat.gui.min.js). I have the script running locally, but once that i try to applied it in Django the geometry doesn´t show and i get a error (Uncaught SyntaxError: Unexpected token <) bellow my HTML file: (the cube_004.js is the javascript thats renders the geometry and before that i am loading all the necessary threejs packages). <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Julius+Sans+One" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Julius+Sans+One" rel="stylesheet"> <link rel="stylesheet" href="{% static "css/master_001.css" %}"/> </head> <body> <h1>GUI</h1> <div id="canvas" class="padding"> <!-- load three library geometry --> <script src= "{% static "Java_Libraries/three.js" %}"> </script> <!-- load GUI Features --> <script src= "{% static "Java_Libraries/dat.gui.min.js" %}"> </script> <!-- load orbit features --> <script src= "{% static "Java_Libraries/OrbitControls.js" %}"> </script> <!-- load the geometry script --> <script id="cube" src= "Java_Libraries/cube_004.js" ></script> </div> <div class="container" align='center'> <a href={% url 'cover' %}> <button id="quit" type="button" class="btn btn-dark">Quit</button> </a> </div> </body> </html> Thank you in advance! Any further info to understand the bug, please just ask!!! Best, T -
How to choose initial drop-down option from database in view.py?
I am populating 3 forms from database. All are populating, but my dropdown list will still be on the first selection "-----" rather than what it is in the dropdown. I am wondering if there is a way in views.py to set the initial option to what is in the database? -
How to use abstract model as a ForeignKey in Django?
I have a model like this: class A(models.Model): .... .... class Meta: abstract = True class B(A): blah.. blah.. class C(A): blah.. blah.. Just i want to use Model A as a forignKey in different model like this:- class X(models.Model): """ I want to use like this, But i'm getting error """ name = models.ForeignKey(A) But I'm getting Error: apis.X.name: (fields.E300) Field defines a relation with model 'A', which is either not installed, or is abstract. Am I doing something wrong? How can to avoid this? Thanks in advance -
templates cannot be found when virtual environment is activated
I am facing a rather peculiar problem. I have built a Django application and only while deploying it, I created a virtual environment(I didn't use virtual environment while building and testing it locally). Now when virtual environment is activated and also when deactivated, the HTML templates cannot be found. Below is the screenshot. Seeing this statement, Python Executable: /home/shadowsaint/Programs/Django/zoomtail/venv/bin/python I went back to terminal and typed which python command. For that it shows /home/shadowsaint/Programs/Django/zoomtail/venv/bin/python Now when I deactivate virtual environment also the which python command gives the same thing. But when I delete the venv file, and run which python it gives, /usr/bin/python And now the application runs fine, i.e., the HTML templates are being found. I have three questions here. When I activate venv, the python used from venv/bin is fine. But even when I deactivate virtual environment why the same python is being used? What does python package(both the versions are same) have to do with templates being found? Is the underlying principle here the same as that in here too - No module named PIL in heroku though it is installed Please help. A newbie here and these errors are very frustrating. Thank you. -
How to routing Index using Django app with one request?
I have made myself a nice little Django app, but I recently understand when Index page is requested, 2 request sent to Django, I found where is the problem but I don't have any solution for it. project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls', namespace='myapp')), ] myapp urls.py: app_name = 'myapp' urlpatterns = [ path('', views.index, name='index'), ] When I request: http://127.0.0.1:8000, first Django check this line: path('', include('myapp.urls', namespace='myapp')), and after map myapp urls, check this line: path('', views.index, name='index'), so 2 requests has processed, as show in console: [06/Jul/2018 14:28:59] "GET / HTTP/1.1" 200 11904 [06/Jul/2018 14:28:59] "GET / HTTP/1.1" 200 11904 how can solve this problem? anybody know? -
update multiple django id's at once
I have a django html page where I have multiple records total 3 colomns(id,P_350,P_450) and I want to update at once when I click submit button. It is working fine when I was updating one by one but I wanted to update multiple records so that I added a loop "for id in ids:" in front to access multiple id's; but somehow I did not able to make it work. My questions is: Should I use also getlist method for the other P_350 and P_450 Am I doing correct by looping ids.If not how can I do that ? Here is my view.py file: ids = request.POST.getlist("id") P_350 = request.POST["P_350"] P_450 = request.POST["P_450"] for id in ids: fp_item = fp.objects.get(id=id) items=[P_350,P_450] for index, w in enumerate(items): if index == 0: if len(w) > 1: fp_item.P_350 = w fp_item.save() elif index == 1: if len(w) > 1: fp_item.P_450 = w fp_item.save() Here is my html file input section: <td style="display:none;"> <input name="id" type="text" value={{ field.id }} > </td> <td width="650"> {{ field.FP_Item }} </td> {% if field.P_350|length == 0 %} <td style="display:none;"> {% else %} <td> {% endif %} <input name="P_350" type="text" value={{ field.P_350 }} > </td> {% if field.P_450|length == … -
Django: Can't update database properly
models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500, verbose_name='Title') post = models.TextField(verbose_name='Post') post_time = models.DateTimeField() update_time = models.DateTimeField() exists = models.BooleanField(default=True) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.id: self.post_time = timezone.now() # self.exists = True self.update_time = timezone.now() return super(Post, self).save(*args, **kwargs) class PostEditHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) title = models.CharField(max_length=500) body = models.TextField() edit_time = models.DateTimeField() views.py @login_required def edit_post(request, username, post_id): other_user = User.objects.get(username=username) post = Post.objects.get(user=other_user.pk, pk=post_id) prev_post = post form = EditPostForm(data=request.POST or None, instance=post) if form.is_valid(): PostEditHistory.objects.create( user=request.user, post=prev_post, title=prev_post.title, body=prev_post.post, edit_time=prev_post.update_time ) return redirect('single_post', username=username, post_id=post_id) form.save() context = { 'form': form } return render(request, 'blog_post/edit_post.html', context) Before saving edited post, I'm trying to save the original post to PostEditHistory model. Every time a post is edited, it performs the same operations. But the code save the edited post to both Post and PostEditHistory model, and the original one gets lost. Help me to solve the problem. Thanks in advance. -
Mapping a ForeignKey with another class
This is my Django Models.py class Test1(models.Model): id = models.AutoField(db_column='Id', primary_key=True) name = models.TextField(db_column='Name', blank=True, null=True) class Test2(models.Model): id = models.AutoField(db_column='Id', primary_key=True) sequence = models.IntegerField(db_column='Sequence') test1id = models.ForeignKey('Test1', models.DO_NOTHING,null=False, db_column='Test1Id') what i am trying to do is to ensure when the Test1 id is saved, it automatically fills in the test1id. -
Django Admin save_model() creates a new object when I only try to edit
My original issue was that I was trying to attach the current user to new entries, so I override the save_model method under admin.ModelAdmin to do def save_model(self, request, obj, form, change): obj.submit_usr = request.user super().save_model(request, obj, form, change) This works great when I try to create new object or new entry in my db, but when I try to edit the existing one, it still creates a new entry my model looks like (I took out all the settings to avoid being messy here) class AppUser(models.Model): app_name = model.CharField() submit_usr = models.ForeignKey() submit_date = model.DateTimeField() I know that the change arg indicates if there's a change in existing entry, but I still don't have a way to tell Django that I only want to modify the current entry instead of creating a new one. Any ideas how to achieve that? -
How to move some values of a dict to a class?
My goal was to have 2 urls, url A and url B and even though it's always the same URL, I could be on different "steps" (like ~2 different single page applications) So I've defined the UUID for the URLs and from this I needed to have the classes based on the step in those SPA's. I wanted also (hence this question) to see where I was into the database. So I had to make a Charfield that had choices based on both the current URL + the current step into this URLs. Here's what I did: class MyModel(models.Model): X_UUID_A = 'x-0' X_UUID_B = 'x-1' X_TAB_UUID = [ X_UUID_A, X_UUID_B, ] # for A XA_STEP_ONE = u'a000 one' XA_STEP_TWO = u'a010 two' # for B XB_STEP_ONE = u'b000 one' XB_STEP_TWO = u'b010 two' TAB_X_STEP = { X_UUID_A: { XA_STEP_ONE: { 'description': _(u"A - Step 1"), 'breadcrumb': _(u"A - Step 1"), 'class': XAStep1, }, XA_STEP_TWO: { 'description': _(u"A - Step 2"), 'breadcrumb': _(u"A - Step 2"), 'class': XAStep2, }, }, X_UUID_B: { XB_STEP_ONE: { 'description': _(u"B - Step 1"), 'breadcrumb': _(u"B - Step 1"), 'class': XAStep1, }, XB_STEP_TWO: { 'description': _(u"B - Step 2"), 'breadcrumb': _(u"B - Step 2"), 'class': XAStep2, … -
How can I disable the rendering of a form input field in django form
I've got the following Form. I let Django render the form automatically for me in my template with: {{ form.as_p() }}. As you can see I've got the company field, however, it's redundant as I am setting the company by clean_company. The company field is hidden, but I want it to be completely gone in the template. I still need it in the form though, because I want to be able to call: form.save(commit=True). Is there a way to get the hidden field out of my template? class PlantPurchaseForm(forms.ModelForm): company = forms.CharField(initial="", widget=forms.HiddenInput()) number = forms.IntegerField(initial=10000, min_value=10000, max_value=99999) date = forms.DateField(widget=forms.DateInput(attrs={"type": "date"})) class Meta: model = PlantPurchase fields = ( "company", "number", "date", "plant", "costs", ) def __init__(self, company, *args, **kwargs): self.company = company super(PlantPurchaseForm, self).__init__(*args, **kwargs) def clean_company(self): data = self.cleaned_data["company"] data = self.company return data def clean_date(self): data = self.cleaned_data["date"] data = datetime.combine(data, time(hour=12)) data = pytz.utc.localize(data) return data The PlantPurchase Model: class PlantPurchase(models.Model): company = models.ForeignKey(Company, related_name="plant_purchases") number = models.PositiveSmallIntegerField(unique=True, validators=[MinValueValidator(10000), MaxValueValidator(99999)]) date = models.DateTimeField() plant = models.ForeignKey(Plant, related_name="plant_purchase", on_delete=models.PROTECT) costs = models.DecimalField(max_digits=8, decimal_places=2) class Meta: unique_together = ("company", "number") def __str__(self): text = "Purchase: #{} {}".format(self.number, self.plant) return text -
django prefetch_related & Prefetch nested
I'm trying to return, for each UserProfile, which has one-to-many Subscription, which has a Foreignkey to both Artist and UserProfile, with each artist having many ReleaseGroup, the count of future release groups that each UserProfile have. In short: I want to return the total count of upcoming releases for all of the subscription that each of the users have. However I'm getting stuck way before I get to count... context['test_totals'] = UserProfile.objects.prefetch_related( Prefetch('subscription_set', queryset=Subscription.objects. prefetch_related(Prefetch('artist', queryset=Artist.objects. prefetch_related(Prefetch('release_groups', queryset=ReleaseGroup.objects.filter( release_date__gte=startdate ), to_attr='rggg')), to_attr='arti')), to_attr='arts')) accessing userprofile.arts|length in template returns total number of subscription, but rggg and arti return nothing. How can this be done? I tried using filtering on self with, say, filter(profile='userprofile)`, but that returns an error. If I could filter on self I could probably get this to work? -
How to deleted a Django project under virtualenv?
I have used virtualenv created a Django project: django-admin.py startproject myweb But now I want to remove/delete this project,what should I do? Can I just directly rm -r myweb or not? -
django seed data with foreign keys
I'm getting a model does not exist error when trying to seed data with foreign keys. How do I seed data with foreign keys? def forward_func(apps, schema_editor): A = apps.get_model("myapp", "A") B = apps.get_model("myapp", "B") db_alias = schema_editor.connection.alias a = A.objects.get(name='test') # <--- FAILS HERE b = B.objects.using(db_alias).create(name="blah", a=a) Note that if I do A.objects.all() and cycle through them I indeed find the object that I am looking for. So I know it is in the database. So what am I doing wrong? -
Django Create a form with using 3 models with foreign key relationships
I am trying to create a form with three models. I am having trouble making the view for the form. I can't seem to figure out how to save the form so that the foreign keys get saved and get saved with the right primary key. Here are the models: class Solutions(models.Model): class Meta: verbose_name_plural = 'Solutions' title = models.CharField(max_length=100) subtitle = models.TextField() description = models.TextField() image = models.ImageField(upload_to='images/', null=True, verbose_name="") def __str__(self): return self.title + ": " + str(self.image) def get_absolute_url(self): return reverse('solutions:index', kwargs={'pk': self.pk}) class KeyTech(models.Model): keyId = models.ForeignKey(Solutions, on_delete=models.CASCADE, default=None, related_name = 'key') keyField = models.CharField(max_length=200) def __str__(self): return self.keyField class BusinessVal(models.Model): businessId = models.ForeignKey(Solutions, on_delete=models.CASCADE, default=None, related_name = 'bus') busField = models.CharField(max_length=200) def __str__(self): return self.busField I created some code that worked, it just didn't save the foreign key values at all, and when I hit submit the first time, it didn't save the form, it just cleared all the fields except for the foreign key fields. When I re-entered in the main form, then it saved only the main form, and not the foreign key forms. Any help would be appreciated. Thank you in advance! Here is the form I created: class SolutionsForm(forms.ModelForm): class Meta: … -
inlineformset_factory only saves the first form
as described in the title, my formset just saves the first "value" passed. the forms that are added by the user do not have their values saved in the database. models.py class Solicitacao(models.Model): ROLE_CHOICES = ( (1, 'Aberta'), (2, 'Fechada'), ) aberta_fechada = models.PositiveSmallIntegerField('Status da Solicitação', choices=ROLE_CHOICES, default='Aberta'), data_emissao = models.DateTimeField(auto_now_add=True) descricao_solicitacao = models.CharField('Descrição da Solicitacao', max_length=255) numero_descricao = models.CharField(default=numero_solicitacao, max_length=255) movimentacao_relacionamento = models.ForeignKey(Movimentacao, on_delete=models.CASCADE) departamento_relacionamento = models.ForeignKey(Departamento, on_delete=models.CASCADE) class Meta: verbose_name = 'Solicitação' verbose_name_plural = 'Solicitações' def __str__(self): return self.descricao_solicitacao class Unidade(models.Model): UNIDADE_CHOICES = ( ('M²', 'm²'), ('KG', 'kg'), ('UN', 'un'), ('M', 'm'), ('CM', 'cm'), ('MM', 'mm'), ) tipo_unidade = models.CharField('Tipo de Unidade', choices=UNIDADE_CHOICES, max_length=255, blank=True, null=True) unidade_descricao = models.CharField('Descrição Unidade', max_length=255, null=True, blank=True) class Meta: verbose_name = 'Unidade' verbose_name_plural = 'Unidades' def __str__(self): return str(self.tipo_unidade) class Materiais(models.Model): descricao_material = models.CharField('Descrição do Material', max_length=255) class Materiais_Solicitacao(models.Model): descricao_material = models.CharField('Descrição do Material', max_length=255, null=True, blank=True) quantidade_material = models.FloatField('Quantidade de Material', null=False, blank=False) relacionamento_materiais = models.ForeignKey(Materiais, 'Relacionamento com Materiais') relacionamento_solicitacao = models.ForeignKey(Solicitacao, 'Relacionamento com Solicitacao') unidade_relacionamento = models.ForeignKey(Unidade, 'Relacionamento com a unidade') class Meta: verbose_name = 'Material da Solicitação' verbose_name_plural = 'Material das Solicitações' def __str__(self): return str(self.relacionamento_materiais) class Meta: verbose_name = 'Material' verbose_name_plural = 'Materiais' def __str__(self): return self.descricao_material views.py …