Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get access to different models in the template?
I have 3 models Do I need to change connections in the models, and make the key field not an id, but a name? class Category(models.Model): name = models.CharField(max_length=150, unique=True) description = models.CharField(max_length=250) class Company(models.Model): name = models.CharField(max_length=150, unique=True) country = models.CharField(max_length=50) class Motobike(models.Model): name = models.CharField(max_length=150) company = models.ForeignKey('Company', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) And tests: def test_category(setup): client = Client() category_id = Category.objects.get(name='Мотоциклы').id response = client.get(f'/categories/{category_id}/') assert response.status_code == 200 response_data = json.loads(response.content.decode('utf-8')) assert len(response_data) == 2 assert response_data[1]['name'] == 'Ninja Turbo' assert response_data[1]['vendor'] == 'Kawasaki' assert response_data[1]['category'] == 'Мотоциклы' assert response_data[1]['description'] == '' response = client.get(f'/categories/25/') assert response.status_code == 404 in view i do so: class CategoryView(DetailView): model = Category template_name = 'bikes_site/categories_detail.html' def get_context_data(self, id, **kwargs): context = get_object_or_404(self.model, id) context['motobikes'] = Motobike.objects.filter(category_id=id).all() return context I get an error: get_context_data() missing 1 required positional argument: 'id' -
psycopg2 cannot connect to docker image
I've started my docker image as follows: docker run --name fnf-postgis -e POSTGRES_DB=fnf -e POSTGRES_USER=fnfuser -e POSTGRES_PASSWORD=fnf2pwd -p5432:5432 -d mdillon/postgis:11 and i've set up my django db config: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'fnf', 'USER': 'fnfuser', 'PASSWORD': 'fnf2pwd', 'host': '', 'port': 5432, However, running makemigrations give this error: psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? but I can successfully connect to the container from pycharm -
Create user related info model
I want to create web site like coursera.org. So I need to create two usertypes like student and teacher. what is the best way to do that? I have tried to create manually usertypes and predefine user types in models.py. But usertype does not show up in admin page. what ia am doing wrong? from django.db import models from django.contrib.auth.models import User # Create your models here. class Usertype(models.Model): user = models.ForeignKey(User,related_name = 'Usertype') usertype = ('Student','Teacher') -
HTML icon didn't load correctly when deploying Django to Google Cloud
I have some trouble when deploying Django to Google Cloud. Currently, I'm using Django2.2. The HTML icon didn't load correctly when I open it from my laptop. But when open it using my mobile browser, it will show the icon perfectly. Already try to clear cache and cookies but still doesn't work, not sure why. The images and CSS in static/ directory can be loaded, but only the HTML icon that can't be load correctly. I've followed this documentation itself. And I think it's kinda funny cause I've tried to deploy using DEBUG = True and change the STATIC_URL = '/static/' but everything works perfectly. But, as it says from Django documentation, that we need to change the DEBUG to False when in productions. Here are my settings.py looks like: DEBUG = False ALLOWED_HOSTS = ['*'] ... MEDIA_ROOT = 'media/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static/') STATIC_URL = 'https://storage.googleapis.com/djangoblogdb/static/' # STATIC_ROOT = '/static/' # STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/static/' ] Here are some of the screenshot: Desktop View Mobile View -
django- page not found error for unknown reason
though everything seems ok, but it shows error. here's 'urls.py' file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), path('products/', include('products.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 'products/urls.py' file: from django.urls import path from . import views urlpatterns = [ path('<int:product_id>', views.product, name= 'product'), path('add', views.add_product, name = 'add_product'), ] in 'views.py' file: def add_product(request): context = { 'categories': categories, } if request.user.is_superuser: return render(request, 'products/add.html', context) else: return redirect('product') -
Deployment a django application
I would like to receive advice on the architecture that I must use to deploy my application django Here are the features of my application: it is an application that connects teachers and students. Teachers create virtual classes and exchange files (pdf, video, audio) with students a forum for asking questions and finding answers a file storage space for users you can see the demo on youtube https://www.youtube.com/watch? v=GTuMJg_PnPc&t=63s Please help me I do not know anything about the deployment,the application works well locally for the real time I used django channels -
Read data from a csv file and then delete the file after every 1 hour in django
I have a admin.csv file, which gets generated after every 1 hour. I want to read the last line of that csv file and store the data in my app's model in the django website. After the value is stored, I want to delete the file as well, and if nothing gets stored after 1 hour and no file is read and no data is saved, then the website should show an error. Kindly help me. I have absolutely no idea on how to do this. I think that celery will help me here, but I dont know how to do it. My models.py file: class Admin(models.Model): Input_IP = models.GenericIPAddressField(protocol='both', unpack_ipv4=False) Skip_Frames = models.PositiveIntegerField() Save_Video = models.BooleanField() Id_Display = models.BooleanField() def __str__(self): return "{},{},{},{}".format(self.Input_IP, self.Skip_Frames, self.Save_Video, self.Id_Display) My tasks.py file in my app folder: @task(name="kay") def oks(): with open('\\home\\aakash\\hi.csv') as r: reader = csv.reader(r) for row in reader: _, created = Admin.objects.get_or_create(Input_IP=row[0],Skip_Frames=row[1],Save_Video=row[2],Id_Display=row[3]) Also, I have a celery.py file in my project folder: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hughes.settings') app = Celery('proj') # Using a string here means the worker don't have to … -
How to redirect with a get parameter in django view?
I want to redirect with a GET parameter in django view. I want to use GET parameter for some reasons, not url parameter. def product_new(request): group = request.GET.get('group') if group == None: product = Product.objects.create() return redirect('cms:product_list_edit') else: product = Product.objects.create(group=group) rreturn redirect('cms:product_list_edit') # I want to redirect this url with GET parameter. -
Troubleshooting guide for internal employees
I am working on the help desk of a call center and i want to create a troubleshooting guide for care agents in order to help them resolving a part of the issues that don't need our intervention. So what i want to do is create two interface one for care agent to follow the guide and another one for an editor to add and delete and update guide paths, knowing that all the paths and eventual solutions will be stored in a database. As i have developed recently a reports application using Django , i searched a lot trying to find some tutorials about creating a similar app using Django and python but i didn't found anything helpful. I have checked also many websites providing similar application, but i am not interested. So my question is : 1 - Which is the best and easy language to develop this application. 2 - Is there any tutorial online that can help me achieving this goal. Many thanks in advance. -
Use Model.save() on Adding Many-to-Many Relationships?
I am trying to create custom Django migration files to prepopulate my database during development. The problem is, that I populate some model values on the Model.save() method. See models.py: class Model2(models.Model): name = models.CharField('kitchen name', max_length=150, blank=False, unique=True) related_users = models.ManyToManyField(User, related_name='kitchens', blank=True) secret_code = models.CharField('kitchen code', max_length=9, blank=True, unique=True) def save(self, *args, **kwargs): if not self.secret_code: self.secret_code = self.generate_random_code() super(Kitchen, self).save(*args, **kwargs) def generate_random_code(self, chars=string.ascii_uppercase + string.digits): """ creates a string out of 6 random characters """ code_digit_num = 9 return ''.join(random.choice(chars) for _ in range(code_digit_num)) In my migration file, however, I am trying to add some users to the related_users field, which returns an error. django.db.utils.IntegrityError: duplicate key value violates unique constraint "customer_exemple_secret_code_key" DETAIL: Key (secret_code)=() already exists. The function to add the data looks like this: def add_example_data(apps, shema_editor): Model1 = apps.get_model("customer", "Model1") Model2 = apps.get_model("customer", "Model2") User = apps.get_model("user", "User") for example_dict in DATA: k = Model1.objects.create( name=example_dict["name"],) related_customer=Customer.objects.get(name=example_dict["related_customer"]) ) if example_dict["related_user"] and isinstance(example_dict["related_user"], list): for related_user_instance in example_dict["related_user"]: u = User.objects.get(email=related_user_instance) k.related_users.add(u) elif example_dict["related_user"] and not isinstance(example_dict["related_user"], list): k.related_users.add(example_dict["related_user"]) I think the problem is, that the .add method uses the .bulk_create method, which will not call .save() on the model and therefore creates some … -
Django: how to render data on users dashboard
I am new to Django. I am working on a project where admin can assign a team to manager and that team should be viewed on that manager's dashboard. But i don't know how can i do this. here is my .html page where admin can see the name of all the managers <div class="body table-responsive"> <table class="table table-hover"> <thead> <tr> <th>S No.</th> <th>COMPANY NAME</th> <th>TEAM MEMBER</th> <th>EMAIL</th> <th>ASSIGN TEAM</th> </tr> </thead> <tbody> {%for team in object%} <tr> <form id="form_id" method="POST" action = "{% url 'accept' %}"> {% csrf_token %} <th scope="row"> {{ forloop.counter }}</th> <td>{{team.company_name}}</td> <td>{{team.team_member}}</td> <td>{{team.email}}</td> <td> <select name="manager_{{manager.id}}"> {% for manager in managers %} <option value ="{{manager.id}}">{{manager.name}}</option> {% endfor %} </select> </td> </tr> {% endfor %} </tbody> </table> and here is my views.py from where admin can see the managers name and all the info def accept(request): obj= Create_Team.objects.filter(status='Accept') managers = manager.objects.all() if request.method == 'POST': acc = manager() manager_id = int(request.POST.get('manager', 1)) acc.manager = manager.objects.get(pk=manager_id) return render(request, "admin/accept.html", {"object": obj, "managers": managers}) here is my views.py from where managers page is rendering def supervisor(request): return render(request, 'manager/index-3.html') here is my model.py file for manager class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) class Meta: … -
Not able to generate cookie for csrftoken when calling login API from Angular 5 client
My backend is using Django/DRF for API writing. and my frontend is using Angular 5 for UI side. I am trying to implement an authentication mechanism using csrf token. When I try to call the API from postman, csrf cookie is getting generated. see my debugger output below: (Pdb) request.COOKIES {'csrftoken': 'KceUKnl9XmNSkoTJS1HbiDoS9Gm5jJ7buvmYQp4rTkzzgTMkprjcmeqR9zUi0azB'} (Pdb) When I am calling the same API from Angular 5 side, csrf cookie is not getting generated. see below-mentioned debugger output: (Pdb) request.COOKIES {} (Pdb) I am really confused the API is same but the behaviour is different when calling from ANgular side. My Angular code : In Imports imports: [ HttpClientModule, HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken', } ), ], Interceptor code: @Injectable() export class HttpXsrfInterceptor implements HttpInterceptor { constructor(private tokenExtractor: HttpXsrfTokenExtractor) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const headerName = 'X-CSRFToken'; let token = this.tokenExtractor.getToken() as string; if (token !== null && !req.headers.has(headerName)) { req = req.clone({ headers: req.headers.set(headerName, token), withCredentials: true }); } return next.handle(req); } } Providers code: providers: [ AuthService, DatePipe, SidebarService, AuthGuard, { provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true } ] Can anyone help me to get through this problem? I can provide more information if neede. -
how to design the serializer in django rest framework for the Json response?
Hi am new to django rest framework.Currently am working on a thing which is contains a json response like this : { "students": [ { "first_name": <str: student first name>, "last_name": <str: student last name>, "unique_id": <str: student unique id>, "current_teachers": [ { "first_name": <str: teacher first name>, "last_name": <str: teacher last name> }, ... ] }, ...more... ] } This is my serializer: class StudentFilterSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ("first_name", "last_name", "unique_id",) class StudentFilterTeacherSerializer(serializers.ModelSerializer): first_name = serializers.CharField(source='teacher.first_name') last_name = serializers.CharField(source='teacher.last_name') class Meta: model = TeacherClass fields = ("teacher","first_name","last_name") class FilterStudentsSerializer(serializers.Serializer): students = StudentFilterSerializer(many=True) current_teachers = StudentFilterTeacherSerializer(many=True, required=False) Now how to edit my serializer to achieve the json response. Cause this is my current json structure: serializer = FilterStudentsSerializer() serializer.data {'students': [], 'current_teachers': []} -
Getting output that results from ajax error
I've got an ajax view that works fine locally, but on my live, production server, I believe that there is an error within the view. When developing locally, this error will automatically print to my console (command prompt), and I can evaluation the problem. In production, I'm not sure how to capture this error. Django doesn't throw a hard error on ajax problems, so I'm not sure that logging will work. For problems with views that are dedicated to ajax posts, I normally rely on that error message that pops up in my console (command prompt). Is there a way that I can capture this error that is happening my my production environment on my view that is dedicated to an ajax POST request? Thanks! -
Getting error "missing grant type" while generating token
When im trying to generate token then im getting missing grant type error . Even if I'm passing grant type in payload @csrf_exempt @api_view(['POST']) def merchanttokengeneration(request): payload = request.data token = request.META.get('HTTP_TOKEN') headers = {"token": token, "Content-Type":"application/json"} print(headers) response = requests.request("POST",'https://staging/merchant/v1/oauth/token', data=json.dumps(payload),headers=headers, auth=HTTPBasicAuth(payload.get('username'), payload.get('password') )) print(response) return HttpResponse(response) -
Django: How to show data to specific users
I am new to Django. I am working on a project where admin will assign a team to manager. when ever admin click on the name of that manager then that team will be assigned to that manager and should be viewed on that manager's dashboard. here is my .html file where admin can see the names of the manager <div class="body table-responsive"> <table class="table table-hover"> <thead> <tr> <th>S No.</th> <th>COMPANY NAME</th> <th>TEAM MEMBER</th> <th>EMAIL</th> <th>ASSIGN TEAM</th> </tr> </thead> <tbody> {%for team in object%} <tr> <form id="form_id" method="POST" action = "{% url 'accept' %}"> {% csrf_token %} <th scope="row"> {{ forloop.counter }}</th> <td>{{team.company_name}}</td> <td>{{team.team_member}}</td> <td>{{team.email}}</td> <td> <select name="manager"> {% for manager in managers %} <option value ="{{manager.id}}">{{manager.name}}</option> {% endfor %} </select> </td> </tr> {% endfor %} </tbody> </table> here is my views.py through which admin can see the names of the manager def accept(request): obj= Create_Team.objects.filter(status='Accept') managers = manager.objects.all() if request.method == 'POST': acc = manager() manager_id = int(request.POST.get('manager', 1)) acc.manager = manager.objects.get(pk=manager_id) return render(request, "admin/accept.html", {"object": obj, "managers": managers}) and here is my views.py for manager that is simply rendering an .html page def supervisor(request): return render(request, 'manager/index-3.html') I want that when ever admin click on the manager then … -
How to fix higher memory utilisation in EC2 instance, is it due to multiple running of processes of gunicorn.sock?
My Django instance is running on EC2 on top of ubuntu 16.04.2 LTS. I'm getting very slow response from my apis, and during debugging i found out almost all of the memory is utilised. Here is the screenshot for your reference: ubuntu@ip-xxx-31-22-205:~/Django/user$ free -m total used free shared buff/cache available Mem: 990 860 69 10 60 14 Swap: 0 0 0 Top command doesn't said much about the memory utilisation. Here is the output of ps -aux command ubuntu@ip-xxx-31-22-205:~/django/user$ ps aux --sort=-%mem | awk 'NR<=10{print $0}' USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 8102 0.1 5.8 311428 59216 ? Sl 05:28 0:03 /home/ubuntu/django/user/venv/bin/python3 /home/ubuntu/django/viago/venv/bin/gunicorn config.wsgi:application -w 3 --bind=unix:/home/ubuntu/django/viago/gunicorn.sock --preload --log-level=debug --log-file=/home/ubuntu/django/viago/gunicorn.log root 8108 0.0 5.7 239012 58356 ? S 05:31 0:01 /home/ubuntu/django/viago/venv/bin/python3 /home/ubuntu/django/viago/venv/bin/gunicorn config.wsgi:application -w 3 --bind=unix:/home/ubuntu/django/viago/gunicorn.sock --preload --log-level=debug --log-file=/home/ubuntu/django/viago/gunicorn.log root 7254 0.0 5.7 239728 58200 ? S May03 0:01 /home/ubuntu/django/viago/venv/bin/python3 /home/ubuntu/django/viago/venv/bin/gunicorn config.wsgi:application -w 3 --bind=unix:/home/ubuntu/django/viago/gunicorn.sock --preload --log-level=debug --log-file=/home/ubuntu/django/viago/gunicorn.log root 5590 0.0 5.6 239440 57632 ? S May02 0:03 /home/ubuntu/django/viago/venv/bin/python3 /home/ubuntu/django/viago/venv/bin/gunicorn config.wsgi:application -w 3 --bind=unix:/home/ubuntu/django/viago/gunicorn.sock --preload --log-level=debug --log-file=/home/ubuntu/django/viago/gunicorn.log root 6929 0.0 5.6 251536 57340 ? Sl May03 0:02 /home/ubuntu/django/viago/venv/bin/python3 /home/ubuntu/django/viago/venv/bin/gunicorn config.wsgi:application -w 3 --bind=unix:/home/ubuntu/django/viago/gunicorn.sock --preload --log-level=debug --log-file=/home/ubuntu/django/viago/gunicorn.log root 2039 0.0 5.5 179196 56324 ? S … -
How to solve UndefinedColumn error in Django
I am new to Django and trying to set up a couple of models, but have run into an error I can't seem to find a fix for. This is the error that I am getting: psycopg2.errors.UndefinedColumn: column carts_cartitem.cart_id does not exist LINE 1: SELECT "carts_cartitem"."id", "carts_cartitem"."cart_id", "c... This is my views file: from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse from products.models import Product from .models import Cart, CartItem def view(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {'cart': cart} else: empty_message = 'Your cart is empty!' context = {'empty': True, 'empty_message': empty_message} template = 'cart/view.html' return render(request, template, context) def update_cart(request, slug): try: the_id = request.session['cart_id'] except: #create a cart new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) if created: print('created') new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() #count products cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) These are my models: from django.db import models class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99) sale_price … -
Foreign Keys with Models - Django Tutorial
I'm learning about Django Web Development with Python and I get stuck in Foreign Keys with Models . This is full code that i'm used to familiarize with foreign keys https://pythonprogramming.net/foreign-keys-django-tutorial/ i tried copying the same code as the tutorial, but when i run "python manage.py migrate" still got the error as shown below. Look forward to the help of everyone!!!`enter code C:\Users\DUYTRA\Duytra>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0003_auto_20190503_2235...Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python\lib\site-packages\django\core\management\base.py", line 323, in run_ from_argv self.execute(*args, **cmd_options) File "C:\Python\lib\site-packages\django\core\management\base.py", line 364, in exec ute output = self.handle(*args, **options) File "C:\Python\lib\site-packages\django\core\management\base.py", line 83, in wrapp ed res = handle_func(*args, **kwargs) File "C:\Python\lib\site-packages\django\core\management\commands\migrate.py", line 234, in handle fake_initial=fake_initial, File "C:\Python\lib\site-packages\django\db\migrations\executor.py", line 117, in mi grate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial =fake_initial) File "C:\Python\lib\site-packages\django\db\migrations\executor.py", line 147, in _m igrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initia l) File "C:\Python\lib\site-packages\django\db\migrations\executor.py", line 247, in ap ply_migration migration_recorded = True File "C:\Python\lib\site-packages\django\db\backends\sqlite3\schema.py", line 34, in exit self.connection.check_constraints() File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 318, in … -
Modal content refresh and submit
I have a use case where my modal loads some content from my DB. Now the same modal has a submit button to push additional text to the db. As of now, my implementation: 1. Modal gets opened 2. Content gets displayed 3. The submit task does not close the modal ( manual submission through Jquery and prevent modal to close) Now i need a way to refresh the updated modal content in this script without closing the Modal. I have tried location.reload(), it seems to refresh the entire page and then i need to open the modal again. Is there any solution? JQUERY: $('#chatbox').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) var recipient = button.data('whatever') $.ajax({ url: "{% url 'fetcher' %}", type: "GET", data: { 'search': recipient }, dataType: 'json', success: function (data) { list = data.list; var id = data.id; $('#chatbox').find('.modal-body').text(list); $( "form" ).submit(function( event ) { var formData = $('#formid').serialize() $.post("/usercreation/addmessage/"+ id, formData, function (response) { console.log('report sent'); $("#formid .input").html(""); location.reload(); }) event.preventDefault(); }); } }); var modal = $(this) modal.find('.modal-title').text('Chat with ' + recipient) }) -
Edit and Export template.xlsx saved in static | DJango
I have a template excel file in static/files/template.xlxs. I need to open the file, append the file and the export as response. │ └── views.cpython-36.pyc ├── static │ ├── css │ │ └── homepage.css │ ├── files │ │ └── template.xlsx │ └── images │ ├── logo.jpg │ └── logo.png ├── templates How do I open the static xlxs file for editing and how do I export the edited file? -
How to handle multiple clients using django channels?
I'm building a real time iot Django server. My server should connect with multiple iot devices at the same time. I know that through a django channel I can serve a client. Is it possible for a django channel to handle multiple clients at once?If not do I need to create multiple websockets in order to handle multiple clients at the same time? -
How to get values from ModelForm
How to show captured data in ModelForm, "quantity" in this example, how to show it in template and how to get it in database class OrderItem(models.Model): PRODUCT_QUANTITY_CHOICES = ( (1, 1), (2, 2), (3, 3), (4, 4) ) quantity = models.IntegerField(default=2, choices=PRODUCT_QUANTITY_CHOICES) order_no = models.IntegerField(primary_key=True, ) product = models.OneToOneField(Product, on_delete=SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True, ) is_ordered = models.BooleanField(default=False) def __str__(self): return '{} - {}'.format(self.product, self.quantity) class Meta: ordering = ('product',) # This defines how we can order products class CartAddProductForm(forms.ModelForm): class Meta: model = OrderItem fields = ['quantity'] -
Duplicate key value violates unique constraint Django
I came up with this problem, when I was creating my app. So whenever I add first comment the problem doesn't appear, but when I try do it second time I get this error: duplicate key value violates unique constraint "tripplanner_discussion_author_id_key" DETAIL: Key (author_id)=(1) already exists. I've tried to put unique=False to models.py, but it didn't help at all. models.py class Discussion(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE, unique=False) group = models.ForeignKey(Trip, on_delete=models.CASCADE, unique=False) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) views.py class DiscussionView(LoginRequiredMixin, CreateView): model = Discussion template_name = 'tripplanner/discussion.html' fields = ['text'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user form.instance.group = self.trip return super(DiscussionView, self).form_valid(form) UPDATE When I logged to another user, the problem disappeared for one post, then it reoccured. So the problem to solve is to make this author_id unique. -
uploading a whole folder containing text documents using django
I want to upload a whole folder using django 2.2.1. Right now I am able to upload one file at a time but I want to expand the uploading functionality by uploading a whole folder at a time and to list every file inside the folder on the webpage.