Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble finding page. Django url / views
this is the first time i had to ask something at stackoverflow, i'm both exited and scared, i don't know why. I'm writing a django app that just hosts web posts. The page is divided in three (3) categories (Index, lkmi and chiqung). Each post has a category (lkmi or chiqung). On the INDEX page you can see all the posts. On the LKMI page you can see only the lkmi posts. On the CHIQUNG page you can see only the chiqung posts. All is controlled just by ONE VIEW called "index_page", wich receives an argument called "cat" that is the url from one of the categories (index, lkmi, chiqung). Based on that it dictates wich posts to load. * NOW THE PROBLEM * I can't find why, but i'm only having trouble loading the lkmi section. The index page and the chiqung_page loads perfectly, but i'm having a "Page Not Found (404) Request Method: GET Request URL: http://127.0.0.1:8000/lkmi/ Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ [name='index_page'] post/ [name='post_detallado'] ^ckeditor/ The current path, lkmi/, didn't match any of these. " I'll leave here the models, views and urls. Models class Category(models.Model): name … -
How can I host django web application on cpanel?
I am unable to host django application on cpanel.After doing whole setup I am facing 503 Service Unavailable The server is temporarily busy, try again later! -
A new table for each user created
I am using Django 3.0 and I was wondering how to create a new database table linked to the creation of each user. In a practical sense: I want an app that lets users add certain stuff to a list but each user to have a different list where they can add their stuff. How should I approach this as I can't seem to find the right documentation... Thanks a lot !!! -
Getting an Error whenever installing using pip3 command
I am a newbie on Django framework, I tried to install PostGreSql as database but after running python3 manage.py runserver command, it throws me an error.I have attached the image of the error it shows. Please help me out. Error Shown When Running Server -
How to display django tags in update form (django-taggit)?
I made a basic blog post app in django and I'm using the django-taggit project (https://github.com/jazzband/django-taggit) to create taggable Model objects. However, tags show up as a query set in my update form field: <QuerySet[<Tag:wow]> Here is what my html looks like: <input type="text" name="tags" data-role="tagsinput" class="form-control" id="tags" name="tags" value="{{ post.tags.all }}"> I know there's a way to loop through the tags when displaying them, but is there a way to loop through them within the form? I'm using a single text field to add tags separated by a comma using this tutorial: https://dev.to/coderasha/how-to-add-tags-to-your-models-in-django-django-packages-series-1-3704 I don't have an issue saving tags. My only issue is displaying tags that already exist in an editable field on my update form. thanks! forms.py: from taggit.forms import TagWidget class PostForm(ModelForm): class Meta: model = Post widgets = {'content_text': forms.Textarea(attrs={'cols': 80, 'rows': 80}), 'tags': TagWidget(), } fields = ['title', 'video_URL', 'content_text', 'score', 'tags',] -
method not allowed:POST
my code show errors: method not allowed: POST method not allowed: /home/ while running the server I couldn't find where the error is and whenever I click search in my html form it again reidirects me to http://127.0.0.1:8000/home/ here is my app's view.py class HomePageView(TemplateView): template_name = 'home.html' class ResultPageView(TemplateView): template_name = 'results.html' def search(request): if request.method == 'POST': MYSearch = Searchform(request.POST) if form.is_valid(): return redirect('/thanks/') else: MYSearch = Searchform() return render(request, 'results.html',{"MYSearch":MYSearch}) forms.py class Searchform(forms.Form): source = forms.CharField(max_length=100) destination = forms.CharField(max_length=100) urls.py urlpatterns = [ path('results/', ResultPageView.as_view(), name='results'), path('home/', HomePageView.as_view(), name='search'), ] -
How to input the image file from Django Admin to the html
if we don't use for, we can directly write the image address like '/img/1.jpg', but what if I already use for? what should i write? here is my directory of my images here is my django/admin, which is where my image has been uploaded on django / admin here is my html file {% for product in products %} <section id="card"> <div class="container"> <div class="row"> <div class="col"> <div class="card" style="width: 18rem;"> <img src= '(what should i write here?)' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.Description }}</p> <a href="#" class="btn btn-primary">Contact Us</a> </div> </div> </div> </div> </div> </section> {% endfor %} -
Multiple lookups in a Django view
I have this models.py: class Work(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name = 'creator') class Event(models.Model): repertoire = models.ManyToManyField(Work, blank=True) Now, in my template I'd like to show all the events containing the works which is present in the repertoire field of an event for a specific creator. So: views.py: context['events'] = Event.objects.filter(repertoire__work__creator_id=1) # why is this not possible? The event 'Great event' has in repertoire: song 1, by John song 2, by James song 3, by Jonathan In John, James, and Jonathan's profile page I want to show the Great event details, because they have one of their piece performed in that date. -
The empty path didn't match any of these, cant figure out
urls.py ''' from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from expense.views import expense_upload urlpatterns = [ path('admin/', admin.site.urls), path('upload-csv/', expense_upload, name="expense_upload") ] ''' views.py ''' import csv, io from django.shortcuts import render from django.contrib import messages # Create your views here. #parameter named request def expense_upload(request): #declaring template template = "expense_upload.html" data = Expense.objects.all() #prompt is a context varibale that can have different values depending on their context prompt = { 'order': 'Order of the CSV should be Month, Date, Description, Category, Withdrawal, Deposit, Paid_by, Purpose', 'expenses': data } #Get request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] #lets check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a valid csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Expense.objects.update_or_create( MONTH = column[0], DATE = column[1], DESCRIPTION = column[2], CATEGORY = column[3], WITHDRAWAL = column[4], DEPOSIT = column[5], PAID_BY = column[6], PURPOSE = column[7] ) context = {} return render(request, template, context) ''' templates/expense_upload.html Title {% if messages %} {% for message in messages … -
Django REST API POST pandas dataframe
I've seen several posts about Pandas dataframes and Django, but couldn't relate any to my specific problem. I'm trying to allow a user to manually create a dataframe in Python , and then make a Django API call to upload that dataframe to my Django site. I can get this to work if the user specifies a filepath, but not manual data entry. My current API Python call looks like: def upload_document(user_token, filename, file_path): url = 'https://www.website.com/upload/' + filename + '/' try: response = requests.post( url, files = {'document': open(file_path, 'rb')}, headers = {'Authorization': 'Token'+ ' ' + user_token} ) return(response) except: return('unable to upload document') My URL is url(r'^upload/(?P<filename>.+)/$', DocumentUpload.as_view(), name = "document-upload"), It is uploading to a model, called Document. The API view is class DocumentUpload(APIView): permission_classes = (IsAuthenticated, ) parser_class = (FileUploadParser,) def post(self, request, filename, format = None, ): user = self.request.user filename = self.kwargs['filename'] file_serializer = FileSerializer(data=request.data, context={'request': request}) if file_serializer.is_valid(): try: #file_serializer.uploaded_by = uploaded_by file_serializer.filename = filename file_serializer.save(filename = filename) return Response(file_serializer.data, status=status.HTTP_201_CREATED) except: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializer is class FileSerializer(serializers.ModelSerializer): uploaded_by = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Document fields = ("id", "filename","document", "uploaded_by") I can also post the … -
Can I automate a web scraping task that updates the django database?
I am working on an application that works with data which I have previously scraped from another website using Selenium. In order for my app to always work with the most up-to-date data, I would like to set up a scheduled task that runs maybe twice a day to execute the script responsible for scraping said website. Now I looked into this a little bit and see a lot of mentions of Celery as a scheduling tool. I was wondering whether it would be feasible for Celery to take care of running a Selenium driver. I am planning to deploy this application to heroku and ideally the updating of the database would be fully automated once the application is live. Can anyone confirm that this is feasible and potentially point me to some resources that will get me started? Maybe I am completely off track here and there would be a better way to do this? Thank you -
Strawberry GraphiQl explorer tries to use websockets and falls with 500 error and "Connection reset by peer" (with Django)
I am using Strawberry with Django And there is a path to GraphiQl explorer in urls.py: from strawberry.django.views import GraphQLView urlpatterns = [ ... path('graphql', GraphQLView.as_view(schema=schema)), ] And while there is a browser tab with http://127.0.0.1:8000/graphql it continuously makes requests to ws://127.0.0.1:8000/graphql each 10 seconds, that causes next errors on back each request: Internal Server Error: /api/ Traceback (most recent call last): File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/strawberry/django/views.py", line 50, in dispatch data = json.loads(request.body) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) [02/Jun/2020 00:22:45] "GET /api/ HTTP/1.1" 500 92779 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 57288) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, … -
Django can AJAX field filter be designed with CreateView?
I already ahve a CreateView which handles creating objects. I am wondering if I can simply put an AJAX response in the get method to allow for the form fields to be filtered based on previous selections. e.g. If a user selects an option in the "Category" field called "Food/Beverage" then I send over an AJAX request to GET the queryset which is filtered for that Category, then update the form. Is this how it is accomplished? Is this usually done in the get_queryset method or another method? Is this normally done in a separate view? Should I be using a generic View which is sparate from the CreateView for this? -
What is the use of SlugField in django?
Note: Please dont consider it as duplicate post, all the existing posts are not giving clear understanding of SlugField. My question is "we can sluggify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?" For example, in my model, I have a field called url = models.CharField(max_length=30) def save(self, ...): self.url = slugify(self.url) ....... Won't the url be saved in slugified format in database? I can use this slugified value in browser right, then what is the use of creating models.SlugFIeld(max_length=30)? What advantage SlugField will add over slugified CharField? -
Accessing foreign keys from the Django template
This is my models.py: class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) class Event(models.Model): title = models.CharField(max_length=50) view.py: def events_list_view(request): events = dateEvent.objects.all() context = { 'dateEvents': dateEvents, } return render(request, 'events/events_list.html', context) template: {% for event in dateEvents %} <tr> <td>{{ dateEvent.start_date_time }}</td> <td><a href="{% url 'event-detail' id=? %}">{{ dateEvent }}</a></td> # I want the event id here <td>{{ dateEvent.venue_event }}</td> {% endfor %} How can I get the Event id which is linked to that dateEvent in my template? Using dateEvent.event_set doesn't seem to work. -
Django - getting "'File' object has no attribute 'read'" error when saving image from url and connecting to ImageField
Basically, my goal is to save an image (for example, this one) to an ImageField. After reading this post, my code currently looks like this: from future import division from django.db import models from django.urls import reverse from io import BytesIO import os import mimetypes from PIL import Image as PilImage import urllib.request from upload.utils import ext_to_format from requests import get from django.core.files.temp import NamedTemporaryFile class File(models.Model): url = models.URLField(null=True, blank=True) image = models.ImageField(null=True, blank=True) def save(self): if self.url and not self.image: img_temp = NamedTemporaryFile() img_temp.write(urllib.request.urlopen(self.url).read()) img_temp.flush() self.image.save("image_%s" % self.pk, File(img_temp)) # error arises self.save() When I run the code, error yields saying: AttributeError: 'File' object has no attribute 'read' The full traceback is: Traceback (most recent call last): File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 172, in post return super().post(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid self.object = form.save() File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\forms\models.py", line 458, … -
Combine parent-childs into one queryset
I have the following model: class Task(models.Model): name = models.CharField(max_length=200, default='New task') start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) task_status = models.IntegerField(default=0) parent = models.ForeignKey( 'self', related_name='childs', null=True, blank=True, on_delete=models.SET_NULL) My app exposes an API endpoint, which return all parent tasks in a data range and all parent tasks with status 0, and all their childs. The filter needs to be applied for parents only, since childs may have different start date and statuses. I need to return all results in a single list. Currently I'm doing it this way: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all().order_by('id') serializer_class = TaskSerializer @action(detail=False, methods=['post']) def get_tasks(self, request): daterange = request.data.get('daterange') items = list() parents = Task.objects.prefetch_related("childs") .filter(start_date__range=daterange, parent__isnull=True) | Task.objects.prefetch_related("childs") .filter(task_status=0, parent__isnull=True) for parent in parents: items.append(parent) items = items + list(parent.childs.all()) serializer = self.get_serializer(items, many=True) return Response(serializer.data) I was wondering, is it possible to obtain the final result (all parents and childs in one list) using only django queryset methods? If not, is there a more efficient way of doing this (given that the number of tasks may be very large)? Thanks! -
NoReverseMatch at /event/vent_detail/3/myguest/
New to Django and can't figure this out, I'm using a header to view event details such as myguest list and keep getting this error, please help :) NoReverseMatch at /event/vent_detail/3/myguest/ Reverse for 'vent_detail_myguest' with arguments '('',)' not found. 1 pattern(s) tried: ['event/vent_detail/(?P\d+)/myguest/$'] (views.py) def vent_detail_myguests(request,pk): current_vent = Vent.objects.get(pk=pk) user_vent = current_vent.myguest myguests = user_vent.users.all() return render(request, 'event/vent_detail_myguest.html', {'myguests': myguests}) (urls.py) re_path(r'^vent_detail/(?P<pk>\d+)/myguest/$', vent_detail_myguests, name='vent_detail_myguest'), (header_template.html) <a class="gaelvents" href="{% url 'event:vent_detail_myguest' vent.pk %}">MyGuests</a> (vent_detail_myguest.html) {% for object in myguests %} <div class="single-guest-container"> <a class="username" href="{% url 'guest:profile_view' pk=object.pk %}">{{object.username}}</a> <a class="profilepic" href=""><img class="profilepic" src="{% static 'guest/images/logo.png' %}"></a> <a class="remove" href="{% url 'guest:connect_guest' adding='remove' pk=object.pk %}">Remove<a/> </div> {% endfor %} (models.py) class Vent(models.Model): event = models.CharField(max_length=15, blank=False, unique=True) date = models.CharField(max_length=15, blank=True) city = models.CharField(max_length=15, blank=True) venue = models.CharField(max_length=15, blank=True) website = models.CharField(max_length=15, blank=True) info = models.CharField(max_length=300, blank=True) myguest = models.ForeignKey(MyGuest, on_delete=models.CASCADE) def __str__(self): return self.event class Meta: ordering = ['event'] -
Django: python manage.py runserver SyntaxError
I had the server running fine before but now whenever I put "python manage.py runserver" in to terminal it produces the below error. Python and Django are both installed in the correct locations. I'm using Python 3.6 and I'm on Windows 10. C:\Users\liam\code\python\django_project>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in … -
Problem while showing active selection on Wagtail navbar
I am trying to highlight the active selection on a navbar in Wagtail. It works if the navbar does not call a new page <li class="nav-item"> <a class="nav-link active" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> But if the link points to a new page, <li class="nav-item"> <a class="nav-link active" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> the highlight shows until the new page is loaded and then disappears. My complete code is: base.html {% load static wagtailuserbar %} <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <title> </title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {# Global stylesheets #} <link rel="stylesheet" type="text/css" href="{% static 'css/wagtail_nav.css' %}"> {% block extra_css %} <link rel="stylesheet" href="https://bootswatch.com/4/lumen/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/my.css' %}"> {% endblock %} </head> <body class="{% block body_class %}{% endblock %}"> <div class="container"> <br> <nav class="container-fluid navbar navbar-expand-sm bg-dark navbar-dark" style="padding-left: 75px; margin-top: -16px;"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> </ul> </nav> </div> {% block content %}{% endblock %} {% block extra_js %} <script type="text/javascript" src="{% static 'js/my.js' %}"></script> {% endblock %} </body> </html> my.css .navbar-dark .nav-item .nav-link.active { color:white; background-color: green; } my.js $('.navbar-nav … -
After deploying Django, I am having trouble adding the column and redeploying it
I deployed a Django project using elasticbeanstalk, but after adding columns to the USER table, there was a problem while redeploying. Folder location : .ebextensions/02-django.config Previous container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_createsu: command: "django-admin createsu" 03_collectstatic: command: "django-admin collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "config/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings I used this time container_commands: 01_makemigrations: command: "django-admin.py makemigrations" 02_migrate: command: "django-admin.py migrate" 03_createsu: command: "django-admin createsu" 04_collectstatic: command: "django-admin collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "config/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings However, an error occurred. I think the migration does not seem to work. Is the command wrong??? error django.db.utils.ProgrammingError: column users_user.hint_question does not exist LINE 1: ...sers_user"."gender", "users_user"."login_method", "users_use... ^ I am in the USER model Added hint_question and hint. Any help would be greatly appreciated!! Thank You:) -
django : django.db.utils.OperationalError: no such table:
I'd like to make a category field. so I make a class category in same model.py file.(Im trying to make default value in category like : IT,Marketing,Design, etc...) but there is an error when I'm trying to make migrate: django.db.utils.OperationalError: no such table: preassociations_category How can I solve it? Do i have to make another app? models.py class Category(models.Model): name = models.CharField(max_length=300) class Preassociation(core_models.TimeStampedModel): category = models.ManyToManyField( Category, related_name="category", blank=True ) -
how to make django dynamic URL works properly with django form
This is my form <form action="{%url 'topicname' %}" method="GET"> <input type="search" placeholder="Search topics" name="searchtopic"> <button type="submit">Search</button> </form> This is my View def searchtopic(request): if request.method == 'GET': mysearchtopic = request.GET['searchtopic'] mydata = myhashtaglist.objects.filter(slug = mysearchtopic) context = { 'mydata':mydata, } return render(request, 'hzone/result.html',context) This is my result.html page {% for m in mydata %} <a href="{% url 'topicname' m.slug %}">{{ m.relatedhashtag }}</a> {% endfor %} This is mu urls.py urlpatterns = [ path('', views.apphome, name = 'homepage'), path('topic/', views.searchtopic, name = 'topicname'), ] what i want is whenever user click on any of the topic on result page this topic should open. reult page should look like intro to django django tutorial 1 django tutorial 2 django tutorial 3 but when i am clicking on any of the topic its not taking me to that topic. -
DRF create object with nested serializers and foreign keys
I am using DRF and I'm trying to create an object which has several foreign keys as well as related objects that will need creating in the process. Here's what a reduced version of my models looks like: class Race(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='races') type = models.ForeignKey(Type, on_delete=models.SET_NULL, related_name='races', null=True) region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name=_('region'), related_name='races') country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='races') timezone = models.ForeignKey(Timezone, on_delete=models.SET_NULL, null=True) class Event(models.Model): name = models.CharField(max_length=200) race = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='events') And then here's my Race serializer: class RaceSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) type = TypeSerializer(read_only=True) events = EventSerializer(many=True) country = CountrySerializer() region = RegionSerializer(read_only=True) timezone = TimezoneSerializer(read_only=True) def create(self, validated_data): with transaction.atomic(): events = validated_data.pop('events', None) race = Race(**validated_data) race.save() for event in events: Event.objects.create(race=race, **event) return race And my view: class AddRaceView(CreateAPIView): serializer_class = RaceSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(owner=self.request.user) And here's some test data I'm sending with my POST request: { "name": "ABC Marathon", "country": { "pk": 1, "name": "United States" }, "region": { "pk": 1, "code": "ME" }, "timezone": { "pk": 1, "code": "EST" }, "events": [ { "name": "Marathon" }, { "name": "Half Marathon" } ] } So the problem I'm having is passing valid … -
display a table showing model instances as rows and let users select instances (rows) to delete
In my app, users can upload files. These files are represented by a model with attributes for associated meta-data (upload time, file name, user created note, max value, etc). A user will upload several files and I want to show them a table of their uploaded files with a checkbox next to each row that can be used to delete selected files and associated model instances. I'm not sure what the right approach is, I've looked at the following options but there doesn't seem to be an obvious solution: 1. model forms, using CheckboxSelectMultiple 2. django_tables2 3. reuse the django admin model form-view-template The default django admin app behavior is perfect for my use case, but I'm not sure what the best way is to reproduce it? app/models.py import uuid from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Document(models.Model): def rename_file(self, filename): ext = filename.split('.')[-1] new_name = uuid.uuid4().hex return f'documents/{new_name}.{ext}' owner = models.ForeignKey( User, on_delete=models.CASCADE, editable=True, ) document = models.FileField(upload_to=rename_file) notes = models.CharField(max_length=258, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) nice_name = models.CharField(max_length=128, null=True, blank=False) start_date = models.DateField(null=True, blank=False) end_date = models.DateField(null=True, blank=False) def __str__(self): return str(self.document) app/admin.py from django.contrib import admin from .models import Document def uuid(obj): return …