Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django base.html doesnt exist
This is my file tree this is my error this is views.py def signup(request): proj = project.objects.all() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'Homepage/Projects.html', {'form': form,"project":proj}) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('projects/', Homepage.views.signup, name='projects') ] my settings.py html did i miss something? -
In Django admin show parent level and sort it
Django==3.0.2 class LevelOne(models.Model): ... class LevelTwoAux(models.Model): parent_level = models.ForeignKey(LevelOne, verbose_name="Level 1", on_delete=models.CASCADE) class LevelTwo(models.Model): parent_level = models.ForeignKey(LevelTwoAux, verbose_name="Level 2 aux.", on_delete=models.CASCADE) utm_suffix = models.CharField(max_length=4, choices=UTM_SUFFIXES) Example of content: Level 1: table Level 2 aux: computer table Level 2: computer table_TR computer table_COMP computer table_INFO In Django admin for Level 2 I'd like to: 1) Show Level 1 in a separate column. 2) Sort by a) Level 1 b) Level 2 inside level 1. Like this: Level 1 |Level 2 table |computer table_TR table |computer table_COMP table |computer table_INFO Could you help me cope with this task? -
AWS, django, postgresql : OperationalError could not connect to server: Connection timed out
I tried deploy my webapp with django. I made RDS to use postgresql DB server and open all port inbound / outbound of the EC2 instance. but when I try 'eb deploy', error log say: OperationalError could not connect to server: Connection timed out Is the server running on host "~~~instance name~~~" (172...~~ip address~~) and accepting TCP/IP connections on port 5432? I don't know what is the problem. could anybody kindly help me? -
Django - Getting 405 error when submitting contact form
My Html contact form <form id="contact-form" method="post" action="{% url 'index' %}"> {% csrf_token %} <div class="messages"></div> <div class="controls"> <div class="row"> <div class="col-md-6"> <div class="form-group wow fadeInDown" data-wow-delay="0.2s"> <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your full name *" required="required" data-error="Fullname is required."> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-6"> <div class="form-group wow fadeInDown" data-wow-delay="0.4s"> <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email *" required="required" data-error="Valid email is required."> <div class="help-block with-errors"></div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group wow fadeInUp" data-wow-delay="0.6s"> <textarea id="form_message" name="message" class="form-control" placeholder="Your Message *" rows="4" required="required" data-error="Leave a message for me"></textarea> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-12"> <button class="btn btn-send" type="submit">Send message</button> </div> </div> </div> </form> urls.py from django.urls import path from .views import HomeTemplateView urlpatterns = [ path('', HomeTemplateView.as_view(), name="index") ] views.py, I defined my HomeTemplate view class with a method index that is handling my contact form from django.shortcuts import render from django.views.generic import TemplateView from .models import * from django.core.mail import send_mail from django.conf import settings class HomeTemplateView(TemplateView): template_name = 'home.html' # override get context date method def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['about'] = About.objects.first() context['services'] = Service.objects.all() context['works'] = RecentWork.objects.all() context['clients'] = Client.objects.all() return context def index(self, request): if … -
websocket onmessage - no connection - if received data equals to / consumers.py - django
New into websockets, searched but cannot find the answer. I send the message with the amount to the server and want to receive it back to update current amount of items. Hope somebody could help. No idea how to meet properly the 'cart_data' in msgData condition. While opening the page console returns onclose function, but after clicking the button sendMessage function returns an appropriate data. part of the template: <div> <a class="amountButton" name="decrease_button"> <button type="button">-</button> </a> <input id="id_amount" class="amountNumber" type="number" name="amount" value="{{ item.quantity }}" min="1" max="{{ item.auction.amount }}" required> <a class="amountButton" name="increase_button"> <button type="button>+</button> </a> </div> websocket.js: var amountbutton = document.getElementsByClassName('amountButton'); var message_cart; webSocket.onopen = sendMessage; webSocket.onmessage = receiveMessage; function receiveMessage(e) { var msgData = JSON.parse(e.data); console.log("msgData: " + msgData); //console ignores the whole line if ('auction_data' in msgData) { //some data, but never entered } else if ('cart_data' in msgData) { //some data, but never entered } }; function sendMessage() { for(let i = 0; i < amountbutton.length; i++) { //some on-click function, results updating message_cart variable webSocket.send(message_cart); //on chrome console shows the alert that WebSocket is already in CLOSING or CLOSED state. console.log(message_cart); //returns correct value } } consumers.py //not debugging in terminal at all def cart_data(self, event): … -
How to create relations of tree nodes efficiently in Django?
I have model Relation, that connects ancestor with all its descendants: class Relation(models.Model): ancestor = models.ForeignKey('Node') descendant = models.ForeignKey('Node') # Number of edges between ancestor and descendant power = IntegerField() And model Node: class Node(models.Model): ...some data... def save(self, parent, *args, **kwargs): self.create_relations(parent) return super().save(*args, **kwargs) I need to efficiently create relations between new node and ancestors. I managed to write the next function: def create_relations(self, parent): relations_of_parent = Relation.objects.filter(descendant=parent).values_list('ancestor', 'power') relations = [] for ancestor, power in relations_of_parent: relations.append(Relation(ancestor=ancestor, descendant=self, power=power + 1)) relations.append(Relation(ancestor=parent, descendant=self, power=1)) Relation.objects.bulk_create(relations) It would be good if there's only one hit database. Is there the way? -
Should I be using Django for this?
It is very possible that the answer to this question is simply “rather use Flask”, but I am hoping I can get a good enough excuse to actually get it working in Django. TLDR - Basic overview of the statistical model pre-Django: I built a model in R which I am busy porting over to Python. The model is a financial model that analyses past behaviour of client payments in order to estimate future expected losses & repayment. The model performs a number of data imports from an existing SQL database which itself gets populated by the company’s source system. The SQL database is ever growing and contains thousands of tables with loads of financial, historic, client data. The model imports what it needs and then we perform a bit of gymnastics in order to obtain a few bespoke parameters (i.e. we calibrate the model). Once all this is done, we apply the parameters to the latest set of loans in order to estimate the aforementioned forecasts. Purpose of the app: The main purpose of the web app is to “white box” the model. Clients were complaining that they have no feel for the numbers and would like to see … -
value too long for type character varying(255) SQLite3 to Postgres Django
I have switched from using sqlite3 to Postgres for my Django app. I have run these commands to get all my data from the sqlite3 database and I wanted to add it to the Postgres database: python manage.py dumpdata > db.json python manage.py loaddata db.json Then I got this error: Could not load database.Object(pk=XXXXXXXXXX): value too long for type character varying(255) In my models.py, the max_length is set to 10 and the value of the primary key is 10. Here is how I set the primary key for that object's model: models.CharField(max_length=10, unique=True, primary_key=True) Why I am getting that error? I have many other threads about this issue but I haven't yet found an answer that solved my issue. -
Django: is it possible to prevent old form entry - cookies?
I develop a django project in my forms, old form entry are not erased at browser closure so that input fields can behave like a dropdown list How can I do to prevent old form entry to be stored ? I try using SESSION_COOKIE_AGE = 0 but doing that I can't login anymore... settings.py SESSION_COOKIE_AGE = 0 SESSION_EXPIRE_AT_BROWSER_CLOSE = True -
Writing a program that arranges articles in a three column grid
can anyone help me code this? “A Homepage Grid” Background I am designing a homepage in a three-column grid format. Articles that appear in the homepage grid can be given a layout value which determines how many columns they take up. Articles can be one-column, two-column, or three-column. Each of the columns is 300 pixels wide, giving a total grid width of 900 pixels. [IMG]https://i.ibb.co/FYbRWJ0/Screenshot-2020-02-13-at-17-41-50.png[/IMG] There is a problem with adopting this grid format: depending on the layout values assigned to each article, the grid may end up having gaps. For example, the following article configuration creates the following layout: [ { "title": "Star Ocean review", "columns": 2 }, { "title": "Lego Star Wars review", "columns": 2 }, { "title": "Prison Architect review", "columns": 1 }, { "title": "Inside review", "columns": 1 }, { "title": "Umbrella Corps review", "columns": 2 } ] [IMG]https://i.ibb.co/fD1v4H9/Screenshot-2020-02-15-at-10-57-57.png[/IMG] As you can see from the above illustration, this article configuration creates a layout that has a gap in the third column of the first row. Given the following article configuration, I need a piece of code that adjusts the layout so that it contains as few gaps as possible. The final output should be rendered as … -
How do i increase the integer field when comment is liked
I have a comment model, i want to increase an integer field when a comment is liked. How do i create a comment like for each comment made by user. class Comments (models.Model): comment_post = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True) comment_likes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def comments(request, id): post = get_object_or_404(Image,id=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.commented_image = post comment.save() return redirect('site:comments', id=id) else: form = CommentForm() all_comments = Comments.objects.filter( author=request.user.id, commented_image=post, ) images = Image.objects.filter( imageuploader_profile=request.user.id, image_caption=post, ) context = { 'form': form, 'all_comments': all_comments, 'images': images, } return render(request,'comments.html', context) -
Why Abstract=True dosen't inherit in Meta class of django model
I we have this models in django: class FotherModel(models.Model): # Some fields goes here! class Meta: # Some fields goes here! abstract = True class ChildModel(FotherModel): # Some fields goes here! class Meta(FotherModel.Meta): #s Some fields goes here! When we inherit a field from the meta class of Django models, that field appears in child meta class, But this rule does not apply to abstract=True. I know that if this happens, no table in database will be created, But I don't know how this inheritance didn't happen. Please explain this process for me. -
How to connect django with mongodb compass?
I installed djongo through pip. My django version is 3 although I checked version 2 also to make it work. Python version is 3. I also made change in settings.py but whenever I load the command with makemigrations, it gives me following error. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql','oracle','postgresql','sqlite3' I don't know what to do with this now? settings.py DATABASES = { default: { 'ENGINE': 'djongo', 'NAME' : 'django_db' } } -
Error: Reverse for 'get_detail' not found. 'get_detail' is not a valid view function or pattern name
I am new to Django and facing the following issue. My Template file index.html: <a href = "{% url 'polls:get_detail' question.id %}" class="btn btn-success btn-sm">Vote</a> I am passing question.id to the url and my urls.py: app_name = 'polls' urlpatterns = [ path('',views.index, name='index'), path('<int:question_id>',views.get_detail, name='get_datail') ] and part of my views.py: def get_detail(request,question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question not exist") return render(request,'polls/result.html',{ 'question':question }) After running this I am getting below error: Reverse for 'get_detail' not found. 'get_detail' is not a valid view function or pattern name. I am using Django version : 3.0.3. Thank you. -
Staying in same tab on form submit but show new content(django)
I have three tabs. The first tab is set as the default tab. In the second tab, there is a form button. How do I make it so that when you click on the form button it calls a function in view, and that function in view renders new content in the SAME tab. Something like this i would imagine -
Django: Show data in panel based on clicking a row in a separate table
I am trying to build a django database which shows a table. For this table, i am trying to click on the row to open up data in panels below. I have been trying to follow this code (Update page with item details on click in Django), however I cannot make comments and it stipulates not to ask questions in the answer section. The data in the table comes from a class from "Drug". The database links Data to another table, "Links", which then links to "Restrictions" (I have no doubt screwed up the relationships in these tables) I am new to django, python and ajax (so please be easy on me) I have been stuck on this for weeks now, so any help would be appreciated. I have attached the relevant code below, any help would be appreciated. To clarify, the table works....When the user clicks the row, I am trying to get the PBSCode, then show the RestrictIndicatText from the Restrictions model, in the panel below the table. dashboard.html <div class="panel-body"> <div class = 'container'> <table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example"> <thead> <tr> <th>PBS Item</th> <th>Brand Name</th> <th>Generic Name</th> <th>Formulation</th> <th>Pack Size</th> <th>Maximum Quantity</th> <th>Number of Repeats</th> … -
How to use custom DateRangePicker widget with Django Filter's DateFromToRangeFilter
So I have this filter using Django Filter: class AssignmentFilter(FilterSet): assignment_date = filters.DateFromToRangeFilter() This built in class of Django Filter generates a form with these two inputs: <input type="text" name="assignment_date_after" id="id_assignment_date_0"> <input type="text" name="assignment_date_before" id="id_assignment_date_1"> So there you pick the two dates and based on that it will get you the filtered QuerySet. All working well. However I would like to use this usefull DateRangePicker: https://www.daterangepicker.com/ This gets activated like this: <input type="text" name="dates" class="form-control"> <script> $('input[name="dates"]').daterangepicker(); </script> However as you can see, this is only one field where the range between the dates will be set. But Django Filter works with an start input field and end input field. How can I modify this so that I can use the one input type: <input type="text" name="dates" class="form-control"> , but on POST it will use the start date and set it to the id_assignment_date_0 field. And the end date and set it to the id_assignment_date_1 field. This way I works with Django Filter, but on the front-end I have this nice DateRangePicker. -
Change collate of all existing column and tables
I had problem related with character code of mysql. I know I can change collate like this. alter database mydatabase COLLATE utf8mb4_general_ci; alter table mytable COLLATE utf8mb4_general_ci; However even after changing database, some tables are still remain old collate setting. after changing tables even,some columns are still remain old collate. Is there anyway to change all of database at once?? These are the error what I have django.db.utils.OperationalError: (1267, "Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='") -
How to load srcset attribute from a bootstrap template in Django website?
I want to load srcset attributes, but I don't know the proper tags, in order to load that srcset. :( Can anyone help me out? TIA <3 Here is the Screenshot of my code click to see code I want it to look like this click to see example -
How to instantiate a class given its parent class in Python?
I have 3 subclasses and 1 parent class that make the children share a common method. Example: class Animal: def communicate(): pass class Dog(Animal): def communicate(): bark() class Cat(Animal): def communicate(): meow() I would like to provide an API that instantiates a cat or a dog based on the received string that will be either "cat" or "dog" and calls .communicate(), but I don't want to write if and elses to check whether I should run Dog() or Cat(). I wonder if it is possible to bark or meow by doing something like: Animal("dog").communicate() Where "dog" can be a variable. Or if possible give the child classes some labelling and be able to instantiate them via this label, or even via the own class name. The ideia is to not have to write conditions Everytime I define new child child classes. Thanks in advance! -
django_filters filtering by ForeignKey not working
I am trying to use django_filters to Filter a model based on a field. these are the models : class Provider(models.Model): name=models.CharField(max_length=100) lat=models.DecimalField(max_digits=9,decimal_places=6) lon=models.DecimalField(max_digits=9,decimal_places=6) address_line1=models.CharField(max_length=255) address_line2=models.CharField(max_length=255) user=models.ForeignKey(User,on_delete=models.CASCADE) class Meta: db_table='providers' class Service(models.Model): name = models.CharField(max_length=50) provider=models.ForeignKey(Provider,on_delete=models.CASCADE) class Meta: db_table='services' I am using a ModelViewSet class ServiceList(viewsets.ModelViewSet): queryset=Service.objects.all() serializer_class=ServiceSerilaizer filterset_class=ServiceFilter and here is my Filter class: class ServiceFilter(filters.FilterSet): provider=filters.NumberFilter(lookup_expr='iexact') class Meta: model=Service fields=["provider_id"] I have defined the URL like this in my urls.py router_service = routers.DefaultRouter() router_service.register("services", ServiceList, basename='services') urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/', include(router_service.urls)), path('api/auth/',include('djoser.urls')), path('api/auth/',include('djoser.urls.authtoken')), ] Now when I hit the URL: http://127.0.0.1:8000/api/services/?provider_id=1 I get all the services, not just the ones for provider_id=1. Can anyone help? Am I missing something? -
How to return upto date serializer data django rest framework
I am trying to vote up comments in my serializer. All seems to work well with the voting part of it. However, the serializer returns old values rather than the updated values. I know I am doing something wrong, just not sure how to put it all together to return the recent value through $ajax after the comment vote is recorded. Note: When I refresh the page, I get the right vote count. Here is my view.py that records the votes: class CommentUpdateAPIView(DestroyModelMixin, generics.RetrieveUpdateAPIView): queryset = Comment.objects.all() serializer_class = CommentUpdateSerializer permission_classes = [IsOwnerOrReadOnly] def perform_update(self, serializer): if self.request.user.is_authenticated: serializer.save(user=self.request.user) # For Comments Voting def partial_update(self, request, *args, **kwargs): if request.method == 'PATCH': if self.request.user.is_authenticated: comment = get_object_or_404(Comment, pk=kwargs['pk']) posttype = self.request.data['type'] try: if posttype == 'down': if comment.votes.exists(request.user.id, 1): comment.votes.delete(request.user.id) else: comment.votes.down(request.user.id) elif posttype == 'up': if comment.votes.exists(request.user.id, 0): comment.votes.delete(request.user.id) else: comment.votes.up(request.user.id) # Should return the latest, values in the database # Unfortunately Only old value keep coming back... return Response(CommentUpdateSerializer(comment).data) except: raise serializers.ValidationError({'detail': _('Something isn\'t right! Try again later')}) And my serializer: class UserPublicSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'is_superuser', 'is_staff' ] class CommentSerializer(serializers.ModelSerializer): user = UserPublicSerializer(read_only=True) image = serializers.SerializerMethodField(read_only=True) class Meta: model … -
One to Many relation, get parent's last inserted ID and use it on child
I am trying to insert data into DB through one to many relation. there is an objects array which is like below. let says language objects array: [ { title: python, framework: 3, publish: 7567 }, { title: php, framework: 5, publish: 234 }, { title: java, framework: 10, publish: 1233 } ] so, lets say I have parent and child table in DB. inside parent there is a title column. I want to insert title to that column. To do that: titles = [] for lang in language: titles.append(land["title"]) for title in titles: parentModel = parent() parentModel.title = title parentModel.save() But the thing I also want to insert other values into child table by their last inserted title's id. what is the best way to achieve this? P.S: in child table there is already foreign_key column -
How to specify autocomplete IntelliSense for Python in django?
I am working on a Django project but and new to Docker and recently I have started working with it. The tree shows my project structure. . ├── app │ ├── app │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-37.pyc │ │ │ └── settings.cpython-37.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── core │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ └── tests │ │ ├── __init__.py │ │ └── test_model.py │ └── manage.py ├── docker-compose.yml ├── Dockerfile ├── LICENSE ├── README.md └── requirements.txt For more information, my virtual environment is in the same folder. I can't use Python autocomplete IntelliSense as my working app Django project directory is inside the app directory. Is there any way of fixing it? -
AWS, postgreSQL : could not connect to server: Connection timed out Is the server running on host "..." and accepting TCP/IP connections on port 5432?
I Use AWS elasticbeanstalk to deploy the Django app, but suddenly I can't deploy with below error. I use RDS to change Database Server. and allow all protocol, all port inbound/outbound of the EC2 instance(I guess). I don't know what is the problem and How can I solve this with AWS. Could anybody kindly help me? OperationalError could not connect to server: Connection timed out Is the server running on host "flying-dutchman.cwzyedh0rcst.ap-northeast-2.rds.amazonaws.com" (172.31.13.163) and accepting TCP/IP connections on port 5432?