Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switching from NoSQL to SQL land in django
I am porting my Mongo-Express app to Postgres-Django. The app includes a simple form for collecting a student's information and the books they have read over the summer. The express API writes the payload to MongoDB. The payload looks like below: { student_id: 123, student_name: 'James Hook', books: [ { book: 'War and Peace', author: 'Leo Tolstoy' }, { book: 'Harry Potter', author: 'JK Rowling' } ] } Mongo is a document-based database so I could store the above payload as-is. Now moving to django-postgres, I have to define models and I can see two options: A. Just create one model with three fields - student_id (IntegerField), student_name (CharField), and books (ArrayField(JSONField)) B. Go full RDBMS and create two models - student and books. Student and book have many-many relationship. Give this, I have a few questions: Q1. If I don't need to index on books, does option A make more sense? Q2. In option A, should it be just JSONField or ArrayField(JSONField)? Q3. In option B, how do we write TWO or more books for one student at a time? Do I need an ArrayFiled there? How does the model would look like and does it violate atomicity constraint … -
Heroku try to deploy python website ,,manage.py collestatic --noninput"
I create a website using Python ,JS, React, Django .When I deployed on Heroku via github, an error occur: -----> Determining which buildpack to use for this app ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. Detected buildpacks: Python,Node.js See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order -----> Python app detected -----> Using Python version specified in Pipfile.lock cp: cannot stat '/tmp/build_02d1f320/requirements.txt': No such file or directory -----> Installing python-3.9.7 -----> Installing pip 20.2.4, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (dee4f1)... -----> Installing SQLite3 -----> $ python leadmanager/manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_02d1f320/leadmanager/manage.py", line 22, in <module> main() File "/tmp/build_02d1f320/leadmanager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in … -
(NOT NULL constraint failed:owner_id)
I make migrations and run migrate. Then, I submit the form for registration but I get NOT NULL constraint. Below is my models: models.py class A(models.Model): u = models.OneToOneField(User, on_delete=models.CASCADE) num = models.IntegerField() class B(models.Model): x = models.ForeignKey(u, on_delete=models.CASCADE) y = models.CharField(max_length = charLen100) forms.py class AForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), required=True), first_name = forms.CharField(max_length=charLen100, widget = forms.TextInput(attrs= {'placeholder': 'First Name'})) last_name = forms.CharField(max_length=charLen100, widget=forms.TextInput(attrs= {'placeholder': 'Last Name'})) num_items = forms.CharField(label="How many items do you own?", widget=forms.Select(choices=ITEM_NUMBER_CHOICES)) class Meta: model = A fields = ('username', 'email', 'password','first_name', 'last_name') class BForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':name'})) class Meta: model = B fields = ('name') views.py def register(request): registered = False if request.method == 'POST': user_form = AForm(request.POST) profile_form = BForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() context_dict = {} context_dict['user_form'] = user_form context_dict['profile_form'] = profile_form context_dict['registered'] = registered return render(request, ..., context=context_dict) so, what I am doing is that I have two tables in database A and B and A can have many B's that is B then holds A as a foreign key. Then, … -
Django migration: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'")
I am trying to deploy a Django app from a development server to a production server I have set up a virtualenv with python 3.8.10, created the mysql database, I am running in the virtualenv. I get no errors from python manage.py check, get "no changes detected" when running python manage.py makemigrations, but when I run ```python manage.py migrate`` I get the following: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last):... final line of the traceback: Django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'") ("classroom" is the name of the app within the project "codex") I just recently rebuilt all of the tables in this database on my development server with no issues. The database on the production server is empty. models.py is in place and complete. I have tried it both with an empty migrations folder and the migration folder removed. The migration does create django_admin_log, django_content_types, django_migrations, but no other tables. All of the other posts I have seen on this have been about have foreign key constraints, but in my models.py all of the tables that have foreign keys are specified after the … -
cant upload multiple images djago - ajax
I'm trying to upload multiple images with ajax request, i'm using modelformset_factory to upload several images , here is my code : class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.is_ajax() and request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return JsonResponse({'success':'success'}) else: messages.error(request,_('error message')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) and here is my template includes html and ajax $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); const formData = new FormData() formData.append('csrf',document.getElementsByName('csrfmiddlewaretoken').value); formData.append('docs0',document.getElementById('id_form-0-docs').files[0]); formData.append('docs1',document.getElementById('id_form-1-docs').files[0]); formData.append('docs2',document.getElementById('id_form-2-docs').files[0]); formData.append('docs3',document.getElementById('id_form-3-docs').files[0]); const form = document.getElementById('docs-uploader-form') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'booking:add_new_image' id=2222 %}".replace(/2222/,parseInt({{obj.id}})), data:formData, dataType:'json', success:successFunction, }) } function successFunction(data){ // console.log(data) form.reset(); alertify.success('added new image') } <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new image" %} </button> <form action="" method="POST" enctype="multipart/form-data" dir="ltr" id="docs-uploader-form">{% csrf_token %} {% for form in images.forms %} {{form.id}} {{images.management_form}} <div class="form-group mt-3" id="images"> {{ form.docs | add_class:'form-control-file' }} </div> {% endfor %} <div class="form-group mt-3" id="formset" style="display: none;"> {{ images.empty_form.docs | add_class:'form-control-file' … -
Django bootstrap collapse isnt working well
i am trying to make a nav bar collapse when a browser window reaches a minimum size it does collapse the right part of the navbar but the button doesnt show a list of the collapsed items which are register and login i am using django latest version with bootstrap3 <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"></button> <a class="navbar-brand" href="{% url 'blogs:Home' %}">MyBlog</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'blogs:blogs' %}">blogs page</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a>hello , {{ user.username }}</a> </li> <li> <a href="{% url 'users:logout' %}">logout</a> </li> {% else %} <li><a href="{% url 'users:register' %}">Register</a></li> <li><a href="{% url 'users:login' %}">Login</a></li> {% endif %} </ul> </div><!--navbar collapse--> </div> </nav> -
How to customize/styling forms using class based views
Is it possible to customize the HTML attributes of the form created by class base views? At this moment, I'm using a generic CreateView: class SlipCreateView(LoginRequiredMixin, CreateView): model = Atum fields = ['atum1', 'atum2', 'atum3', 'atum4', 'atum5', 'atum6', 'atum7'] I want to change, for example, the length and position of the input fields, the color, and others attributes. Is this possible? And if yes, how? Thank you advance. -
Django, Vue and WebSocket - getting client side to work
There was a similar question on SO about this some time ago, though I tried the answers and they did not work. I am implementing a SPA using Django backend and Vue front end with Vue cli. Django is using channels to send JSON via a WebSocket to the frontend, the frontend receives this data and is supposed to update a table. The Django part is working. A connection to the WebSocket is confirmed and data is received in Vue, though I have two problems that I have not been able to find a way to solve: The data, while in a variable, is not being shown on the table and The front end only receives the data once - I don't know how to apply a listener to the WebSocket, or in which part of my Vue app, so that new payloads (I hope I am saying that correctly) are received and updated accordingly. Below I have provided the Django consumers.py file, the Signals.vue view file, and the console.log output showing that the variable does contain the JSON object despite the table remaining blank. Does anyone have an idea of where I am going wrong and how I can … -
Django Model Constraint Condition With Field From Inherited Class - Is It Possible?
I'd like to use a field from a parent class as a constraint condition in a child class. models.py class ParentClass(object): ... is_public = models.BooleanField(default=False) class ChildClass(ParentClass): ... price = models.DecimalField(max_digits=6, decimal_places=2, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['price', 'is_public'], name='null_price'), models.CheckConstraint( check=Q(price__isnull=True) & Q(is_public=True), name='price_exists_check', ) ] When I attempt to migrate, I see this error in my terminal: myapp.ChildClass: (models.E016) 'constraints' refers to field 'is_public' which is not local to model 'ChildClass'. HINT: This issue may be caused by multi-table inheritance. It's obvious why I am seeing this error (is_public field lives in ParentClass). My question is, is it simply not possible then, or can I refactor something? What is my end-goal? To not let an instance of ChildClass is_pulic change to True if the price is null. I'd like to enforce this at the database level. Is there a way and if so, what needs to change? -
Scoped Styling in Django
My base.html ... <body> {% include 'parts/navbar.html' %} <div>This is the base content html file</div> {% block content %} {% endblock %} {% include 'parts/footer.html' %} </body> ... my navbar: <div>NAV</div> my footer: <div>Footer</div> <style> div { color: blueviolet; } </style> The footer style applies also to the nav-div which i don't want. Is scoped styling in Django possible or do i have to use line-styles or some engine etc. -
Try to host a website usigh Python and Django
I create a website using Django , Python ,Redux .This website I wanna to host on a domain that I bought for this project.Now , I am kinda new and I do not understand why I ca not upload the files for this website via my host provider. I understand that I am rlly dump , but I wanna to understand why and how to host this website.In localhost:800 all work great. Code for this website:enter link description here (repository on github) -
Django creates an extra unwanted entry in many-2-many intermediate table
I have a many-2-many relationship between Flight and Passenger. When I try to assign a passenger to a flight object, Django seems to add an extra entry to the intermediate table. Here are the models: class Passenger(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() class Flight(models.Model): time = models.DateTimeField('flight time') destination = models.CharField(max_length=20) passengers = models.ManyToManyField( to=Passenger, symmetrical=True, related_name='flights', blank=True, ) Say the intermediate table looks like this, with passenger Say flight_object is a Flight with ID=1, and passenger_object is a Passenger with ID=2, when I run flight_object.passengers.add(passenger_object) Django adds 2 entries to the intermediate table in the database. The table now looks like this: Both entries with ID=1 and 2 should be there, but 3 is incorrect, and the flight_id foreign key is for a completely different flight! -
Why does stunnel keep throwing "Address already in use (48)"?
I am working in implementing Auth0 in a Django project, using stunnel to create the https connection. I followed this instruction This is my dev_https file: pid= cert = stunnel/stunnel.pem foreground = yes output = stunnel.log [https] accept=8080 connect=8000 TIMEOUTclose=1 However, when want to start the server, using this command: stunnel stunnel/dev_https & python3 manage.py runserver& I get the following: [.] Configuration successful [ ] Deallocating deployed section defaults [ ] Binding service [https] [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to :::8080: Address already in use (48) [ ] Listening file descriptor created (FD=9) [ ] Setting accept socket options (FD=9) [ ] Option SO_REUSEADDR set on accept socket [.] Binding service [https] to 0.0.0.0:8080: Address already in use (48) [!] Binding service [https] failed I tried changing the accept port from 8443 to 8080. Same result I then checked for active processes on the port with lsof -i 8080 This reveals that stunnel is already running on the port. I killed that process and tried again, but I get the same error. Specific questions Can someone briefly explain how … -
How do I set a NOT NULL constraint on Django charfield?
I'm struggling with how I can set a NOT NULL constraint on a charfield. Currently, my model looks like this: class Tutors(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20, blank=False) email = models.EmailField(max_length=254) birth_day = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return(self.first_name + ' ' + self.last_name) I want to make sure that last_name and first_name can't be saved to the database as NOT NULL. Docs are confusing me a bit lol -
Django Databases - Can you use Postgresql for the Django tables, but have the meat of the data on MSSQL?
I have a scenario where I have full access to CRUD operations on a Database, but cannot create tables, etc., or justify requesting tables to be created. Is it possible to have all the meta tables (auth_*, user_*, django_* tables) hosted local to the app server, and keep the working data in the MSSQL database? I know I could create models to match the MSSQL tables, and copy the data over regularly, but this doesn't seem like a great idea. I'm also aware that there is mixed feelings online about the django-mssql plugin and its abilities. So this adds extra confusion to the problem for me. -
En un modelo DJANGO estoy usando la herramienta FilterView, al momento de visualizar el filtro no me aparece el form clase META
Modelo python donde se define los campos de la tabla from django.db import models # Create your models here. class Integrantes(models.Model): nombre = models.CharField(max_length=50) apellido = models.CharField(max_length=30) codigo = models.CharField(max_length=20) cargo = models.CharField(max_length=20) Filter.py - aqui defino que filtro aplicaré from django.contrib.auth.models import User import django_filters from apps.integrantes.models import Integrantes class integrantesFilter(django_filters.FilterSet): class Meta: model = Integrantes fields = ['nombre'] La vista del Filtro - Uso la herramienta FilterView from django.shortcuts import render, redirect from django.http import HttpResponse, request from django.urls import reverse_lazy from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django_filters.views import FilterView from apps.integrantes.forms import IntegrantesForm from apps.integrantes.models import Integrantes from apps.integrantes.filters import integrantesFilter # Create your views here. class IntegrantesList(ListView): model = Integrantes template_name = 'integrantes/integrantes_list.html' paginate_by = 10 class Integrantes1List(FilterView): model = Integrantes template_name = 'integrantes/integrantes_list.html' filter_class = integrantesFilter paginate_by = 10 Template HTML -> la visualización, sin enmargo, me aparecen todos los campos del modelo INTEGRANTES y solo necesito filtrar por 'nombre' {% extends 'base/base.html' %} {% block title %} ADM RTN {% endblock %} {% block header %} {% endblock %} {% block content %} <form action= "" method="get"> {{ filter.form.as_p }} <input type="submit"/> </form> <table class="table table-bordered"> <thead> <tr> <td>#</td> <td>NOMBRES</td> <td>APELLIDOS</td> <td>CODIGO</td> … -
Is the a way to pass data from an inline formset's clean method to the parent's model admin's clean method in Django?
I have models Product and ProductVariant where on the admin site, the ProductVariant (child) is an inline within the Product (parent). I have overriden the ProductVariant's clean() method to do some validation and creation of stuff like SKU etc. Now I would like to also override the Product's clean() method to do some validations but for one of the validations, I would like to use data (cleaned_data) I have obtained from the ProductVariant's clean() method. So my question is, is there a way that I can pass something I've obtained from the cleaned_data in an inline to the clean() method of the inline's parent. I have added a bit of my code below for reference. It may look a bit more complex than the question I've asked above because I'm using nested inlines and whatnot, but I'm sure the answer will apply in both cases. Thank you in advance. # File: models.py class Product(models.Model): name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', slugify_function=autoslug_slugify, unique=True) option_types = models.ManyToManyField(OptionType, blank=True) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) option_values = models.ManyToManyField(OptionValue, blank=True) # File: admin.py # ==================== # ProductVariant Admin # ==================== class OptionValueInlineFormSet(BaseInlineFormSet): def clean(): # Generate SKU using option_values. Opted for this because … -
Best way to create a Mobile App out of a Django website
What is the best/efficient way of creating a mobile app out of a Django site. I understand that perhaps using React to and connect to a DJANGO API, but assuming I don't know React, can I somehow convert DJANGO site into a Phone Appp? -
How do I get Django form errors from Ajax to appear on the user screen?
Perhaps I'm not thinking clearly...but it would seem to make sense to me that if I am submitting a form via AJAX...the same form that I can submit via the traditional HTML method that I should be able to get the form errors and display them just as I would via a HTML submit? I can certainly get the form.errors in my console if I print them.....but I can't seem to figure out how to get them back to the template so that they render on the user's screen. JSONRESPONSE shows them in a different screen...but how can I just get them back on the form itself? Here is my View... class CreateProcedureView(LoginRequiredMixin,CreateView): model = NewProcedure form_class = CreateProcedureForm template_name = 'create_procedure.html' def form_valid(self, form): instance = form.save() return JsonResponse({'success': True }) def form_invalid(self, form): response = JsonResponse({"error": "there was an error"}) response.status_code = 403 # To announce that the user isn't allowed to publish return response def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Procedures:procedure_main_menu')) else: self.object = None user = request.user form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) files = request.FILES.getlist('file[]') if form.is_valid() and file_form.is_valid(): procedure_instance = form.save(commit=False) procedure_instance.user = user procedure_instance.save() list=[] … -
Context variables on several templates
I have a view, which return context {}. I need to use these context variables not in one template.html, - but in several templates. How can I do this? return render(request, 'cart/cart_detail.html', { 'order':order, 'order_item':order_item, 'total':total} -
Displaying image URL Django
who knows what the problem is and how to fix it, I will try to explain. I have 2 projects, 2 databases: a warehouse and a store, when a new product arrives at the warehouse, the selery performs the task and checks how much product needs to be added to the Store's database, or if it is a new product, then it adds it. problem with pictures. Model Warehouse: class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.ImageField(upload_to='products/%Y/%m/%d') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() here everything is fine, it saves pictures in media / products Model Store: class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.URLField(validators=[URLValidator()]) slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() What is the correct name for a field in the store image? link to task celery: https://dpaste.com/G6HJBSJAY screen from API and Image … -
How should I handle timing with push notifications in my Django app?
I'm working with a Django project and I'm implementing push notifications to the back end. I'm using fcm-django for the job. At the moment I'm wondering how should I take care of checking the notification times (how do I tell the app when it should send the notification)? I'll give an example. I have a test Model: class TestNotificationModel(models.Model): timestamp = models.DateTimeField(auto_now_add=False) title = models.CharField(max_length=100) text = models.TextField() user_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=("User"), blank=True, null=True) So I can save events to the database and now I need some system to send the notification to the user at some certain time, for example one hour before the time value of the field timestamp. I've been thinking using some library to check for example every hour if the user has an upcoming event and if there is an event which is set to happen at 4pm, the app would send the notification at 3pm. Does this sound like a valid way to implement the feature of sending notifications or is there some other way that would be better? I'm at the starting point with this so any help would be appreciated. -
How to add custom input form to django admin for adding dynamic data?
I'm building an eCommerce website with multiple product variants. So how can I modify the Django admin panel, so that I can add new variants and the corresponding image from the same product adding page? Here is my model: class Products(models.Model): title = models.CharField(max_length=200, blank=False, db_index=True) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(Category, default=None) thumbnail = models.ImageField(blank = True, upload_to = 'products/thumbnails') tags = models.CharField(max_length=100, blank=True, null=True) slug = models.TextField(max_length=500 ,blank=True, help_text="Client side only") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Attribute(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Attribute_Value(models.Model): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) value = models.CharField(max_length=100, unique=True) def __str__(self): return self.value class Product_Option(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) options = models.ForeignKey(Attribute, on_delete=models.PROTECT) class Product_Combinations(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) combination = models.CharField(max_length=100, blank=True, default="") price = models.DecimalField(max_digits = 10, decimal_places=2, default = 0) class Images(models.Model): product = models.ForeignKey(Product_Combinations, on_delete=models.CASCADE) # title = models.CharField(max_length=200, blank=True) image = models.ImageField(blank=True, upload_to='products/images') Example- Attribute: size, color, material, height Attribute value: 3inch, 5inch, red, blue, wood, metal Product 1: Product_Option- size, material Product_Combinations- combination: 3 inch | wood price: 100 combination: 5 inch | wood price: 200 combination: 3 inch | metal price: 150 combination: 5 inch | metal price: … -
How to Add Image from FILE or URL
I'm trying to add Image from FileField or URL CharField (Url) but i've got some issue. 1st > File from URL is uploaded correctly, Name and Image in Models are successfully created but .. Image is not correct (see code below) 2nd > If File is choosen all is perfect ! I get POST value from Name , slugify it and use it to change name of image with extension in both case ... When I choose an url ... Result for image in Models is : halo/.jpg ... I just want to get back value from file just uploaded from url... In other words : If URL field is filled ... I use this URL instead of File, If not I use FileField to upload. Thanks for help VIEWS.PY def createHalo(request): form = HaloForm() if request.method == 'POST': form = HaloForm(request.POST, request.FILES) if form.is_valid(): document = form.save(commit=False) document.name = request.POST['name'] img_url = request.POST['url'] if img_url != "": print(img_url) photo = Halo() # set any other fields, but don't commit to DB (ie. don't save()) filename = urlparse(img_url).path.split('/')[-1] extension = filename.split(".")[-1].lower() name = "halo/" + slugify(request.POST['name']) + "." + extension # content = urllib.request.urlretrieve(img_url) response = requests.get(img_url) if response.status_code == … -
Editing a Model using templates in django
before updating the update.html form I get null constraint Error how do update my note in my app when i try to update Note model i get this error Request URL: http://127.0.0.1:8000/list Django Version: 2.0.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: TakeNotes_note.title In views.py def see(request): if request.user.is_anonymous == False: # lIST OF THE NOTES notes = list(Note.objects.filter(user = str(request.user))) context = {"notes":notes} if request.method == 'POST': # GET THE NOTE REQUESTED note_req = request.POST.get("note_req") if request.POST.get("form_type") == note_req: # CHECK THE DETAILS OF THE NOTED for i in context['notes']: if i.title == note_req: deets = {'note': i} return render(request,'read.html',deets) # Updating the note elif request.POST.get("form_type") == "EDIT": print("Editing", ) for i in context['notes']: if i.title == note_req: deets = {"note":i} if request.method == "POST": # Here is my problem newTitle = request.POST.get("title") newNote = request.POST.get("note") print(newTitle, newNote) i.title = newTitle i.note = newNote i.save() return render(request,"Update.html",deets) #missing Update # Deleting the note elif request.POST.get("form_type") == "DELETE": for i in context['notes']: if i.title == note_req: i.delete() return redirect("/") return render(request,'UserIndex.html',context) else: return redirect("/") in Update.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Update Note || {{ …