Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value too long for type character varying(3) Django Models
I can't seem to find out what is happening, the values for paymenttype are 3 characters long, so if anybody could tell me whats the problem with this model I'd be grateful. class PaymentType(models.Model): INSCRIPTION = 'INS' CROSSSFIT = 'CRF' FUNCTIONAL = 'FUN' KICKBOXING = 'KBX' ALL_ACCESS = 'ALL' UNSPECIFIED = 'UNS' PAYMENT_CHOICES = ( (INSCRIPTION, 'Inscription'), (CROSSSFIT, 'Crossfit'), (FUNCTIONAL, 'Functional'), (KICKBOXING, 'Kickboxing'), (ALL_ACCESS, 'All access'), (UNSPECIFIED, 'Unspecified'), ) payment_code = models.CharField(max_length=3, choices=PAYMENT_CHOICES, default=UNSPECIFIED) amount = models.FloatField() class Payment(models.Model): payment_type = models.ForeignKey(PaymentType, on_delete=models.SET("UNS")) date = models.DateField(default=timezone.now) reference = models.IntegerField() athlete = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.payment_type def get_absolute_url(self): return reverse('payment-detail', kwargs={'pk': self.pk}) -
Saving images names into the database - Django
I have the folllowing class model in my Django website: class Buy(models.Model): category = models.ForeignKey(Category, related_name='sell', on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.FileField() image2 = models.FileField(blank=True) description = models.CharField(max_length=300) date = models.DateField(default=timezone.now) buy_price = models.DecimalField(max_digits=6, decimal_places=2) sell_price = models.DecimalField(max_digits=6, decimal_places=2) seller = models.ForeignKey(Seller, on_delete=models.PROTECT) showcase = models.BooleanField(default=False) As you can see, I store photos files with 2 fields: image and image2. But now my client requested me to add more photos. My doubt is: Should I continue adding new fields to this class, for example, image3, image4, image5 and so on? The problem I see: not every records will have so many photos and the most of them will become "empty". Should I only upload the new photos without saving their names into the database? In this way, the new photos should follow some name related to the image class field. I mean, unique_photo_1.jpg goes inside the image field, unique_photo_2.jpg is not saved into the database but is related to this field, as well as the unique_photo_3.jpg. What is the best practice? Thank you! -
Django - The label doesn't change its name
I am trying to change my label in forms. But despite trying, I can't get a label change for consumer field. I also don't see a typo made by me. models.py class Offer(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Klient') seller = models.ForeignKey(Seller, on_delete=models.CASCADE, verbose_name='Sprzedawca') vat = models.ForeignKey(Vat, on_delete=models.CASCADE, verbose_name='Stawka VAT') annual_usage_kw = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Roczne zużycie KW') monthly_usage_kwh = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Miesięczne zużycie KWH') monthly_usage_zl = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Miesieczne zużycie PLN') excepted_power = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True, verbose_name='Oczekiwana moc KW') roof_orientation = models.ForeignKey(RoofConstruction, on_delete=models.CASCADE, verbose_name='Konstrukcja dachu') price_per_kw = models.ForeignKey(PricePerKw, on_delete=models.CASCADE, verbose_name='Cena za KW') product = models.ManyToManyField(Product, verbose_name='Produkt') inverter = models.ManyToManyField(Inverter, blank=True, verbose_name='Inverter') number_of_product = models.IntegerField(blank=True, null=True, verbose_name='Liczba produktów (opcjonalnie)') employer_margin_price = models.IntegerField(blank=True, null=True, verbose_name='Marża cenowa pracownika') accessories = models.ManyToManyField(Accesorie, blank=True, verbose_name='Akcesoria') forms.py class OfferParametersForm(forms.ModelForm): class Meta: model = Offer fields = ('customer', 'vat', 'annual_usage_kw', 'monthly_usage_kwh', 'monthly_usage_zl', 'excepted_power', 'roof_orientation', 'price_per_kw') labels = {'customer': 'Klient', 'vat': 'VAT', 'annual_usage_kw': 'Roczne zużycie KW', 'monthly_usage_kwh': 'Miesięczne zużycie KWH', 'monthly_usage_zl': 'Miesieczne zużycie PLN', 'excepted_power': 'Oczekiwana moc KW', 'roof_orientation': 'Konstrukcja dachu', 'price_per_kw': 'Cena za KW', } I use my form as method {{ form.as_p }}. I guess I might be making some stupid mistakes. But I don't see … -
Django Autocomplete with jQuery UI | AJAX | Search | Filter from Database
By using database categories. I am trying to make an input field to be autocomplete in postad form. I have written this code and while execuiting i am facing the issue. The error which i got i have pasted below. So i want to make my field to autocomplete, views.py def autocomplete(request): if 'term' in request.GET: qs = vk_categories.objects.filter(cat_name__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.cat_name) # titles = [product.title for product in qs] return JsonResponse(titles, safe=False) return render(request, 'postad.html') postad.html <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ console.log("some"); source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> *html* <form class="valid_form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="container5 postadd"> <h1>Post Ad</h1> <p> <input type="text" placeholder="Title" name="title" maxlength="60"> </p> <p><textarea type="text" placeholder="Write your description.." maxlength="600" name="description"> </textarea></p> <input type="text" name="type" id="Categories" placeholder="Search for your categories"> <p><input type="number" placeholder="Price" name="price" min="0.00" max="100000000000.00" step="0.01"/> <p class="select_p"> <input name="state" placeholder="State" type="text"> <input type="text" placeholder="Zip Code" name="zip"> </p> <p><input type="file" class="myfile" name="image"> <input type="file" class="myfile" name="image1"></p <p><input type="file" class="myfile" name="image2"> <input type="file" class="myfile" name="image3"></p> <input type="submit" value="Submit"></div></form> see below i attached a error what i getting in console [enter image description here][1] [1]: https://i.stack.imgur.com/GY8cW.png -
NuxtJs asyncData get data based on $route
I've been using NuxtJs for a short time and I'm learning how to use the asyncData method. In my project I would like to load data according to the url. Show my code : async asyncData({ $axios, params }) { try { newFolder = false let folder = {} if (params === '/new/folder') { newFolder = true } else { folder = await $axios.$get(`/folder/${params.id}/`) } return { folder, newFolder, } } catch (e) { return { folder: {}, newFolder: false, } } }, As you can see I would like folder to be an empty object if the url is === /new/folder, on the other hand, I would like in other cases to recover the data on my api. But with this code, whatever the url, axios tries to get the api. -
Connect logged user with model
I'm working on small project with Django framework. And as I can implement usage of authentication mechanism, that I can find a solution how to use information about logged user with model I define. In example. I have model that will store information about QSL cards, and I want to have option that depends on which user is logged, his/her QSL cars will be shown from database. I search here and in docs.djangoproject.com but without success. Thanks in advance for any tips or links. -
Django admin list_filter lookup options - ordering issue
I have recently updated an old project from Django 1.11 to 2.2 LTS. I have noticed that the list_filter filters for foreign keys do not longer have an alphabetical order for their lookup names (as it used to). If I create a custom filter, the ordering of the results is correct. list_filter = ( 'modela__modelb' ) What am I missing? -
How can I keep defined data out of the field in django rest framework?
I'm trying to mark the number of comments on some post on the api. First of all, by defining the commentserializer, received the comments after, it declared comments in the defined later, its commentserializer there counting the number of comment_cnt. By the way, if you do this, the comments will be in the fields. Is there a way to remove comments from fields or is there a better way to display the number of comments? Here is my codes. Thanks in advanced models.py class Post (models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author', null=True) title = models.CharField(max_length=40, null=True) text = models.TextField(max_length=300, null=True) tag = models.CharField(max_length=511, null=True) view = models.IntegerField(default=0) liker = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liker', blank=True) comments_cnt = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__ (self) : return self.title class Image (models.Model) : post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) class Comment (models.Model) : author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) serializers.py class AuthorSerializer(serializers.ModelSerializer): profile = serializers.ImageField(use_url=True) class Meta: model = User fields = ['username', 'email', 'profile'] class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ['image'] class CommentSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) text = serializers.CharField(allow_null=True) class Meta: model … -
How to get Django stdout forwarded to Elastic Beanstalk logs?
My Django application runs on Elastic Beanstalk, using Amazon Linux 2 platform. My problem is that output to stdout (e.g. print ("hello world") ) is not stored in any log file found in the log bundle. I just migrated to AL2 from the older Amazon Linux platform. With the legacy platform I did not have issues with logs. -
How to get Django Admin CSS styles to work on Elastic Beanstalk?
I'm running Django on Elastic Beanstalk, Amazon Linux 2 platform. Proxy server is nginx. Django admin does work, but the styles do not. I get the following error message: Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. How can I fix this? -
How to read pdf file from frontend using Django framework?
I am trying to read pdf file content using Django framework. what I have tried till now is def upload(request): try: if request.method == 'POST': if request.FILES['document'].name.split('.')[-1] == "pdf": input = request.FILES['document'].read().decode() print(input) return HttpResponse('upload Products') except Exception: traceback.print_exc() input = request.FILES['document'].read().decode() // This method gives error like 'utf-8' codec can't decode byte 0x9c in position 72: invalid start byte input = request.FILES['document'].read() I am not able to decode the Output b'%PDF-1.4\n%\xc3\xa4\xc3\xbc\xc3\xb6\xc3\x9f\n2 0 obj\n<</Length 3 0 R/Filter/FlateDecode>>\nstream\nx\x9c\xdd\x1b\xcb\x8e\xe3\xb8\xf1\xde_\xe1\xf3\x02\xee\x88ER\x94\x80\x81\x01\xdbm\x07\xd8\xdbf\x1a\xc8!\xc8\xc9\xc9&Xx\x03d/\xfb\xfb xa9'Yz\xd8\xed\xe9\xde\x1c\xa6\xd1\x18O\x95$\x92\xf5\xae\x12Y\xea\x9e\xc3\xe6\xf7\xa7\xffn\xbaM\x87P\x1e\xf33l\x86\x14\x9e\x87\xcdo\xff|\xfa\xeb\x0f\x9b\xff<\x85\r\xfd\xfd\xf6\xaf\xa7\x0eo\xc0\xe6\xd7'{\x086W\x1d@C\xaf:\x05\xfd/\xf7 xfe\xfd\xf4\xf3\x0f\x93A\xd1\r\x8a\xf7\x0619\xf8\x87\x8b\x1e^\x9fr\xc6'\x06\xc0\x9f\xd7\x7fl\xfetFj\x86\xcd\xeb\xcf_\xba\xb0{\xfd\xe5\xe9\xf4\xfa\xf4\xd3\xecy\x08\xf0\x9c\xee\x0f\xe8\x9e\xbb\xae\x0c\t\xd7\x8e\xb9\x1fz\xfc?\r\x103M\x00 cA\xe6\x87\xd8\xe3\x1c\xbf>\x11q\x02_\x99P\x12MQ\x16\xd2\x1c\xd3\xe7\xfc\x0c\xd7'\x91\xc2\x8d\xf5\xfe\xf2g\xa2\xfd\xb9\xc4<l~G\x06~DI\xff Do I have to do anything with content type which is application/pdf -
Accessing "request" object within Jinja2 "environment" function
I am currently working on a project which heavily uses Jinja2 for template rendering. The relevant code looks like this: settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'request/templates'), os.path.join(BASE_DIR, 'core/templates'), os.path.join(BASE_DIR, 'vaux/templates')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'myapp.jinja2.environment', 'extensions': ['jinja2.ext.i18n', 'jinja2.ext.do', 'vcom.jinja2.blockcache', 'jinja2.ext.with_'], 'autoescape': False, 'bytecode_cache': FileSystemBytecodeCache(CACHE_DIR), 'auto_reload': True, 'lstrip_blocks': True, 'trim_blocks': True, }, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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' ], }, }, ] myapp/jinja2.py file looks like this: def environment(**options): env = Environment(**options) env.globals.update({ 'some_global_context_var': 'Some value' }) # how do I access request ? So that I can write something like request.META['HTTP_HOST'] So my goal now is to try to get access to the request object, so that I can write something like request.META['HTTP_HOST']. Is there any way to do that ? Prior to this, I tried to come up with a global context var using Django's vanilla `context processors' concept, but with Jinja2 it is not so easy. -
Query an attribute of many to many object in django
In my Django Model I want to query a many to many related object and get value of another attribute Models.py class FlowKits(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) trip_cost = models.IntegerField(default=0) class Flow(models.Model): flow_name = models.CharField(max_length=500, default=0) kits = models.ManyToManyField(FlowKits) owner = models.ForeignKey(User, on_delete=models.CASCADE) How can I get the trip_cost of a flow whose flow_name = 'Foo' and kit = 'bar'? I got the Flow object but how to proceed? t = Flow.objects.get(flow_name = 'Foo') -
Don't put the current value in the form
Faced such a problem that the current values about the user are not passed to the form. What I want to do is to combine the user model and the profile model, then display the current user data in two forms for editing. It seems to be done correctly, but for some reason it does not work. Please tell me who understands this) file views.py: class ProfilePage(UpdateView): model=Profile template_name="market/profile.html" form_class=ProfileUpdateForm second_model = User second_form_class= UserUpdateForm def get_context_data(self, **kwargs): context = super(ProfilePage,self).get_context_data(**kwargs) context['UserUpdateForm'] = UserUpdateForm( prefix='UserUpdateForm', data = self.request.POST, instance=self.request.user, ) context['ProfileUpdateForm'] = ProfileUpdateForm( prefix='ProfileUpdateForm', data = self.request.POST, files = self.request.FILES, instance=self.request.user.profile, ) return context def post(self, request, *args, **kwargs): super(ProfilePage,self).post(self, request, *args, **kwargs) context = self.get_context_data(**kwargs) if context['UserUpdateForm'].is_valid(): context['UserUpdateForm'].save() elif context['ProfileUpdateForm'].is_valid(): context['ProfileUpdateForm'].save() return self.render_to_response(context) file forms.py: class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ("username",) class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=('valuta','slug','avtor') file models.py: class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) avtor=models.ImageField(default='user_images/default.jpg', upload_to='user_images',blank=True) slug=models.SlugField(max_length=50, unique=True,blank=True) valuta=models.ForeignKey(Valuta,default="5", on_delete=models.CASCADE) -
How to preserve form values after submit?
I'm preparing a simple search/filter form for my django project and I would like to have all options kept after clicking 'submit' button. I'm using select options, inputs and checkboxes. Is there any all-purpose solution for this? The method used is GET Here's the code: <form method = "GET" action = "."> <div class="form-row"> <div class="form-group col-8"> <label for="filter_by_name">Search by name</label> <div class="input-group"> <input class="form-control py2 border-right-0 border" type="search" name="filter_by_name" placeholder="Name contains.."/> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> <div class="form-group col-md-4"> <label for="filter_by_shop">Search by shop</label> <select id="filter_by_shop" class="form-control" name="filter_by_shop"> <option selected>All shops</option> <option>first shop</option> <option>second shop</option> </select> </div> </div> <div class="input-group col-md-8 checkboxes"> <span> <input type="checkbox" name="first" value="first"\> <label >first</label> <input type="checkbox" name="second" value="second"\> <label >second</label> <input type="checkbox" name="third" value="third"\> <label >third</label> </span> </div> <div class="form-group col-md-2"> </div> <button type="submit" class="btn btn-primary">Search</button> </div> </form> def myView(request): qs = v_pricenew.objects.all().order_by('PRICE') filter_by_name = request.GET.get('filter_by_name') filter_by_shop = request.GET.get('filter_by_shop') if is_valid_queryparameter(filter_by_name): qs = qs.filter(NAME__icontains=filter_by_name) if is_valid_queryparameter(filter_by_shop): qs = qs.filter(SHOP__icontains = filter_by_shop) filter_list = [] if first: filter_list.append('firstCat') if second: filter_list.append('secondCat') if third: filter_list.append('thirdCat') if len(filter_list) != 0: qs = qs.filter(CAT__in = filter_list) context = { 'queryset': qs } return render(request, 'compare_app/main.html', context) I managed to achieve this using … -
How do I make a search bar that will get a query from saved entry without a model
Def search(request): Lists = util.lists.entries() Object_list = lists.objects.GET.get('q') Return object_list -
Render variables in DB strings?
I'm building a survey tool. The questions will be derived from templates. But of course, it would be nice if they would contain personalized elements, too. Here is an example: How many products from {{ brand_name }} do you buy per week? This information should not be rendered in a HTML template but rather sent via JSON. Django comes with functions like render_to_string that take a context object and a template path. But I'm not sure if they can be used here. I'm super happy for any help! Thanks! -
How can I do to add the condition AND using exlude?
I have this query : MyTable.objects.filter(date=date).exclude(starthour__range=(start, end), endhour__range=(start, end)) But I want exclude the queries that starthour__range=(start, end) AND endhour__range=(start, end) not OR. I think in this case the OR is used. Could you help me please ? Thank you very much ! -
Enable user to add item to a list dynamically using Django and Ajax
I am trying to build functionality into my webapp the does the following: A user searches for an address Nearby cafes are pulled from a database table and displayed to them The user is able to click an "add-to-list" tag The cafe name/address are added to a list made by the user I have successfully built 1 and 2. I am struggling with 3 and 4. The Current Situation I am trying to pass the cafeName at this stage via an AJAX post call, but it doesn't look like it is firing correctly. Initially I was trying to do this with AJAX and views.py function but was advised to use Django Rest Framework, so I am now creating an api and using Ajax to pass the cafe details async. The Code At this stage my models.py file looks like this class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) class Meta: managed = False db_table = 'a_cafes' class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? class Venues(models.Model): venue_name = models.CharField(max_length=255) venue_address = models.CharField(max_length=100) venue_long = models.FloatField(null=True) venue_lat = models.FloatField(null=True) venue_geolocation = models.PointField(geography=True, blank=True, … -
Request parameter explanation
In messages.success(request, 'Account was created'+user) is the request keyword requesting messages.success or 'Account was created'+user? -
Programming Error at/ relation "project_app_category" does not exist
I am trying to run "docker-compose up" and my django app is not seeing all my Database tables. I have run migrations multiple times and i have also syncdb but it's all to no avail. I am using PostgreSQL as my db and all the database tables exist in the DB. This is my settings.py file DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "Vendor", "USER" : "postgres", "PASSWORD" : "sangobiyi", "HOST" : "db", "POST" : "5432", } } docker-compose.yml version: '3.4' services: db: image: postgres:latest restart: always environment: POSTGRES_DB: 'Vendor' POSTGRES_USER: 'postgres' POSTGRES_PASSWORD: 'sangobiyi' web: build: . image: temiloluwaelizabeth/vendor-business:v1.0.0 command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/vendor_business ports: - "8000:8000" depends_on: - db Dockerfile FOM tiangolo/uwsgi-nginx:python3.8 LABEL Name-code6 Version=0.0.1 EXPOSE 8000 ENV LISTEN_PORT=8000 ENV USWGI_INI uswgi.information WORKDIR /app ADD . /app RUN chmod g+w /app ADD requirements.txt . RUN python -m pip install -r requirements.txt Whenever i change the host to "localhost" in my settings.py file and run python manage.py runserver it works fine but when i change the host in my settings.py to "db" and run docker-compose up it throws the programming error. i have tried multiple times to run migrations and everything has migrated -
If and else statements in Django template
I am doing an encyclopedia project and on the homepage there is a search field where the user can enter in the title of an entry to perform a search. If there is a complete match, then the entry page will load. If there is a partial match then it will lead to a search page that will list some entry suggestions with similar titles. If there is no match or the search was performed without a query, I want the search page to display a message telling the user no entries have been found. I have the first 2 conditions down and they are working fine but I am struggling with getting the page to display the error for no entries found. views.py def search(request): value = request.GET.get('q','') if(util.get_entry(value) is not None): return HttpResponseRedirect(reverse("entry", kwargs={'entry': value })) else: subStringEntries = [] for entry in util.list_entries(): if value.upper() in entry.upper(): subStringEntries.append(entry) return render(request, "encyclopedia/search.html", { "entries": subStringEntries, "search": True, "value": value }) search.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} {% if search %} <h1>Searching for "{{ value }}"</h1> <h2>Did you mean...</h2> <ul> {% for entry in entries %} <li><a href="{% … -
Django - How to get multiple model data with single POST request?
I have 2 such models. I need to POST the data of 2 models in single POST API Call. Is it possible using viewsets ? class Customer(models.Model): id = models.AutoField(primary=True) customer_name = models.CharField(max_length=255) customer_number = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CustomerReferences(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) reference_name = models.CharField(max_length=255) reference_address = models.CharField(max_length=255) reference_number = models.IntegerField() -
Django Integrity Error NOT NULL constraint failed
I have searched this error over and over now and can't find a response that relates to my issue. I have a modal in my home page which I would like to allow users to update their posts from. I am using an inclusion tag and fbv for this. Here is my view: def update_view(request): profile = Profile.objects.get(user=request.user) if 'submit_u_form' in request.POST: u_form = PostUpdateForm(request.POST) if u_form.is_valid(): instance = u_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() return redirect('posts:index') And here is my custom tag: @register.inclusion_tag('posts/update.html') def update_tag(): u_form = PostUpdateForm() return {'u_form': u_form} Forms.py is here: class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'image', 'category',] Urls.py: urlpatterns = [ path('update/', update_view, name='update'), ] My modal in index.html includes this form: <form action="{% url 'posts:update' %}" method="post" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} <input type="hidden" name="post_id" value={{ post.id }}> {% update_tag %} </div> <div class="modal-footer"> <button type="submit" value="submit" name="submit_u_form">Update Post</button> </div> </form> And update html simply contains {{ u_form }} My form shows up in the modal how I would like it to however upon submit I receive this error: NOT NULL constraint failed: posts_post.author_id Please can someone explain to me why this is happening and how … -
Updating models with unique fields in Django Rest Framework
I get a "value already exists" error when I try to update the existing record. example: I have 10 Companies in a database. Now I want to edit the 4th record. Am looking to update the company "short_name" and leaving the "full_name" unchanged. When I hit submit, an error message is displayed in postman for full_name field "Already Exist" How can I avoid this? Model.py class CompanyProfile(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='ID',) short_name = models.CharField(max_length=30, null=True, blank=True,) full_name = models.CharField(max_length=255, unique = True,) def __str__(self): return str(self.full_name) Serializers.py class RegisterationCompanySerializer(serializers.ModelSerializer): short_name = serializers.CharField( max_length=30, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Short Name already exists or already in use")], ) full_name = serializers.CharField( max_length=255, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Full Name already exists or already in use")], ) class Meta: model = CompanyProfile fields = '__all__' extra_kwargs = { 'short_name': {'required': True}, 'full_name': {'required': True}, } views.py class MainCompanyProfileView(viewsets.ModelViewSet): queryset = CompanyProfile.objects.all() serializer_class = RegisterationCompanySerializer permission_classes = (permissions.AllowAny,) def update(self, request, pk=id ,*args, **kwargs): partial = kwargs.pop('partial', False) instance = get_object_or_404(CompanyProfile, id = pk) serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return super().update(request, *args, **kwargs) urls.py router = DefaultRouter() router.register('', MainCompanyProfileView) urlpatterns = [ path('v1/', include(router.urls)), ] Stacktrace Note: There are a lot of fields in each company have …