Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot have a SlugRelatedField to a FileField in a DRF Serializer?
I have a Model w/ a foreign-key relationship to another Model w/ a FileField. I am unable to serialize the 1st model using a serializer w/ a SlugRelatedField to the file of the 2nd model. Here is some code: models.py: class Foo(models.Model): name = models.CharField(max_length=100) bar = models.ForeignKey(Bar, blank=True, null=True) class Bar(models.Model): file = models.FileField(blank=True, null=True, upload_to="some_path") serializers.py: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ("name", "bar") bar = serializers.SlugRelatedField(read_only=True, slug_field="file") But when I try to serialize an instance of Foo I get the following sort of error: UnicodeDecodeError at /api/foo/1/ 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte Any suggestions? -
Django: Move columns, fields from Child Model to Parent Model?
I currently have a Parent model and a few Child model classes that descend from it. Something like this: class ParentClass(django.db.models.Model) , class ChildClassA(ParentClass) , class ChildClassB(ParentClass) There are several fields that only exist currently on one of the child classes that I would like to exist on all of the child classes. Let's call those fields FieldX, FieldY, and FieldZ. One way I could handle this is by copying FieldX, FieldY, FieldZ to all of the child models. Which isn't a bad solution but is kind of annoying. Is there a good way to move the column/field to the ParentClass? Originally I was going to do it with three migration files: the first migration file would add the columns to the parent class, the second migration file would copy data over, the third would remove the columns from ChildClassA. However, that didn't work. Because Django is smart enough to detect that I was trying to add the same field name to the Parent Class that already exists on one of the Child classes. It raised a n exception for that: django.core.exceptions.FieldError: Local field 'FieldX' in class 'ChildClassA' clashes with field of the same name from base class 'ParentClass'. Instead … -
Django rest_framework returning Server error 500 on UnsupportedMediaType
New to Django REST. My API is supposed to work with JSON content-type. However, when I send a POST body of Content-type text, the API raises UnsupportedMediaType exception as expected, But the response contains 500 Server error instead of 415 Unsupported Media type. -
Django Inline Formset Field Required/Not Required Setting in View
How do I change a field of a inline formset from not required to required in the view? For example, for a form, it would be form.fields['field name'].required = True How do I replicate this setting for an inline formset? I tried formset.fields['field name'].required = True, but was given the error, 'formset' object has no attribute fields. -
How to use django selenium testing in GitHub actions?
I am creating a Django project and I have created a test case that inherits from django.test.LiveSeverTestCase (so it uses selenium): from django.test import LiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver class FrontEndTestCase(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) # Get the URL cls.selenium.get('http://127.0.0.1:8000/vota/') # Add CSRFToken cls.selenium.add_cookie({'name': 'csrftoken', 'value': '1cY4Yb3SljOqj9tUndW1YlIokNOD8tNc2MSU5iKNvsZW8co9WoOOCVGd5RFzxD8P'}) # Define page sections cls.choose_comps = cls.selenium.find_element_by_id('choose-comps') cls.poll = cls.selenium.find_element_by_id('poll-container') cls.end_table = cls.selenium.find_element_by_id('table-container') cls.navs = cls.selenium.find_elements_by_class_name('nav-link') @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() The tests are irrelevant to my problem, so I won't include them for the sake of longness. As you probably realize, for this test case to work, I have to start the server with python manage.py runserver. The problem here is that I want to use all these tests in GitHub Actions, and so far, I have, until creating this testcase. Since I have to start the server first, I made a new step in the job. But this step never ends since the server will always be listening for further requests. I also have to install somehow a chromedriver, a step I don't know how to do. Here is my ci.yml file: name: Testing on: push jobs: test_vote: runs-on: ubuntu-latest services: postgres: image: postgres:10.8 env: POSTGRES_USER: postgres … -
cant save ManyToMany field in django?
i have ManytoMany Field but everytime i save data in forms all data saved except this field (ManyToManyField) this is my views.py @login_required() def post_update(request,id): post = get_object_or_404(Post,id=id) form = PostForm(request.POST or None,request.FILES or None,instance=post ) if request.method == 'POST': if form.is_valid(): instance =form.save(commit=False) instance.user = request.user instance.save() form.save_m2m() messages.success(request, "You successfully updated the post") return redirect(reverse("home:post",kwargs={"id":post.id})) context={"form":form} return render(request,"post_update.html",context) and this is the Error: Internal Server Error: /post/update/4/ Traceback (most recent call last): File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "G:\Web Development\Back End\JustDjango\Build any blog with Django\Blog\blog\BlogApp\views.py", line 111, in post_update form.save_m2m() File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py", line 443, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\taggit\managers.py", line 543, in save_form_data getattr(instance, self.name).set(*value) TypeError: set() argument after * must be an iterable, not NoneType -
Django - create ForeignKey reference based on existing value in referenced model
models.py: class Thread(models.Model): title = models.CharField(max_length=400) discussion = models.URLField(max_length=250, unique=True, blank=True, null=True) ... class Comment(models.Model): thread = models.ForeignKey('Thread', null=True, on_delete=models.SET_NULL) thread_name = models.CharField(max_length=100) thread_link = models.URLField(max_length=250) ... addcomments.py: .... clean_comments = list(zip(thread_name, thread_link)) for thread_name, thread_link in clean_comments: # if thread_link exists in Thread model Comment.object.create( thread=???, thread_name=thread_name, thread_link=thread_link) # if not exists Comment.object.create( thread=Null, thread_name=thread_name, thread_link=thread_link) I want to create Comment object with ForeignKey referencing Thread object if the value of thread_link (Comment model) exists in Thread model (thread_link == discussion). If thread_link != discussion i want ForeignKey to be set to None. I'm thinking about for thread_name, thread_link in clean_comments: filtered = Thread.objects.filter(discussion=thread_link) if filtered: Comment.object.create( thread=???, thread_name=thread_name, thread_link=thread_link) else: Comment.object.create( thread=None, thread_name=thread_name, thread_link=thread_link) -
My views.py is returning null from django admin object
I would really appreciate some help on this because I'm completely stuck. I've started up a simple django app (trying to make an instagram clone). However, when I try to display the post objects (which I created in the django admin page) nothing is displayed in index.html, so I tried printing out the objects in the views.py and it's returning to me an empty query set. I don't quite understand what I'm doing wrong and why I can't access the objects? When I print out the username I am able to get that, but then nothing for both post and stream objects. Please I'm so stuck any advice would be appreciated. views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.template import loader from django.http import HttpResponse # Create your views here. from post.models import post, stream @login_required # we are getting all of the string objects that are created for the user def index(request): user = request.user print(user) posts = stream.objects.filter(user=user) print(posts) group_ids = [] #then looping through and getting post id to a list for posted in posts: group_ids.append(posted.post_id) print(group_ids) #then filtering them so that you can display it in the index #selecting a specific post by … -
why am I receiving this error == Reverse for 'download_done' not found. 'download_done' is not a valid view function or pattern name
I'm trying to create a youtube downloader but when I'm trying to download it gives this error "Reverse for 'download_done' not found. 'download_done' is not a valid view function or pattern name." I have compared the app name and its corresponding, I have also checked the HTML file it looks okay please help me...its urgent views.py from django.shortcuts import render from pytube import YouTube import os # Create your views here. def youtubedownloader(request): return render(request, 'youtube_downloader.html') def download(request): global url url = request.GET.get('url') yt = YouTube(url) video = [] video = yt.streams.filter(progressive=True).all() embed_link = url.replace("watch?v=", "embed/") Title = yt.title context = {'video': video, 'embed': embed_link, 'title': Title} return render(request, 'download.html', context) def download_done(request, resolution): global url homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' if request.method == "POST": YouTube(url).streams.get_by_resolution(resolution).download(dirs) return render(request, 'download_done.html') else: return render(request, 'errorrrr.html') urls.py from django.contrib import admin from django.urls import path from .views import youtubedownloader, download, download_done app_name = 'yt_downloader' urlpatterns = [ path('youtube_downloader/', youtubedownloader, name='youtube downloader'), path('youtube_downloader/download/', download, name='download video'), path('download/<resolution>/', download_done, name='download done') ] download.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1> Title : {{title}} </h1> <div class=" mt-5 embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src={{embed}} allowfullscreen></iframe> </div> <table class="table"> <thead class="thead-light"> … -
Join with double key in Django
I got a question and problem with Django. How can I do this sql query in Django? SELECT * FROM `pot010` LEFT OUTER JOIN `pot042` ON (`pot010`.`ninp10` = `pot042`.`ninp42`and COSE42 = 20202021) Thanks so much. -
I am trying to create an app in Django where registered users can log in and access certain information from the main database
I am trying to create an app in Django where registered users can log in and access certain information from the main database, but I know how to make a filter in Django when the user logs in and on the welcome page show only the database items that I want to show to that user .. Do I have to create a model for each User separate from the login? I appreciate your help -
Is their a straightforward way to limit the number of updates of a certain field in a django model?
For example i use the extended user model called "profile" and in the profile i have many fields describing the using. what i want is that the user choose whether he is a business user or a regular customer on the web site. but once this field is updated it cannot be updated again, in which the field appears in the profile edit form but as non-editable field. What is the best way to do that? I thought of using an additional field in the database where i include an "update date" and if this field is not null then the user cannot update. but it seems to me too much coding for this small feature. Thanks in advance -
Django DetailView but get_object_or_404() instead of get_object()
I have Django Model that has a live boolean attribute. I want the View to get the Model by slug and only go to this page if it's live USING THE DetailView (not function based view, because I want to see how to do it. Model definition # myapp/models.py class MyModel(models.Model): name = models.CharField(max_length=255) live = models.BooleanField(default=True) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.name) I hoped it would be done something like this: class ModelDetailView(DetailView): model = MyModel def get(self, request, *args, **kwargs): service = self.get_object_or_404(Service, live=True) # <- Main point of what I'm looking for help with return super().get(request, *args, *kwargs) Is there a way to filter this way? -
the google map is not showing the nearby results of carwashes?
Any guidance will be helpful! I have implemented some code in my apps in Django as map.html(code is below). The app is able to locate the user's location but it does not show the nearby results of carwashes? do I need to be more specific in the code or am I completely missing something? (the API key has already been inserted I just removed it to be safe) <!DOCTYPE html> <html> <head> <title>CarwashFinder</title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; background-color: grey; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } /* TODO: Step 4A1: Make a generic sidebar */ /* Styling for an info pane that slides out from the left. * Hidden by default. */ #panel { height: 100%; width: null; background-color: white; position: fixed; z-index: 1; overflow-x: hidden; transition: all .2s ease-out; } .open { width: 250px; } /* Styling for place details */ .hero { width: 100%; height: auto; max-height: 166px; display: block; } .place, p { font-family: 'open … -
Django ModelForm issue
I'm having an issue with Django form, Accounts/models.py class MyUser(AbstractBaseUser): email = models.EmailField( max_length=255, unique=True, verbose_name='email addres') name = models.CharField(max_length=255, verbose_name="name") date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) phone_number = models.CharField(max_length=11, verbose_name="Phone Number") is_cliente = models.BooleanField(default=False) is_recebedor = models.BooleanField(default=False) is_colocador = models.BooleanField(default=False) is_dono = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = UserManager() class Meta(): verbose_name_plural = "Usuarios" def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def get_short_name(self): full_name = self.name name_gap = full_name.find(" ") first_name = full_name[:name_gap] return first_name class Dono(models.Model): user = models.OneToOneField( MyUser, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.get_short_name() class Colocador(models.Model): user = models.OneToOneField( MyUser, on_delete=models.CASCADE, primary_key=True) work_for = models.ForeignKey(Dono, models.CASCADE, blank=True, null=True) def __str__(self): return self.user.get_short_name() class Meta(): verbose_name_plural = "Colocadores" class Recebedor(models.Model): user = models.OneToOneField( MyUser, on_delete=models.CASCADE, primary_key=True) work_for = models.ForeignKey(Dono, models.CASCADE, blank=True, null=True) def __str__(self): return self.user.get_short_name() class Meta(): verbose_name_plural = "Recebedores" A 'Dono' user is able to register sales and every sale is related to one 'Colocador' my Venda (Sale in portuguese) model: class Venda(models.Model): STATUS_CHOICES = { ('AV', 'A vencer'), ('PG', 'Pagou'), ('RM', 'Remarque'), ('SM', 'Sumiu'), } name … -
how to fix sql query in django
I'm not sure how to fix 'likesCounter' query. I want to count all likes from one article. Any help is appreciated. ' model: class Likes(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="like_article") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='liker_user') view: def article_detail(request, pk): article = Article.objects.get(pk=pk) already_liked = Likes.objects.filter(article=article, user=request.user) likesCounter = Likes.objects.filter(article=article, user_id=request.user).count() if already_liked: liked = True else: liked = False return render(request, 'article/single-article.html', context={'article':article, 'liked': liked,'likesCounter':likesCounter,'already_liked':already_liked}) -
How to upload NamedTemporaryFile via FileField in Django
I have a NamedTemporaryFile which I wish to upload by updating my Django model. Below is how I am creating the NamedTemporaryFile. I am updating the file through csv.writer error_file = open(tempfile.NamedTemporaryFile().name, 'w+', newline='') I have a model like below: class Logs(models.Model): error_file = models.FileField(upload_to='errors/', blank=True, null=True, max_length=200) I am trying to upload the error_file to the errors directory. from django.core.files.base import File l = Logs.objects.get(pk=1) error_file.seek(0) # I seek the cursor to the starting position before saving l.error_file.save('error1.csv', File(self.error_file)) Below is the error I am getting: AttributeError: 'File' object has no attribute 'temporary_file_path' -
PUT request not working in Django Rest - VueJS app
I'm trying to make a blog useing VueJS and Django with the REST Api (Ajax via Axios). I can send a "PUT" request without errors in the console bur it is not effecting the database, is link the method is not called. I also have a problem with setting by default the already-uploaded image in the input type="file" field. The code: Vuejs <template> <h1>ARTICOLO</h1> <form @submit="onSubmit"> <input type="text" name="title" placeholder="Titolo" v-model="form.title"> <input type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> <input type="text" name="category" v-model="form.category"> <input type="file" name="image" @change="EditImage"> <input type="text" name="author" v-model="form.author"> <input type="text" name="author" v-model="form.slug"> <textarea name="text" v-model="form.text"></textarea> <p>{{ form }}</p> <button type="submit" @click= "onSubmit">Edit</button> </form> </template> <script> import axios from 'axios'; import { getAPI } from '../api' export default { data () { return{ Postslug: this.$route.params.Postslug, form: { title:"", desc:"", text:"", category:"", date:"", author:"", image:"", slug:"", }, selectedFile: '' } }, methods: { EditImage(event){ this.selectedFile = event.target.files[0] console.log(event); }, // Form method onSubmit(event){ const fd = new FormData(); fd.append('image', this.EditImage, this.EditImage.name) event.preventDefault(); axios.put(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, this.form).then(response => { this.form.title = response.data.title this.form.desc = response.data.desc this.form.text = response.data.text this.form.image = this.fd this.form.category = response.data.category this.form.author = response.data.author this.form.slug = response.data.slug }) .catch(err => { console.log(err) }) }, }, created() { getAPI.get(`blog/api/edit/${this.Postslug}`) .then(response => { this.form.title … -
How to use a Formset with Django_Tables2
I love using django_tables2 but I've hit a bit of a snag. I have an edit page with a standard django form for updating a member's details. Within this form there is a table of addresses for the current member which I can render easily with django_tables2 using the following code. from tables.py class AddressTable(tables.Table): address1 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 1'}}) address2 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 2'}}) address3 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 3'}}) address4 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 4'}}) address5 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 5'}}) postcode = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Postcode'}}) class Meta: model = Address fields = ('address1','address2','address3','address4','address5','postcode',) template_name = 'django_tables2/bootstrap.html' attrs={'id':'addresslist', 'class': 'table table-noborder no-table'} and I pass the data from my view like like this from views.py f = AddressListFilter(request.GET, queryset=Address.objects.all(),request=request) addresstable = AddressTable(f.qs) However, the page needs to allow the user to be able to dynamically add as many extra address records as they wish (which I can use javascript to do this) but I then need to pass the entire table, complete with additional address records, back to django for processing when the user hits the submit button within the form. From what I can gather I should be using a django formset to achieve this … -
How to keep the API running and also Consume Pika (RabbitMQ) parallelly
I have a set of API endpoints serving in the Django app. But I also want to consume a queue(from Pika, a message broker) and execute a function when there is a message in the queue. If I consume a queue, it is blocking the thread and API stops serving. I'm not sure how to achieve this. Do I have to use [background tasks][1] or use Multi-Threading to create a new thread and use it to consume? Any sample code to achieve this is much appreciated. [1]: https://django-background-tasks.readthedocs.io/en/latest/#:~:text=In%20Django%20Background%20Task%2C%20all,process)%20to%20execute%20the%20tasks -
How do I properly implement Django formsets with a CreateView ( Class Based View )?
And thanks in advance for any suggestions. I have been playing around with how to properly implement formsets with a CreateView for a couple of days and I'm stuck. Here is my code. My Models: class Team(models.Model): team_name = models.CharField(max_length=264,null=False,blank=False) class Player(models.Model): player_name = models.CharField(max_length=264,null=False,blank=False) team = models.ForeignKey(Team,null=True,on_delete=models.CASCADE) My View: class CreateTeamView(LoginRequiredMixin,CreateView): model = Team form_class = CreateTeamForm template_name = 'create_team.html' def get_context_data(self, **kwargs): context = super(CreateTeamView, self).get_context_data(**kwargs) if self.request.POST: context['new_player'] = NewPlayerFormSet(self.request.POST) else: context['nwe_player'] = NewPlayerFormSet() return context def get_form_kwargs(self, *args, **kwargs): kwargs = super(CreateTeamView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): context = self.get_context_data() new_player_form = context['new_player'] if new_player_form.is_valid(): self.object = form.save() new_player_form.instance = self.object new_player_form.save() instance = form.save() else: return self.render_to_response(self.get_context_data(form=form)) My Forms: class CreateTeamForm(forms.ModelForm): class Meta: model = Team exclude = [] NewPlayerFormSet = inlineformset_factory(Team, Player, extra=1, fields=['player_name',]) My HTML: <div="players> <div="add_players"> {{ new_player.management_form }} {% for form in new_player %} {{ form.id }} {{ form.player_name }} </div> </div> My form is saving one player, but when I try to update the code to save more than one player with the initial CreateView, it only recognizes the first contact. I have overridden the BaseInlineFormset to do validation as shown below.... class NewPlayerFormSet(NewPlayerFormSet,BaseInlineFormSet): player_name = … -
How do you format a Django datepicker as ISO 8601?
We need to display dates in ISO 8601 (yyyy-mm-dd) format throughout our Django site. The dates that we are getting from the database show correctly, however date pickers do not. When I run the django test server in ubuntu, the datepicker appears to use the locale that the OS is set to. When I run the same code in Windows, it uses dd/mm/yyyy. The various input_formats args appear to be getting overridden somehow, even though I have set them everywhere I can find. Is it possible to force datepickers to display yyyy-mm-dd regardless of client settings? If so, how? Here is the code we have so far. forms.py ... class DateInput(forms.DateInput): input_type = "date" input_formats = ["%Y-%m-%d"] options = { "format": "%Y-%m-%d", "autoclose": True } class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=255, required=True) preferred_name = forms.CharField(max_length=255, required=False) email = forms.EmailField(required=True) password = forms.CharField( max_length=255, required=True, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) birth_date = forms.DateField(required=True, widget=DateInput, input_formats=["%Y-%m-%d"]) ... settings.py ... LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = False USE_TZ = True DATE_INPUT_FORMATS = [ '%Y-%m-%d' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%dT%H:%M:%S' ] DATETIME_FORMAT = [ '%Y-%m-%dT%H:%M:%S' ] ... Full code available on GitHub. -
How to test Django messages for a Class Based FormView?
I am struggling to find the proper way to test a FormView. I would like to check if the message (generated through django.contrib.messages) is rendered when the user is not authenticated. I have already read about RequestFactory, Client, Mock, Middleware and I was not able to implement this test in CBV FormView. The problem is not about authenticating user particularly, I want to use the logic in other fields also to test other messages. Here is my code: View: class MyView(FormView): form_class = MyForm template_name = 'app/welcome_template.html' def form_valid(self, form): form_data = form.cleaned_data auth = LDAPBackend() user = auth.authenticate(self.request, username=form_data['login_field'], password=form_data['password_field']) if user: return super(MyView, self).form_valid(form) else: messages.add_message(self.request, messages.WARNING, 'some warning' + str(form_data['other_field'])) return self.form_invalid(form) Form: class MyForm(forms.Form): login_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Login', 'class': 'form-control form-control-sm'}), label='Login:', max_length=20) password_field = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control form-control-sm'}), label='Password:', max_length=20) other_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Select ...', 'class': 'form-control form-control-sm', 'max': '99999999'}), label='Other:') Template: <form autocomplete="off" onsubmit="$('#ModalCenter').modal({backdrop: 'static', keyboard: false})" action="." target="_top" method="post"> {% csrf_token %} <div class="row"> <div> {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div> {% endfor %} {% endif %} </div> <div class="form-group mt-2"> {{ form.login_field.label_tag }} {{ … -
Django Form and two forms with foreign key
I have these models: class Customers(models.Model): ID = models.AutoField(primary_key=True) ... def __str__(self): return str(self.ID) class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... CustomerNoID = models.ForeignKey('Customers', on_delete=models.CASCADE) def __str__(self): return str(self.ID) and my view: def add_customer_view(request): user_id = request.user.id last_customerno = Customers.objects.filter(UserID=user_id).order_by('CustomerNo').last() if not last_customerno: # return '0001' last_customerno = 1000 if last_customerno == 1000: customerno_int = 1000 else: customerno_int = last_customerno.CustomerNo + 1 # if this is a POST request we need to process the form data if request.method == 'POST': customer_form = CustomerForm(request.user.id, request.POST) customer_address_form = CustomerAddressesForm(request.user.id, request.POST) if customer_form.is_valid(): new_customer = customer_form.save(commit=False) new_customer.save() if customer_address_form.is_valid(): new_address = customer_address_form.save(commit=False) new_address.CustomerNoID = new_customer new_address.save() return HttpResponseRedirect('/backend/kunder/') else: customer_form = CustomerForm(request.user.id, initial={'CustomerNo': customerno_int}) customer_address_form = CustomerAddressesForm(request.user.id) return render( request, 'backend/add_customer.html', { 'title': 'WestcoastShop - Backend', 'customer_form': customer_form, 'customer_address_form': customer_address_form } ) But just the Customer is creating not the address I think the form is missing the CustomerNoID and I think I got the right way but after 6 hrs I give up maybe here is a smart guy how finds the error. regards. -
Python / Django - Generating API Documentation - Not using Django Rest
I am working on a Django project that does not use Django Rest On top of this code base I am trying to build a framework to autogenerate swagger documentation From this S.O. Post I am able to get the available Urls: from django.urls import get_resolver urls = get_resolver().reverse_dict urls is a MultiValueDict, here are the first few items in the Dict: MultiValueDict: { <function create_demo at 0x10f6a3820>: [( [('api/v1/create-demo', [])], 'api/v1//create\\-demo$', {}, {} )], 'create_demo': [( [('api/v1/create-demo', [])], 'api/v1/create\\-demo$', {}, {} )], <function users_detail at 0x10f67d280>: [( [('api/v1/users/users/%(user_id)s', ['user_id'])], 'api/v1/users/users/(?P<user_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', {}, {'user_id': <django.urls.converters.UUIDConverter object at 0x10bc3c6a0>} )], 'users_detail': [( [('api/v1/users/users/%(user_id)s', ['user_id'])], 'api/v1/users/users/(?P<user_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', {}, {'user_id': <django.urls.converters.UUIDConverter object at 0x10bc3c6a0>} )] It appears the keys for this dict are a reference to a view function, followed by the url "name" for that function, and the values are lists containing the relative url path and params. My thought is to loop through each function reference and create an entry for the swagger doc. Inside each view function, I will define vars named RequestSchema and ResponseSchema. Ideally I can access those vars, from the function reference, and add that data to the swagger doc as well. The goal is to have documentation that …