Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unresolved Reference in Pycharm Using Django
code I'm using Pycharm. I created a new app called pages that's part of this tutorial on Youtube. I created some functions in the pages/views.py. Then I went to urls.py to import the functions and add the URLs. But the IDE can't find pages. I tried restarting Pycharm/invalidating the caches, and that did not work. Please let me know if you have any ideas. -
Django not running on localhost when using with Docker
I am a beginner to web development with Django. I have been trying to use docker-compose as a part of the lectures but due to some issues, I am not able to run the server. This is my docker-compose.yml file: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=1029384756Vithayathil ports: - "5432:5432" migration: build: . command: python3 manage.py migrate volumes: - .:/usr/src/app depends_on: - db web: build: . command: python3 manage.py runserver volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db - migration This is my DockerFile: FROM python:3 WORKDIR /usr/src/app ADD requirements.txt /usr/src/app RUN pip install -r requirements.txt ADD . /usr/src/app This is my database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PASSWORD':'**********', 'PORT': 5432, } } On doing docker-compose up command, these things happen: Starting airline4_db_1 ... done Starting airline4_migration_1 ... done Starting airline4_web_1 ... done Attaching to airline4_db_1, airline4_migration_1, airline4_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-11-07 15:37:00.770 UTC [1] LOG: starting PostgreSQL 13.0 (Debian 13.0-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2020-11-07 15:37:00.789 UTC [1] LOG: listening … -
How to Solve a FieldError- Cannot resolve keyword 'slug' into field
I'm making a Post and Comment model. I created and Post and Comment model and it looks ok. I can add post and also comment to any particular post. But getting trouble when I'm trying to delete the comment after several attempts I am getting an error from test_func. Here is the views.py class PostCommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/postcomment_confirm_delete.html' # <app>/<model>_<viewtype>.html def test_func(self): comment = self.get_object() <------------- Error showing from here if self.request.user == comment.user: return True return False def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the template: {% for comment in comments %} <ul class="list-unstyled"> <li class="media"> <img class="rounded-circle article-img" src="{{ comment.post.author.profile.image.url }}"> <div class="media-body"> <h5 class="mt-0 mb-1">{{comment.user| capfirst}}<small class="text-muted">- {{ comment.created}}</small> </h5> <hr class="solid mt-0"> {{ comment.content}} </div> </li> </ul> {% if comment.user == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'blog:post-commentu' post.slug %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'blog:post-commentd' post.slug %}">Delete</a> </div> {% endif %} {% endfor %} Here is the url path('blog/<slug:slug>/delete_comment/', PostCommentDeleteView.as_view(), name='post-commentd'), Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') slug = models.SlugField(blank=True, null=True, max_length=120) class Comment(models.Model): … -
How do I go about debugging 'OSError: Failed to write data' on my Flask server?
I'm running a Flask application (with some bits of Django ORM) on Elastic Beanstalk (code link: https://github.com/onnela-lab/beiwe-backend). However, I'm getting constant notifications from Elastic Beanstalk about 5xx failures (~5-25% failures). Looking at the logs (/var/logs/httpd/error_log), I see the following errors: Error 1: [Fri Nov 13 13:58:55.487007 2020] [:error] [pid 14630] [remote {load_balancer_ip_address:port1}] mod_wsgi (pid=14630): Exception occurred processing WSGI script '/opt/python/current/app/wsgi.py'. [Fri Nov 13 13:58:55.487070 2020] [:error] [pid 14630] [remote {load_balancer_ip_address:port1}] OSError: failed to write data Error 2: [Fri Nov 13 13:59:55.486449 2020] [:error] [pid 17765] (70008)Partial results are valid but processing is incomplete: [client {load_balancer_ip_address:port2}] mod_wsgi (pid=17765): Unable to get bucket brigade for request Doing a quick grep -c (result: 5418) for each of these confirms that they're likely related issues, despite no correlation in PIDs and different LB ports. I did some research on Stack Overflow and found the following related questions: Django OSError: failed to write data Apache + mod_wsgi + flask app: "Unable to get bucket brigade for request" error in logs Summary: It's possible that clients with spotty connections are causing this issue due to an interrupted connection or that something is killing the Apache child worker process. Most of the clients calling this API are … -
Serve some static from Django and others from s3
I have a Django app on Heroku and recently moved all my static files to s3. This is working great, except a few static files used in a script that need to be served locally. I'm using the https://github.com/higuma/web-audio-recorder-js to let the visitor leave a voicemail. When the files are on S3, I get this error when leaving a voicemail: gum_error err.name: SecurityError; SecurityError: Failed to construct 'Worker': Script at '[my-s3-bucket]' cannot be accessed from origin '[my-domain]'. From this SO answer, it seems "Chrome doesn't let you load web workers when running scripts from a local file." So I think to solve this, I need to serve most of my static files on S3, but a few of them locally. I'm using django-storages and boto3 for static files, and it seems like it's all-or-nothing. -
How to grab context from Django Generic Views
I'm very new to django and I'm trying to override the get_context method but it's not working for me Views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super(PostCreateView, self).get_context_data(**kwargs) context['content'] = self.content return context models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs = {'pk':self.pk}) -
Using GET parameters with Django and Ionic
I'm developing an application where I need to make HTTP requests, so I'm trying to use the GET method with parameters. My code in ionic is this: getZona(code: string) { return this.http.get( this.API_URL + "zonas", {codigo_acceso: code}, {} ); } My Django code is class ZonaView(viewsets.ModelViewSet): queryset = Zona.objects.all() serializer_class = ZonaSerializer So when I do a GET request, I get all records, even though if the parameter's value doesn't exists in the records. No matter what I write in the parameter, I get all records. I have tried with postman and I get the same behavior. Hope you can help me. -
Can I use an aggregation function on the result of a previous aggregation function in Django?
I've been receiving the following error on a query: Cannot compute Sum('failures'): 'failures' is an aggregate I have a model that represents a payment: class Payment(models.Model): created = models.DateTimeField(null=True) customer_name = models.CharField(max_length=50) status = models.CharField(max_length=20) # e.g. 'paid' or 'failed' When an user makes a purchase and tries to perform payment with her credit card, a Payment object is created. If the attempt fails, the status becomes 'failed'. An user may try several times, generating several Payment objects with the 'failed' status, and then give up, or maybe when she tried with a different card the nth payment was successful. I would like to perform an aggregated query where I can count both the total number of failed attempts and the "unique" fails, that is, counting a single fail for each customer that had a failed attempt. For example, suppose we had the following payment attempts Date/Time Customer Name Status 2020-11-10 8:00a.m Alice failed 2020-11-10 8:01a.m Alice failed 2020-11-10 8:02a.m Alice failed 2020-11-10 8:10a.m Bob failed 2020-11-10 8:11a.m Bob paid 2020-11-11 7:30a.m Charles failed 2020-11-11 7:31a.m Charles failed I would like to obtain the following result using a queryset: Date Total failures unique failures 2020-11-10 4 2 2020-11-11 2 1 … -
Django Rest Framework Serializer Method Calling
I'm new at Django Rest Framework and I wonder how methods create and update are called inside a ModelSerializer Class. What I understand is that create and update methods are automatically triggered when a POST or PUT request is sent. Is there a way to call a new function, like say_hello()? Here's an example. I want to call method say_hello() when I hit a PUT Request class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = User fields = "__all__" def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update an user, setting the password and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user def say_hello(self, validated_data): print(validated_data) return "Hello you" -
Is there a way to add multiple models to a class view (django)?
I'm trying to add two models to a group update view so that when a new group is created the user gets added the the groups userList. This is what I have (the relevant stuff): allgroups\models.py class Allgroups(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) private = models.BooleanField(default=False) discussion = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('allgroups_detail', args=[str(self.id)]) class userlist(models.Model): allgroups = models.ForeignKey( Allgroups, on_delete=models.CASCADE, related_name = 'userList', ) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return str(self.user) allgroups\views.py from .models import Allgroups, userlist, class AllgroupsCreateView(LoginRequiredMixin, CreateView): model = Allgroups template_name = 'allgroups_new.html' fields = ('title', 'body','private',) login_url = 'login' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class userlistUpdateView(CreateView): model = userlist fields = ('user','allgroups',) template_name = 'userlist_update.html' success_url = reverse_lazy('allgroups_list') def test_func(self): obj = self.get_object() return obj.author == self.request.user For the AllgroupsCreateView class I want to be able to use two models: model = Allgroups, userlist so that when the new group is created the author of the new group is added to the userlist Any ideas? Thanks! -
Django - Move url.py dispatcher to project folder
Newbie here ... Django Version:3.1.3 I want to put my urls.py dispatcher inside my project folder and not in the default application one for better visibility. Example: Project Name: Project Default Application Name: Project/Project So I would like to get the following: /urls.py I tried with a modification of /Project/settings but it doesn't work: ROOT_URLCONF = '.urls' My folder tree: . ├── env │ ├── bin │ ├── include │ ├── lib │ ├── lib64 -> lib │ ├── pyvenv.cfg │ └── share └── Project ├── __pycache__ ├── db.sqlite3 ├── manage.py ├── polls ├── Project └── urls.py -
How to make server for mobile app using Python and Django frameworks?
I doing mobile voice assistant and i need server side and client side but i dont know how writing this on Django or on some other framework python. How do you help me? -
Django HttpResponseRedirect versus redirect
Given the following: def add(request): if request.method == "POST": task = request.POST.get('task') form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] request.session['tasks'] += [task] # return HttpResponseRedirect(reverse("tasks:index")) return redirect('tasks:index') else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) what's the difference, why would you use one over the other, between: return HttpResponseRedirect(reverse("tasks:index")) and: return redirect('tasks:index') -
form fields do not get filled in DJANGO
I have this model: class Tarea(models.Model): numtar = models.AutoField(primary_key=True) cliente = models.ForeignKey(User, related_name='user_cliente', null=True, on_delete=models.DO_NOTHING) acargo = models.ForeignKey(User, related_name='user_acargo', null=True, on_delete=models.DO_NOTHING) asignado = models.ForeignKey(User, related_name='user_asignado', null=True, on_delete=models.DO_NOTHING) descorta = models.CharField(max_length=140) deslarga = models.TextField(max_length=8195) estado = models.ForeignKey(Estado, null=True, on_delete=models.SET_NULL) tipo = models.ForeignKey(Tipos, null=True, on_delete=models.SET_NULL) prioridad = models.ForeignKey(Prioridad, null=True, on_delete=models.SET_NULL) creacion = models.DateTimeField(default=timezone.now) revision = models.DateTimeField(auto_now=True) cierre = models.DateTimeField(null=True, blank=True) # objects = models.Manager() # el gestor por defecto de objetos leídos # listado = ReqMgr() # Mi gestor de lecturas class Meta: verbose_name = "Tarea" verbose_name_plural = "Tareas" and this view: @login_required(login_url='/login') def newincid_view(request): form = newincidForm() form.estado = Estado.objects.get(estado='Abierta') form.tipo = Tipos.objects.get(tipo='Incidencia') form.creacion = timezone.now() if request.method == 'POST': form = newincidForm(request.POST) if form.is_valid(): instancia = form.save(commit=False) instancia.save() return redirect('vacia') return render(request, 'incid/newincid.html', {'form': form}) and this form: class newincidForm(ModelForm): class Meta: model = Tarea exclude = ['numtar', 'revision', 'cierre'] def __init__(self, *args, **kwargs): super(newincidForm, self).__init__(*args, **kwargs) self.fields['descorta'].widget.attrs['class'] = 'form-control no-resize' self.fields['deslarga'].widget.attrs['class'] = 'form-control no-resize autogrowth' The form gets rendered and I fill all the fields but I always get and error "field is required" for "estado", "tipo" and "creacion". Of course form.is valid is never True and nothing gets written. Why is it? -
Django 'endfor', expected 'endblock'
I am attempting to learn Django but keep receiving the error " 'endfor', expected 'endblock'. Did you forget to register or load this tag? " when I add the {% for key,value in price.DISPLAY.items %} {{ key }} {% endfor %} part of the code. How can I fix this? Any help would be great thanks. home.html {% extends 'base.html' %} {% block content %} {% for key,value in price.DISPLAY.items %} {{ key }} {% endfor %} <br /> <br /> {{ price.DISPLAY }} <div class="jumbotron"> <h1 class="display-4">Welcome</h1> </div> <div class="container"> <div class="row"> {% for info in api.Data %} <div class="card" style="width: 18rem"> <img src="{{info.imageurl}}" class="card-img-top" alt="{{info.source}}" /> <div class="card-body"> <h5 class="card-title">{{info.title}}</h5> <p class="card-text">{{info.body}}</p> <a href="{{info.url}}" class="btn btn-secondary" target="_blank" >Read more</a > </div> </div> {% endfor %} </div> </div> {{ api.Data }} {% endblock content %} -
Unsuccessfully trying to migrate my app using python manage.py migrate
Unsuccessfully trying to migrate my app using python manage.py migrate then python manage.py makemigration but nothing is showing up in the terminal. python manage.py migrate python manage.py makemigrations Migrations for 'my_app': ^CBrittanys-Air:cragslist_app brittany$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 35, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Brittanys-Air:cragslist_app brittany$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 39, in execute_from_command_line(sys.argv) NameError: name 'execute_from_command_line' is not defined Brittanys-Air:cragslist_app brittany$ python manage.py migrate Brittanys-Air:cragslist_app brittany$ python manage.py makemigrations -
How can I divide the request.POST to fit 2 distinct forms in django?
I would like to know whether it is possible to divide the request.POST attribute in django in order to fill 2 or more distinct forms. Because my Main model operates in a form that it is related to 2 child models with a ManyToManyField(), I want to create more instances of this model using forms. A quick Example: class ChildModelOne(models.Model): title_one = models.CharField(max_length = 64) list = models.ManyToManyField(otherModel, blank = True, default = None) def __str__(self): return self.title_one class ChildModelTwo(models.Model): title_two = models.CharField(max_length = 64) list = models.ManyToManyField(otherModel, blank = True, default = None) def __str__(self): return self.title_two class ParentModel(models.Model): name = models.CharField(max_length = 128, default = 'My Name', null = True, blank = True) p_modelOne = models.ForeignKey(ChildModelOne, on_delete = models.CASCADE,default = None, blank = True, null = True ) p_modelTwo = models.ForeignKey(ChildModelTwo, on_delete = models.CASCADE,default = None, blank = True, null = True ) and now my forms: class Register_ChildModelOne(forms.ModelForm): class Meta: model = ChildModelOne fields = ['title_one', 'list'] class Register_ChildModelTwo(forms.ModelForm): class Meta: model = ChildModelTWo fields = ['title_two', 'list'] class Register_ParentModel(forms.ModelForm): class Meta: model = Routine fields = [ 'name','p_modelOne', 'p_modelTwo'] and in my templates the forms are inherited as follows : context { 'form_One' : Register_ChildModelOne(), 'form_Two' … -
Django redirect within method
I have the following: def wiki(request,title): entries = [] entry = util.get_entry(title) if entry != None: markdowner = Markdown() entry = markdowner.convert(entry) entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": title, "entries": entries, }) def search(request): search=request.GET.get('q') entries = util.list_entries() for entry in entries: if search == entry: ######################################### entries = [] entry = util.get_entry(search) markdowner = Markdown() entry = markdowner.convert(entry) entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": search, "entries": entries, }) ####################################### possible=( [str for str in entries if (search in str )] ) print(possible) return render(request, "encyclopedia/search.html") if search == entry: is there some way to redirect to or call wiki(request,title)? and thereby be able to eliminate the code between the hash marks? -
access to the coupon information in the webbook in stripe
I am using coupon in stripe checkout session. it works fine but I need to store the information once checkout successfully completed in my server. I am thinking of either of the following potential solutions: 1- pass the info to webhook: @csrf_exempt def stripe_webhook(request, **myextrainfo**): 2- somehow find the used coupon info in the webhook event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) I don't know if the first is doable and about the second, I can almost retrieve all the information like customer, product, total, subtotal but I cannot find coupon info. here is information that I can retrieve: session = event['data']['object'] line_items = stripe.checkout.Session.list_line_items(session['id'], limit=1) print(line_items) print(line_items["data"][0]["price"]["id"]) print(line_items["data"][0]["price"]["product"]) print(line_items["data"][0]["price"]["recurring"]["interval"]) print(line_items["data"][0]["price"]["recurring"]["interval_count"]) I appreciate if someone can help me. -
Heroku + Django : Restarting a dyno every 15 min
I have a Django website hosted on Heroku. I need to restart 1 dyno "clock" every 15 minutes. Through Heroku CLI, this can be done through the command line: heroku dyno:restart clock.1 But I can't seem to automate it from within the Django app. I don't know if a Django scheduled job/management command can execute a Heroku CLI command. Currently my back-up solution is to have : one .bat to 1) Activate my venv 2) execute heroku dyno:restart clock.1 one Windows Task Scheduler to launch my .bat every 15 min. (Yes... my laptop has been on for months now) What I want is a cronjob inside my Django app, which would restart this dyno every 10 min. Or anything like that ? -
Docker Flask File not running
Been a while since I used docker and having issues getting my Flask server up and running, the django one in running file. I'm sure I'm doing something wrong related to my directory. Can anyone help me and identify the issue? Failure is: backend_1 | python: can't open file '/backend/manage.py': [Errno 2] No such file or directory frontend_1 | Traceback (most recent call last): frontend_1 | File "frontend/app.py", line 4, in <module> frontend_1 | from frontend.utils import register_request, login_request frontend_1 | ModuleNotFoundError: No module named 'frontend' pycharmprojects_backend_1 exited with code 2 pycharmprojects_frontend_1 exited with code 1 This is my directory structure: ├── backend │ ├── db.sqlite3 │ ├── DjangoRestfulApi │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-39.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── settings.cpython-39.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ ├── urls.cpython-39.pyc │ │ │ ├── wsgi.cpython-36.pyc │ │ │ └── wsgi.cpython-39.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── Dockerfile │ ├── manage.py │ ├── requirements.txt │ └── users │ ├── apps.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ … -
How to update and delete comments in Django
I am struggling with updating and deleting comments created by users, I have created Class Based Views for the comments but I am not sure how to proceed as I am getting errors The error I am currently receiving is: FieldError at /blog/sdsdssds/update_comment/ Cannot resolve keyword 'slug' into field. Choices are: content, created, id, post, post_id, updated, user, user_id Any ideas how to fix this error and what is the reason for it? Here is models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) Here is the views.py class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment fields = ['content'] # What needs to appear in the page for update template_name = 'blog/post_detail.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) def test_func(self): comment = self.get_object() if self.request.user == comment.user: return True return False class PostCommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/postcomment_confirm_delete.html' # <app>/<model>_<viewtype>.html def test_func(self): comment = … -
How can I find the current users primary key to check if it matches a notes pk?
I am working on an application that stores data on different artists, venues, and notes the user can create for shows. I am currently trying to implement a feature to delete an existing note based off it's PK and the users PK associated with that note. I have most the work done but I don't know how they are storing the current logged in users PK to check before deleting. Here is what I have so far and links for reference: https://github.com/claraj/lmn/blob/master/lmn/views/views_notes.py # Note related paths path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:show_pk>/delete', views_notes.delete_note, name='delete_note'), https://github.com/claraj/lmn/blob/master/lmn/urls.py # Delete note for show @login_required def delete_note(request, show_pk): # I need to grab the existing note PK and user PK associated with that note # Then check if the current user matches the PK associated with that note to delete or return a 403 status code. if note.user == request.user: note.delete() return redirect('latest_notes') else: return HttpResponseForbidden https://github.com/claraj/lmn/blob/master/lmn/templates/lmn/notes/note_list.html # Grabs PK for specific note <form action="{% url 'delete_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="delete">Delete</button> </form> -
django.db.utils.ProgrammingError: relation "knox_authtoken" does not exist
I'm getting "django.db.utils.ProgrammingError: relation "knox_authtoken" does not exist" error. Actually I'm writing an API in django using restframework. And I'm getting 500 Internal server error over the line AuthToken.objects.create(user)[1] and my import for the AuthToken is from knox.models import AuthToken And my error logs are: Traceback (most recent call last): File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "knox_authtoken" does not exist LINE 1: INSERT INTO "knox_authtoken" ("digest", "token_key", "salt",... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\auths\views.py", line 43, in post token = AuthToken.objects.create(user)[1] File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\knox\models.py", line 20, in create instance = super(AuthTokenManager, self).create( File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, … -
How to step wise post data to an object using the Django-Rest Framework?
I want to post an object with Django-Rest Framework to my backend. The object contains multiple nested objects, and the user inserts this information setp-wise via a React JS frontend. class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) date_posted = models.DateTimeField(default=timezone.now) place = models.ForeignKey(Place, on_delete=models.PROTECT, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) images = models.FileField(upload_to='audio_stories/',validators=[validate_file_extension_image], blank=False) audio = models.FileField(upload_to='audio_stories/',validators=[validate_file_extension_audio], blank=False) I now wonder how it is possible to send the data to the server step by step. Is there a way to initiate a story object at the very beginning of the creation process to generate its primary key and then add the other data to this key step by step, e.g. images and audio? I've already searched for the right term in the Django documentation, but I'm having difficulties to approach this topic. I am happy for any clarification.