Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker-compose and django secret key
I have build my postgres and django appplication using the following version: "3.8" services: django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db db: image: postgres container_name: pgdb environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres When I check the docker-desktop, I got 2 docker containers, "django" and "pgdb". When I check the django, it says django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Originally, on my windows 10 machine, I saved the secret key in the windows variable. What is the way to build the docker-compose so it has the secret get? SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') -
Django Postgres not adding / dropping constraints not working for partitions
I am creating a unique together constraint on set of four columns. I am seeing after creating those constrains, the table is still accepting the duplicates. Later I found that the partitions of that table also needs the constraints to be applied. Before doing that, I deleted all duplicate records. Now when I tried the same again, it is not working. Only the root table is getting the unique constraints and not the partitions. I am trying all these through Django migrations. If I run the SQL query to alter table directly in postgres on individual partitions, in that case it is working. Please advise what I am missing here. -
Modifying foreign key queryset in Django create CBV
I have 2 groups of 5 employees. In each group, one of the employees is that group's supervisor. In the create view, once the supervisor field is populated, I would like the employee foreign key field to show only those employees belonging to that supervisor. It would be nice to have the appropriate employees displayed based on the user (supervisor) without the supervisor field having to be populated first. I have tried model forms to try to appropriately modify the employee foreign key field query set, obviously to no avail. Please help! The code is as follows: class Instruction(models.Model): supervisor = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="supervisorinstructions" ) employee = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="employeeinstructions" ) instruction = models.CharField(max_length=300) def __str__(self): return f"{self.instruction}" def get_absolute_url(self): return reverse("myapp:instructiondetail", kwargs={"pk": self.pk}) class InstructionCreate(CreateView): model = models.Instruction fields = [ "supervisor", "employee", "instruction", ] template_name = "myapp/instruction_create_form.html" -
How can I copy a FieldFile to a different model?
I have referenced this SO.. Django - how to create a file and save it to a model's FileField? But I can't quite make out what I'm supposed to do. I am trying to populate a model with initial data and I am getting a FIELDFILE...I strip all of the other attributes and I am just getting the FIELDFILE name. I am trying to save it to a model using inlineformsets...but it won't save. I tried to override my SAVE method in my form...as shown below just as an experiment... def save(self, update_author, *args, commit=True, **kwargs): f = open('/path/to/file') self.attachments.save(book, File(f)) But it does nothing. Thanks in advance for any pointers. -
Django Fetching Submit Orders
I am dealing with Django this project where I need to create an ordering system, where there would be possible to create an order as a company (so there would be billing information of the company) and based on how many employees the company would select to take part in the course, they would fill up forms about the employees. So f.e. i need to fetch the data like this - One order: Company Ltd. (information about the company) - Will Smith (information about the employee) Company Ltd. (information about the company) - Jennifer Proudence (information about the employee) Company Ltd. (information about the company) - Stein Code (information about the employee) Company Ltd. (information about the company) - Michael Louve (information about the employee) and also: Company Ltd. (information about the company) - Will Smith (information about the employee), Jennifer Proudence (information about the employee), Stein Code (information about the employee), Michael Louve (information about the employee) -
Django and Tensorflow serving in Docker Compose
I can successfully run my django using the following # pull the official base image FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update RUN apt-get install ffmpeg libsm6 libxext6 -y RUN pip install --upgrade pip COPY requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY .. /usr/src/app EXPOSE 8000 WORKDIR /usr/src/app/flyingChicken CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And I can successfully the TensorFlow serving using docker run -p 8501:8501 --name tfserving_classifier --mount type=bind,source=algorithms\SSIM\,target=/models/flyingChicken-e MODEL_NAME=flyingChicken-t tensorflow/serving I would like to deploy both remotely on an Azure server. How can I trigger the tensorflow serving docker from the django docker? -
Django local memory cache is re-fetching each time
I am using Django's local memory cache in development and I can't get it to work. I have set the following in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } I see the views are being called everytime a page is loaded. I only have one Django server process running in dev -
Django test fails with "No User matches the given query."
I wrote Django app and now I'm trying to cover it with automated tests. For testing get_queryset function within my ListView I created a test user and his post, but my test fails with "No User matches the given query". When I execute py manage.py runserver everything is fine, no exceptions are raised and the page's displayed properly. I'm new to Django testing so I absolutely have no idea what's going on. Could you help me please? This is my view from view.py class UserPostListView(ListView): """Displaying a page with a certain user's posts""" model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): """Dynamic filtering to get posts by a chosen user""" queryset = super().get_queryset() user = get_object_or_404(User, username=self.kwargs.get('username')) return queryset.filter(author=user).order_by('-date_posted') Test for that view: class TestUserPostListView(TestCase): """Test UserPostListView""" def setUp(self): """Creating a test user and his post to see if the certain user's page with posts is displayed properly""" self.factory = RequestFactory() self.user = User.objects.create_user( username='test_user', email='testuser@example.com', password='fhhewo87539275' ) self.post = Post.objects.create( title='test_post', content='blabla', author=self.user ) def test_get_queryset(self): """Testing get_queryset function""" url = reverse('user-posts', kwargs={'username': self.user.username}) request = self.factory.get(url) view = UserPostListView() view.setup(request) queryset = view.get_queryset() self.assertIn(self.post, queryset) Traceback: Traceback (most recent call last): File … -
Update a choice field when an event occurs in Django
I want a CharField to automatically be updated into one of the choices it has when user clicks on a certain button. So I defined the model like this: models.py: class Oficio(models.Model): class Estatus(models.TextChoices): NUEVO = 'NU', _('Nuevo') NO_REVISADO = 'NR', _('No Revisado') LEIDO = 'L', _('Leido') SEGUIMIENTO = 'S', _('Seguimiento') COMPLETADO = 'C', _('Completado') folio = models.CharField(primary_key=True, max_length=10, unique=True, null=False) usuario = ForeignKey('users.Usuarios', on_delete=models.PROTECT) fecha = models.DateTimeField(auto_now_add=True) asunto = models.TextField(null=False) estatus = models.CharField(max_length=2, choices=Estatus.choices, default=Estatus.NUEVO) documento = models.FileField(upload_to='static/pdf') dependencia = models.ForeignKey('Dependencia', on_delete=models.CASCADE, related_name='dependencia_origen') turnado = models.ForeignKey('Dependencia', on_delete=models.CASCADE, related_name='dependencia_destino') def __str__(self): return self.folio When creating a new object of this model, the estatus field default value is Nuevo. In my template this object is displayed like this: And I want to update that Nuevo tag in blue into another one (one of the choices defined in models.py) when user clicks the button next to it which downloads the documento field file. template.html for this button: <form method="POST" action="{% url 'oficios:status' oficio.folio %}"> {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg" title="Descargar"> <a href="{{oficio.documento.url}}" download> <i class="fas fa-file-download"></i> </a> </button> </form> So far I tried creating a function in views.py like this: def change_status(request, pk): oficio = Oficio.objects.get(folio=pk) form_status = forms.UpdateStatus(instance=oficio) … -
pytest-django not found by pytest
I am trying to switch my Django tests from manage.py test to using pytest. I installed the last versions of both pytest and pytest-django (NOT django-pytest), but I get a PytestConfigWarning: Unknown config option: DJANGO_SETTINGS_MODULE when trying to run my tests, and nothing Django-related works. Reproductible example: Install packages: pip install django -U, pip install pytest -U, pip install pytest-django -U Add a pytest.ini file, with the following content: [pytest] DJANGO_SETTINGS_MODULE = test_settings Run py.test --traceconfig. This should print the PytestConfigWarning. Note that there is no reference to pytest-django in the plugins. Full log: PLUGIN registered: <_pytest.config.PytestPluginManager object at 0x10a800280> PLUGIN registered: <_pytest.config.Config object at 0x10a73bc70> PLUGIN registered: <module '_pytest.mark' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/mark/__init__.py'> PLUGIN registered: <module '_pytest.main' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/main.py'> PLUGIN registered: <module '_pytest.runner' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/runner.py'> PLUGIN registered: <module '_pytest.fixtures' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/fixtures.py'> PLUGIN registered: <module '_pytest.helpconfig' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/helpconfig.py'> PLUGIN registered: <module '_pytest.python' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/python.py'> PLUGIN registered: <module '_pytest.terminal' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/terminal.py'> PLUGIN registered: <module '_pytest.debugging' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/debugging.py'> PLUGIN registered: <module '_pytest.unittest' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/unittest.py'> PLUGIN registered: <module '_pytest.capture' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/capture.py'> PLUGIN registered: <module '_pytest.skipping' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/skipping.py'> PLUGIN registered: <module '_pytest.tmpdir' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/tmpdir.py'> PLUGIN registered: <module '_pytest.monkeypatch' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/monkeypatch.py'> PLUGIN registered: <module '_pytest.recwarn' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/recwarn.py'> PLUGIN registered: <module '_pytest.pastebin' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/_pytest/pastebin.py'> PLUGIN registered: <module '_pytest.nose' … -
how could i solve broken this pipe problem?
Quit the server with CTRL-BREAK. [29/Sep/2021 22:19:36] "GET / HTTP/1.1" 200 37607 [29/Sep/2021 22:19:43,135] - Broken pipe from ('127.0.0.1', 56390) [29/Sep/2021 22:19:45,208] - Broken pipe from ('127.0.0.1', 56396) [29/Sep/2021 22:19:45,219] - Broken pipe from ('127.0.0.1', 56411) -
How do add +1 to the PositiveIntegerField model field when adding each new Post?
I have a Posts model. And field Order = models.PositiveIntegerField() has been created for arbitrary sorting. class Post(models.Model): title = models.CharField(max_length=15) create = models.DateTimeField(auto_now_add=True) Order = models.PositiveIntegerField() Objective: in the model, overriding the save method, do add the index +1 (from the last available index of Posts) to this field when adding each new Post. That is, each post must have an Order-index, and if there are already 3 posts on the site, then when the fourth is added - index 4 is added to his the field, and so on. "1" index in Order field (1st post), "2" index in Order field (2nd post) etc 3, 4, 5... similar ID. Help implement this logic im method save. It seems simple, but I don't know how to approach it. I understand that in the model and what I do: def save(self, *args, **kwargs): qs = self.order.objects.all() last_item = qs.latest(self.order) last_item.order += 1 super().save(*args, **kwargs) But this don't work. Help me, please! -
why django post method doesn't work this case?
html file <form action="/input" method="post"> {% csrf_token %} <input type="text" name="data" /> <input type="submit" value="post" /> </form> view.py def a(request): x=request.POST['data'] html='<h1> {} </h2>'.format(x) return HttpResponse(html) it shows Server Error (500) and when i change line 3 in view.py to "html='html=' {} '.format(request.method)" it shows "GET". i want to use "post" but it doesn't work -
I want to build a private chat application
I am trying to build a private chat application using django channels. I created the a chat application by following django channels docs. But I need a system like that- If a logged in user select another user they can chat each other in a private chat room. Here is the code I tried. I am completely new in django channels. So the codes are from the docs Here is my views from django.shortcuts import render # Create your views here. def get_home_page_url(request, *args, **kwargs): args = {} return render(request, 'chat/index.html', args) def get_room_url(request, room_name, *args, **kwargs): return render(request, 'chat/room.html', { 'room_name': room_name }) Here is routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] Here is my models.py class PrivateChatRoom(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user1") user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user2") is_active = models.BooleanField(default=True) class RoomChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(PrivateChatRoom, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(unique=False, blank=True) I am trying to implement this models to realtime chat but i dont know what logic should i use. I have no experience in django channels and sockets. ** Need Urgent Help ** -
Just like we have TypeScript for JavaScript, whey do we not have some super set language for Python to introduce type safety?
I felt that type-safety is very important for the development of applications. The absence of type safety is one of the major sources of bugs. So just like Typescript introduces type safety to javascript, why do we not have some like that for python -
Django filter and pagination doesn't display
i created 2 query list, in the first list i created, the filter and pagination is displayed successfully, but when there is no item in the second datatable i created, it appears successfully, but when I add a item to table, it disappears. my models.py; class nagioslar(models.Model): nekip = models.TextField(max_length=100, null=True) nalarmseviyesi = models.TextField(max_length=100,null=True) nr1 = models.TextField(max_length=100, null=True) nr2 = models.TextField(max_length=100, null=True) nr3 = models.TextField(max_length=100, null=True) nkonu = models.TextField(max_length=100, null=True) netki = models.TextField(max_length=100, null=True) ndetaylar = models.TextField(max_length=100, null=True) niletisim = models.TextField(max_length=100, null=True) views.py; def nagios(request): nmembers_list = nagioslar.objects.all() paginator = Paginator(nmembers_list, 1000000000000000) page = request.GET.get('page', 1) try: nmembers = paginator.page(page) except PageNotAnInteger: nmembers = paginator.page(1) except EmptyPage: nmembers = paginator.page(paginator.num_pages) return render(request, 'nagios.html', {'nmembers': nmembers}) html; <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> Nagios Alarmlar <a class="btn btn-sm btn-success" href="{% url 'ncreate' %}" style="padding: 8px; float: right; background-color: green; color: white;">EKLE</a> </div> <div class="card-body"> <div class="table-responsive "> <table class="table table-striped table-bordered text-center dataTable no-footer align-center align-middle " id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Ekip</th> <th>Alarm Seviyesi</th> <th>R1</th> <th>R2</th> <th>R3</th> <th>Konu</th> <th>Etki</th> <th>Detaylar</th> <th>İletişim</th> </tr> </thead> <tbody> {% for nmember in nmembers %} <tr> <td>{{ nmember.nekip }}</td> <td>{{ nmember.nalarmseviyesi }}</td> <td>{{ nmember.nr1 }}</td> <td>{{ nmember.nr2 }}</td> <td>{{ nmember.nr3 }}</td> <td>{{ nmember.nkonu … -
How to get current user id in Django Rest Framework serializer
I have a serializer that gets product date from a table and the inventory data from another table for the user that is logged in. I have set up the serializer to get the product data and added fields which should hold the user's inventory amount. The request returns the correct data structure, however it was returning the inventory amount for all users and then failing. So I have tried to filter these added fields by the current users id, however when adding it it fails. I would like to filter the added fields for the user's inventory by the user id for the user that is logged in. However adding it seems to break the request. class CardsDataSerializers(serializers.ModelSerializer): inventory = serializers.SerializerMethodField() class Meta: model = magic_set_cards fields = ['id', 'name', 'rarity', 'manaCostList', 'convertedManaCost', 'colors', 'number', 'type', 'types', 'imageUri', 'promoTypes', 'hasFoil', 'hasNonFoil', 'inventory'] @staticmethod def get_inventory(self, obj): user_id = self.request.user.id try: standard = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('standard').get()[0] except inventory_cards.DoesNotExist: standard = 0 try: foil = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('foil').get()[0] except inventory_cards.DoesNotExist: foil = 0 inventory = { 'standard': standard, 'foil': foil, } return inventory Error: get_inventory() missing 1 required positional argument: 'request' Request Method: GET Request URL: http://127.0.0.1:8000/magic/sets/ss1/cards-data/?name= Django Version: 3.2.7 Exception Type: TypeError Exception Value: … -
ImportError: cannot import name 'Index' from 'landing.views'
So I was following a tutorial on Youtube, and here is the link: https://www.youtube.com/watch?v=Rpi0Ne1nMdk and I got to 12:46 when he got to importing Index. I hit run, but I received a Syntax Error instead. Here is a sample of my code: from django.urls import path from landing.views import Index urlpatterns = [ path('', Index.as_view(), name='index'), ] when I hit run, this returned: ImportError: cannot import name 'Index' from 'landing.views' (/home/runner/red-chilli-media/landing/views.py) If it looks weird, it's because I'm using replit. I used the django project, and the language is Python/HTML. if any information is missing, please tell me. The error is in Python, as you can clearly see. -
Django ModelForm with Access to More than One Model
So, i want to know if it possible to have a django modelform access more than 1 django model... i currently have 2 models relating to the product and they are shown below...the reason i made 2 models is to allow each product to have multiple images class Product(models.Model): title = models.CharField(max_length=255) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) thumbnail = models.ImageField(upload_to='uploaded_products/', blank=True, null=True) description = models.TextField(max_length=255, null=True, blank=True) categories = models.ManyToManyField(Category,related_name='products', blank=True, help_text="Select One or More Categories that the product falls into, hold down ctrl to select mutiple categories") tags = models.ManyToManyField(Tag, blank=True) stock = models.PositiveIntegerField(default=1, blank=True) notes = models.TextField(null=True, blank=True) ownership = models.FileField(blank=True, null=True, upload_to='product_files', help_text='Optional : provide valid document/picture to proof ownership (presence of this document increases the reputation of your product).Note: Provided Document if invalid or incorrect can be invalidated after upload') verified = models.BooleanField(default=False, blank=True, null=True) uploader = models.ForeignKey(Account, on_delete=models.CASCADE, blank=True) serial_number = models.CharField(max_length=255, blank=True, null=True) class Meta: ordering = ['-updated'] def __str__(self): return self.title class Product_Image(models.Model): name = models.CharField(max_length=255, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='uploaded_products/') default = models.BooleanField(default=False, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.name: self.name = self.product.title super().save(*args, **kwargs) Now i want to be able to access … -
Django admin url decoding
I have a Django admin panel with simple products view. Each product has it's own ID like "bus", "avia", "bus_24" and "avia_26". Url to products page look like this: /products/<product_id>/. For products with ids like "bus" and "avia" it works just fine. But for "bus_24" and "avia_26" I get HttpRedirect to main page with messages: Product with ID "avia&" doesn’t exist. Perhaps it was deleted? Product with ID "bus$" doesn’t exist. Perhaps it was deleted? I guees there is smth with decoding/encoding url, so "_24" = $ and "_26" = &. I tried to override get_object method of admin.ModelAdmin to decode object_id but it didn't worked out. Maybe someone had same problem? -
How to create a function to pass ajax data when a button is clicked
I want the ajax data to be passed to the add_teacher function in views.py when the "Add Teacher" button is clicked. path('student/add_teacher/', views.add_teacher, name='add_teacher'), If only the code below is executed, the value is output to the console. $(function () { $checkbox = $('.Checked'); $checkbox.click(checkArray); function checkArray(){ var chkArray = []; chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); } ); But when I add a button click condition, the function doesn't work. $(function () { $('button.addteacher').on('click',function () { $checkbox = $('.Checked'); $checkbox.click(checkArray); function checkArray(){ var chkArray = []; chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); $.ajax({ url: "/student/add_teacher/", type: "post", data: {'chkArray' : chkArray}, headers: { "X-CSRFToken": "{{ csrf_token }}" }, }); } }); }); The html file looks like this: <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th>Select</th> </tr> </thead> <tbody> {% for student in students %} <tr class="student"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox" class="Checked" id="{{ student.id }}"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Add Teacher</button> -
Django object creation from form with nested elements - not behaving as expected
I am using Django 3.2 I am trying to create an object that has child elements, (without using formsets). I have used Javascipt to build a user friendly UI that allows a user to dynamically add the child elements. The post method of the route handler class parses the POST fields and extracts the child elements. This is a simplified version of my codebase: /path/to/myapp/models.py class Question(models.Model): title = models.CharField(max_length=64) start_date = models.DateTime() end_date = models.DateTime() class Choice(models.Model): title = models.CharField(max_length=64) pos = models.PositiveSmallInteger(default=0) question = models.ForeignKey(Question, on_delete=models.CACSCADE, related_name='choices') /path/to/myapp/forms.py class QuestionForm(forms.ModelForm): def clean(self): cleaned_data = super().clean() start_date = cleaned_data['start_date'] end_date = cleaned_data['end_date'] if end_date <= start_date: self.add_error('end_date', ValidationError(_('End date must be greater than the start date'), code=_('invalid_date'))) class Meta: model = Question /path/to/myapp/views.py class QuestionCreateView(CreateView): model = Question form_class = QuestionForm def post(self, request, *args, **kwargs): post_data = request.POST question_choice_data = [x.split('-') for x in post_data.get('question_choices','').split(',')] # <- object is sometimes created on this line! form = self.form_class(post_data) if form.is_valid(): new_question = form.save(commit=False) # set some field attributes # ... new_question.save() for position, choice_name in question_choice_data: Choice.objects.create(question=new_question, title=choice_name, pos=int(position)) When I attempt to save a new question by POSTing, two unexpected things happen: The post() method appears to be … -
Django - How to call Detailview as alternative to UpdateView based on user auth and pk
I need to have user2 (with no authorization) to see a DetailView instead of the UpdateView (that user1 can see) as alternative view in a shared ListView, by calling the appropriate page with object PK(title). Anyone knows what's the best practice to accomplish this or where/what should I look for to reach my objective? Thanks in advance! Details: I can't figure how to do this and call the Detailview correctly. I already created both UpdateView and DetailView and all it is apparently needed but I have to call them both from object pk and doesn't work. HTML {% extends 'base/mybase2.html' %} {% load static %} {% block content %} <h1> List</h1> <a class="btn btn-outline-info " href="{% url 'home' %}">Back to homepage</a> <a class="btn btn-sm btn-outline-primary" href="{% url 'a_add' %}">Add</a> <hr> {{ myFilter.form }} <hr> <ul> <table class="table table-hover table-light table-striped"> <thead> <tr><th scope="col">#Title</th>...</tr> </thead> <tbody> <tr> <caption>Total number of selected objects: {{ page_obj.paginator.count }}</caption> {% for object in object_list %} {% if perms.varmodel.change_atitle %} <th scope="row"><a href="{{ object.get_absolute_url }}">{{ varmodel.a_number }}</a></th> {% else %} <th scope="row"><a href=#>{{ varmodel.a_description }}</a></th> {% endif %} <td> {{ ... }} </td> URLS from django.urls import path from varapp.views import AListView from varapp.views import ACreateView, … -
Possible authorization/authentication for html?
Is it possible do do something like this for the author in HTML? (I want the Author to see the delete and cancel buttons but other users just get the 3 links.) post.html {% if user.is_authenticated and user == post.author %} <!-- Edit Buttons --> <div class="text-center form-group"> <a class="button-delete" type="button" href="{% url 'post_confirm_delete' post.id %}">Delete</a> <a class="button-cancel" type="button" href="{% url 'post' %}">Cancel</a> </div> <br> {% else %} <!-- Action Buttons --> <div class="row my-2"> <div class="col g-2 justify-content-evenly text-center"> <a class="card-link" type="submit" href="#">Save</a> <a class="card-link" type="submit" href="#">Applied</a> <a class="card-link" type="submit" href="#">Hide</a> </div> </div> {% endif %} This is some of the code for view. view.p class PostListView(ListView): model = post template_name = 'posts/post.html' context_object_name = 'posts' ordering = ['-created'] class PostDetailView(DetailView): model = post class PostCreateView(CreateView): model = Post form_class = PostForm template_name = 'posts/create_post.html' def form_valid(self, form): form.instance.author = self.request.user.gig return super().form_valid(form) class PostDeleteView(DeleteView): model = Post success_url = 'posts/my_post.html' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False -
cs50w commerce project : IntegrityError UNIQUE constraint failed
I'm working on cs50w's commerce project, trying to create a new listing, but I keep getting this error: IntegrityError at /new UNIQUE constraint failed: auctions_listings.user_id Here are my models for user and listing: class User(AbstractUser): pass #def __str__(self): #return f"{self.username}" class Listings(models.Model): title = models.CharField(max_length=30) desc = models.TextField() #starting_bid = models.FloatField(validators = [MinValueValidator(1)]) img = models.URLField(blank=True) category = models.CharField(blank=True,max_length=20) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner", primary_key=True) This is my view for new listing: def new(request): if request.method == "POST": if not request.user.is_authenticated: return render(request, "auctions/new_listing.html", { "message": "Try logging in first" }) user = request.user ###################################################### for u in User.objects.all(): print(f" UID = = {u.pk} | Name = = {u}") ###################################################### title = request.POST["title"] img = request.POST["image"] category = request.POST["category"] #starting_bid = request.POST["starting_bid"] description = request.POST["description"] listing = Listings.objects.create( user = user, title = title, img = img, category = category, #starting_bid = starting_bid, desc = description ) if listing is not None: listing.save() return redirect("index") return render(request, "auctions/new_listing.html") And the form for creating a new listing: <form action="{% url 'new' %}" method="post" class="form-horizontal" style="width: 50%; margin: auto;"> {% csrf_token %} <div class="form-group"> <label for="title">Title: </label> <input type="text" name="title" id="title" class="form-control" autofocus required> </div> <div class="form-group"> <label for="image">Image URL: </label> <input …