Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Must be owner of table A", but A doesnt exist
I`m trying to run database migrations, but getting the following error: psycopg2.ProgrammingError: must be owner of table request_settings This is from my .env file: ... DB_USER=idaproject DB_NAME=wellton DB_PASSWORD=password DB_HOST=127.0.0.1 DB_PORT=5432 ... So, I assume, this table should be inside "wellton" database. The user "idaproject" is the owner of "wellton" database and has all priveleges and rights on the database. Then I tried to change owner of request_settings table with ALTER TABLE request_settings OWNER TO idaproject; But seems like it doesn't exist ERROR: relation "request_settings" does not exist Am I missing something? -
Can I create one Superuser and use it in multiple Django Projects?
In order to reduce short-term memory load, is it possible to use one superuser account in the Django admin for multiple projects? -
Django Channels "took too long to shut down and was killed"
I am using Django Channels for a real-time progress bar. With the help of this progressbar the client gets actual feedback of a simulation. This simulation can take longer than 5 minutes depending on the data size. Now to the problem. The client can start the simulation successfully, but during this time no other page can be loaded. Furthermore I get the following error message: Application instance <Task pending coro=<StaticFilesWrapper.__call__() running at /.../python3.7/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/futures.py:348, <TaskWakeupMethWrapper object at 0x123aa88e8>()]>> for connection <WebRequest at 0x123ab7e10 method=GET uri=/2/ clientproto=HTTP/1.1> took too long to shut down and was killed. Only after the simulation is finished, further pages can be loaded. There are already articles on this topic, but they do not contain any working solutions for me. Like for example in the following link: https://github.com/django/channels/issues/1119 A suggestion here is to downgrade the Channels version. However, I encounter other errors and it must also work with the newer versions. requirments.txt: Django==3.1.2 channels==3.0.3 channels-redis==3.3.1 asgiref==3.2.10 daphne==3.0.2 I am grateful for any hint or tip. Best regards, Dennis -
change function based to generic list view in django
How do i write this view into generic list view in django @login_required def accept_tickets_view(request,pk): ticket = get_object_or_404(Ticket,id=pk) if ticket.status == 'Opened': ticket.status = 'Accepted' ticket.accepted_date = datetime.datetime.now() ticket.accepted_by = request.user ticket.save() return redirect(reverse('open_tickets')) -
how to do reverse query set based on forgen key set in django
its a bit complicated, here are the 2 models that am performing the query on : class Line(models.Model): # Relationships end_station = models.ForeignKey("stations.station", related_name='line_end_station', on_delete=models.CASCADE) starting_station = models.ForeignKey("stations.station", related_name='line_start_Station', on_delete=models.CASCADE) class InLineStation(models.Model): # Relationships line = models.ForeignKey("lines.Line", on_delete=models.CASCADE) in_line_station = models.ForeignKey("stations.station", on_delete=models.CASCADE) am getting a station object in the request and I need to filter the line model based on it , if it's a starting , ending, or in line station.. here is how I tried this : @api_view(['POST', ]) def do_search_logic(request): if request.method == 'POST': from_station_id = request.data['from_station_id'] to_station_id = request.data['to_station_id'] from_station_object = station.objects.get(id=from_station_id) to_station_object = station.objects.get(id=to_station_id) Line.objects.filter(Q(starting_station=from_station_object) | Q(end_station=to_station_object) | Q(from_station_object in inlinestations_set)) #this_is_the_tricky_line any help about this ?? -
Django : Why does logging in with superuser email allauth redirect to different page?
I have a django app in which I have a google allauth sign up/login . If I log in with the same email I entered in the superuser creation , it redirects me to : Otherwise : Why? -
Django - set many to many through with differing defaults
Assuming the data model as in Django docs: class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) In the docs the beatles group is set the following way: beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)}) In my case I got a tuple with differing through values: ( { "person": "john", "date_joined": datetime(2002,1,1), "person": "ringo", "date_joined": datetime(...), ... } ) How do I set this many-to-many with differing defaults? I could do something like group.members.clear() for m in member_to_set: Membership.objects.create(person = m.person, date_joined = m.date_joined) But this would invoke a lot of database operations. On the other hand I would not like to reimplement the whole logic of finding out, which memberships to remove -
Django, DRF: How to get related posts with Tag(m2m)
Currently, we are able to get the following related articles by Tag. In the following method, scores are calculated in the order of the number of tags contained in the object. If more related objects of the object with the highest score are retrieved, only articles with more tags will be retrieved and articles with fewer tags will not be retrieved. Is there any other way? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # views.py class RelatedListView(generics.ListAPIView): serializer_class = VideoSerializer def get_queryset(self): video_pk = self.kwargs["pk"] tags = Video.objects.get(pk=video_pk).tags.all() return ( Video.objects.annotate(score=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tags) .order_by("-score") ) -
How to cast parameter values based on their annotations in python functions?
Consider having a task worker, which executes tasks from a task queue. I am trying to built a web interface in django to trigger those tasks manually. So far, for some built-in data-types I go about something simple like this: # tasks.py @app.task def add(a: int, b: int) -> int: return a+b # views.py TYPE_TO_FIELD_MAPPING = { str: forms.CharField, int: forms.IntegerField, float: forms.FloatField, datetime: forms.DateTimeField, # ... } class TaskTriggerView(View): def get(self, request): tasks = {} for task in app.tasks: tasks[task.name] = self.make_task_parameter_form(task)() return render(request, 'template.html', context={'tasks': tasks} def make_task_parameter_form(self, task): # every task has a signature parameter which # is a inspect.Signature object. task_signature: inspect.Signature = task.signature # Initialize a django form with fields made out of # task's function signature, where the form field # is based on it's annotation if annotation is in # `TYPE_TO_FIELD_MAPPING` else forms.CharField. # initial value comes from parameter's default value # if it is not parameter.empty. parameter_form = type( 'ParameterForm', (forms.Form,), {param_name: TYPE_TO_FIELD_MAPPING.get(param.annotation, str)( initial=None if param.default is param.empty else param.default ) for param_name, param in signature.parameters.items()}) return parameter_form def post(self, request): task_name = request.POST.get('task_name') task = app.get_task_by_name(task_name) form_class = self.make_task_parameter_form(task) form = form_class(request.POST) if form.is_valid() # this sends the task to … -
How do I format django url so that AJAX call will get database data that is not dependent on the current page, but from a form value?
I have a page that details a post and comments on that post. The pk for this page is the post pk. I want to be able to construct comments using symbols only. I have a series of symbols saved to the database that are all associated with a category class. I have a form on my page that can select one of those categories, but how do I get an AJAX call to load all the symbols in that category? The user will need to be able to chop and change between categories so I wanted to do this with AJAX rather than reload the page each time. So far, all I get are 404 not founds. I want to do this so that I can drag or select symbols to add to comments. I've tried lots of different formats to get the urls to work (both in urls.py and in main.js) so I can't list off all the alternatives that I've tried as it's all a bit overwhelming. I've also read through a heap of questions on here and other sites but nothing seems to match what I am trying to do. Any help would be appreciated. Symbols … -
Django search bar implementation with multiple field filtering
I am trying to implement the functionality of a search bar. my models.py: class Question(models.Model): questionId = models.IntegerField(primary_key=True) groupId = models.IntegerField(default=0) questionTitle = models.TextField() groupName = models.CharField(max_length=500, null=True, blank=True) correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses") My database is huge, so I tried to skip Question.objects.all() to save time. my views.py: def questionList(request) # Searching Any Value if request.method == "POST" and request.POST['searchKey'] != '': searchKey = request.POST['searchKey'] questions = Question.objects.filter(questionId=searchKey) return render(request,'diagnosis/questionList.html', {'questions': questions}) This works perfectly but it can only filter by questionId. I wish to have such a search bar that will filter by matching all the fields(questionId, groupId, questionTitle... etc all) the Question model has. (note: request.GET already been used for pagination.) Please suggest how can I do this? -
How to return field name containing a given value in a django model?
I have a list of strings I want to search for in my database, and I want my function to return the name of the field that contains the string: for word in word_list: if word in MyModel.objects.all(): return ?? How do I complete the function so that it accomplishes this? -
Concatenate foreign key fields with delimiter Django
Lets say I have 2 models with a foreign key relation which are used to bundle books: class Bundle(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=20) isbn = models.CharField(max_length=13) bundle = models.ForeignKey(Bundle) we'll identify the bundles by concatenating the ISBN numbers with the delimiter like so: 123456788 & 123456789 To further export a list of available bundles for further processing we need that number. I'm aware I could use: for bundle in Bundle.objects.all(): complex_isbn = ' & '.join(bundle.book_set.all().values_list('isbn', flat=True)) But this would just be too slow for the real-world purpose. Is there a way I could use annotate to accomplish this? If so, how? I'm struggling to find my way through the docs on how to accomplish concatenating multiple foreign key entries. -
Django DRF get ForeignKey values in serializer
I'm trying to retrieve all Benchmarks related to a Node in my serializer, but i'm not too sure how to retrieve them. Would I need to do some sort of reverse foreignkey lookup? Maybe my models are not made correctly? class Node(models.Model): node_id = models.CharField(max_length=42, unique=True) wallet = models.CharField(max_length=42, null=True, blank=True) earnings_total = models.FloatField(null=True, blank=True) data = models.JSONField(null=True) online = models.BooleanField(default=False) version = models.CharField(max_length=5) updated_at = models.DateTimeField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Benchmarks(models.Model): benchmark_score = models.IntegerField(default=0) benchmarked_at = models.DateTimeField(null=True, blank=True) provider = models.ForeignKey(Node, on_delete=models.CASCADE) class NodeSerializer(serializers.ModelSerializer): class Meta: model = Node fields = ['earnings_total', 'node_id', 'data', 'online', 'version', 'updated_at', 'created_at', ] -
You may need an appropriate loader
I'm trying to implement a project using Django and React but I'm facing a problem when doing "npm run dev". It seems to be related with .jsx and some loader. I don't even know what else to do 😭 Module parse failed: Unexpected token (5:7) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | | const container = document.getElementById("root"); > render(<App/>, container); My .jsx file, webpack.config.js and package.json -
How to implement my own search filter - Django?
I have a Book model: class Book(models.Model): title = models.CharField() ... HTML form: <form type="get" action="."> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button type="submit" >Submit</button> </form> For example: User input some text in my form:"Some strange text" I wanna find all books, which contain at least one of these words in upper or lower case or some phrases in this text('Some', 'some', 'Strange', 'strange', 'Text', 'text' or 'some strange', 'Strange text' and so on). How can I do that? -
Django ImageKit change image dimension inside Admin site
I use ImageKit to display images inside Django Admin site and it works fine: @admin.register(Client) class ClientAdmin(admin.ModelAdmin): list_display = ['title', 'client_logo', ] client_logo = AdminThumbnail(image_field='logo') client_logo.short_description = 'Logo' readonly_fields = ['client_logo'] But I need to display the images as thumbnails not in the original dimension, but I can't figure out how to use processors there. -
rendering specific div tag from views.py in django
I am working in my final year project and i am stuck to render specific page. I have following code. in accounts.html i have a div tag which contains anchor tags and by clicking them it will load a other html page. here is my code for accounts.html <div class="row no-gutters row-bordered row-border-light"> <div class="col-md-3 pt-0"> <div class="list-group list-group-flush account-settings-links"> <a class="list-group-item list-group-item-action active" data-toggle="list" href="#account-general">General</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-connections">Connections</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-change-password">Change password</a> <a class="list-group-item list-group-item-action" data-toggle="list" href="#account-delete-user">Delete Account</a> </div> </div> <div class="col-md-9"> <div class="tab-content"> <div class="tab-pane fade active show" style="overflow-y:scroll; height:450px;" id="account-general"> {% include 'EditProfile.html' %} </div> <div class="tab-pane fade" id="account-connections"> {% include 'connections.html' %} </div> <div class="tab-pane fade" id="account-change-password"> {% include 'change_password.html' %} </div> <div class="tab-pane fade" id="account-delete-user"> {% include 'delete_user.html' %} </div> </div> now i am trying to render specific page from django views.py i tried this def fun(request): //logic return render(request, 'account.html','#account-connections') as by default it will always load #account-general in the page how can I! any help appreciated! -
Page not found (404) No comment found matching the query
views.py class CommentCreatView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] template_name = 'home/add-comment.html' success_url = 'homepage' def form_valid(self,form): form.instance.user = self.request.user post = self.get_object() form.instance.post = post return super().form_valid(form) urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from .views import PostCreateView, PostsListView, PostDetailView, CommentCreatView urlpatterns = [ path('', PostsListView.as_view(), name='homepage'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-and-comments'), path('post/<int:pk>/comment', CommentCreatView.as_view(), name='add-comment'), path('creat', PostCreateView.as_view(), name='creat-post') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) add-comment.html {% extends "home/base.html" %} {% load crispy_forms_tags %} <!-- allow us to use crispy filter on any of our forms --> {% block content %} <div class="content-section"> <form method="POST"> <!--this method post is to protect our form fromcertain attacks --> {% csrf_token %} {{form|crispy}} <button class="btn btn-outline-danger mt-1 mb-1 mr-1 ml-1" type="submit">Add Comment</button> </div> </form> </div> {% endblock content %} So I opens it home/post/6/comment , I see the form and when I submit it. I get this error and the comment isnt saved error screenshot -
datetime_re.match(value) // TypeError: expected string or bytes-like object
I am running into this error when trying to run python manage.py migrate it seems that their could be a problem with the date fields in my models.py Please see the following code: Models.py from django.db import models class newCustomersClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) class jobCardsClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) jobNumber = models.CharField(max_length=50, blank=True ) dateRecieved = models.DateTimeField(auto_now=False, auto_now_add=False) dateToBeCompleted = models.DateTimeField(auto_now=False, auto_now_add=False) instructionBy = models.CharField(max_length=50, blank=True ) jobDoneBy = models.CharField(max_length=50, blank=True ) timeStarted = models.TimeField(auto_now=False, auto_now_add=False) timeCompleted = models.TimeField(auto_now=False, auto_now_add=False) Instructions = models.TextField(max_length=255) totalCostOfJob = models.CharField(max_length=50, blank=True) Forms.py: from django import forms from .models import newCustomersClass, jobCardsClass from django.forms import ModelForm class newCustomerForm(ModelForm): class Meta: model = newCustomersClass fields = 'customerName', 'addressStreetNo' ,'addressStreet', 'addressSuburb' ,'addressCity' , 'contact' , 'mail' , 'CellNo' class jobCardForm(forms.ModelForm): class Meta: … -
How to generate random unique id in django?
I am trying to generate random username based on user full name. Also here the phone is allowed null and blank but with create api view empty string is being passed to server if phone is not provided and with that integrity error occurs with phone. Here I think with the while condition i am getting 504 Gateway Time-out response. Is there any way without while statement since it is making request slower. class User(AbstractUser): phone = models.CharField(max_length=10, blank=True, null=True, unique=True) ... def save(self, *args, **kwargs): if not self.username: counter = 1 name = self.full_name unique_id = name.replace(" ", "") while User.objects.filter(username=unique_id): name = f"{unique_id}{counter+1}" self.username = unique_id return super().save(*args, **kwargs) -
How to wrap custom endpoints in Django Tastypie?
I want to add a dispatch method to some resource so I could use a wrapper decorator on it. The issue is that it only works on the CRUD operations and wont go into the dispatch method on 'original' endpoints: class SomeResource(SomeBaseResource): class Meta(...): ... def get_something_extra(self, request, **kwargs): ... def patch_detail(self, request, **kwargs): ... and the base resource: class SomeBaseResource(ModelResource): class Meta(...): ... # the wrapper @sheker_to_wrap_all_methods_with(...) def dispatch(self, request_type, request, **kwargs): logger.info('Enter') response = super(SomeBaseResource, self).dispatch(request_type, request, **kwargs) logger.info('Exit') return response So when I use patch request it is working as expected, but wont on calling the get_something_extra api. How do I wrap ALL methods in resource? -
How to mark a method as deprecated with swagger_auto_schema?
I'm using swagger-auto-schema to document my endpoints API using django-rest-framework, swagger, and drf-yasg. Is there a way to mark the API endpoints in the documentation as deprecated? -
Is there a way to run server with a session-persisted database connection in Django?
As I develop the backend side, I also develop the frontend. As you have probably guessed, I have to do some REST requests on my server. Well, there are a couple of solutions for that. I can use mocks on the frontend, or a fake JSON server. However, there are some cons to this approach: I have to remodel what I have on an already existing backend server. Dealing with authentication on a fake JSON server is not really comfortable. I have to write a lot of boilerplate if I want to go on mocking and unit testing approach. Again, all the logic I want already exists in my Django project, so what I want is: Run a dev server. Set up a fresh new database. Provide some initial data. Some fake users, posts, whatever. Do my testing on my frontend project while the server runs. Hit the kill signal. (CTRL+C) Gracefully drop the database that I have created on step 2. Shutdown the program. I use pytest and pytest-django. They do exactly these when they set up a test environment, I was wondering if I can manually do that. Thanks in advance. Environment Python 3.9 Django 2.2 -
__init__() got an unexpected keyword argument 'username'
Getting this error while making redis connection in django app. return self.connection_class(**self.connection_kwargs) Throwing error in this line. This looks like a dependency version issue, as it was working fine earlier