Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django manage request to an static file url
Does django have any method to process some logic before return static file? Example: request to http://example.com/some-file.js would be passed through an logic function before return that javascript file? -
Django Filter timestamp data GROUP BY day, week, month, year
I have an django(DRF) app in which I storing periodic data based on API response. Here is my model.py # Model to store the Alexa API Data class Alexa(models.Model): created_at = models.DateTimeField(auto_now_add=True) extra = jsonfield.JSONField(null=True) rank = models.PositiveIntegerField(default=0, null=True) I am using django-filters to query data based on a range (__lte, __gte). Like /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z return all the data created before 2020-02-14T09:15:52.329641Z [ { "id": 1, "created_at": "2020-02-03T19:30:57.868588Z", "extra": "{'load_time': 00, 'backlink': 0}", "rank": 0 }, ... ] Is there a way to build an endpoint to return aggregated data grouped by day, week, month and year based on the query params I pass. For example, /api/alexa/?created_at__lte=2020-02-14T09:15:52.329641Z&group_by=month would return [ { "created_at": "2020-01-01T00:00:00.000000Z", "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data "rank": 0 <- Aggregated Data }, { "created_at": "2020-02-01T00:00:00.000000Z", "extra": "{'load_time': 00, 'backlink': 0}", <- Aggregated Data "rank": 0 <- Aggregated Data }, ] Here's my current serializer.py class AlexaViewSet(viewsets.ModelViewSet): queryset = Alexa.objects.all() filter_fields = {'created_at' : ['iexact', 'lte', 'gte']} http_method_names = ['get', 'post', 'head'] I have seen several snippets doing aggregation but none completely fulfilling my requirements or giving me a complete idea about the topic. I am new to Django and building analytics dashboards in general, if there β¦ -
I am getting a weird error in running a django application
I am trying to run this app in my pc. https://github.com/Nidhintsajee/Django-Quiz-System I have activated virtual environment but i am getting an error on runserver, don't know what's wrong. Please help. -
How to optimize query set from duplicated query
1.(0.001) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=() 2.(0.000) SELECT COUNT(*) FROM (SELECT COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id") subquery; args=() (0.001) SELECT "entities_origin"."id", "entities_origin"."name", COUNT(DISTINCT "entities_hero"."id") AS "_hero_count", COUNT(DISTINCT "entities_villain"."id") AS "_villain_count" FROM "entities_origin" LEFT OUTER JOIN "entities_hero" ON ("entities_origin"."id" = "entities_hero"."origin_id") LEFT OUTER JOIN "entities_villain" ON ("entities_origin"."id" = "entities_villain"."origin_id") GROUP BY "entities_origin"."id" ORDER BY "entities_origin"."id" DESC; args=() entities/models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Origin(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Entity(models.Model): GENDER_MALE = "Male" GENDER_FEMALE = "Female" GENDER_OTHERS = "Others/Unknown" choice = ( (GENDER_MALE, GENDER_MALE), (GENDER_FEMALE, GENDER_FEMALE), (GENDER_OTHERS, GENDER_OTHERS), ) name = models.CharField(max_length=100) alternative_name = models.CharField(max_length=100, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) origin = models.ForeignKey(Origin, on_delete=models.CASCADE) gender = models.CharField(max_length=100, choices=choice) description = models.TextField() def __str__(self): return self.name class Meta: abstract = True class Hero(Entity): class Meta: verbose_name_plural = "Heroes" is_immortal = β¦ -
Wagtail : Internal server error when DEBUG = False
When change my DEBUG to False django-dashboard and wagtail-dashbard work fine but other urls give me this error page Internal server error my logs: [15/Feb/2020 06:15:45] ERROR [django.request:228] Internal Server Error: / Traceback (most recent call last): File "/home/minetuts/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/templatetags/static.py", line 106, in render url = self.url(context) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/templatetags/static.py", line 103, in url return self.handle_simple(path) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/templatetags/static.py", line 118, in handle_simple return staticfiles_storage.url(path) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 153, in url return self._url(self.stored_name, name, force) File "/home/minetuts/.venv/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 132, in _url hashed_name β¦ -
Bootstrap4 adjacent navbar columns
Here is my code: <nav class="navbar navbar-expand-lg navbar-light bg-light" role="navigation" id="navbar"> <div class="container"> <a class="navbar-brand mynav" href="{% url 'home' %}">Star Social</a> <ul class="navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="">Posts</a></li> <li><a href="">Groups</a></li> <li><a href="">Create Group</a></li> <li><a href="{% url 'accounts:logout' %}">Logout</a></li> {% else %} <li><a href="">Group</a></li> <li><a href="{% url 'accounts:login' %}">Login</a></li> <li><a href="{% url 'accounts:signup' %}">Signup</a></li> {% endif %} </ul> </div> </nav> I have a code like this but when I run the server, I'm getting style like this. -
Forbidden 403 You don't have permission to access this resource. (mod_wsgi, wamp, django) on windows
i have installed everything properly and gone through all solutions related to this subject but still error remains, I'm new to Django and i would really appreciate your help I get this error in my error log file: [Fri Feb 14 21:52:16.916422 2020] [authz_core:error] [pid 4288:tid 1252] [client ::1:51391] AH01630: client denied by server configuration: E:/AppSource/eCommerce/src/ecommerce/wsgi_windows.py and when i try to reach 127.0.0.1:80 i get: Forbidden 403 and this is my wsgi_windows.py configuration: activate_this = 'CE:/AppSource/eCommerce/Scripts/activate_this.py' exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site from django.core.wsgi import get_wsgi_application site.addsitedir("C:/Python37/Lib/site-packages") sys.path.append('E:/AppSource/eCommerce') sys.path.append('E:/AppSource/eCommerce/src') sys.path.append('E:/AppSource/eCommerce/src/ecommerce') os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings") application = get_wsgi_application() and this is hhtpd-vhosts.conf configuration: <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "E:/appSource/eCommerce/eCommerce.error.log" CustomLog "E:/appSource/eCommerce/eCommerce.access.log" combined WSGIScriptAlias / "E:/appSource/eCommerce/src/ecommerce/wsgi_windows.py" <Directory "E:/appSource/eCommerc/src/ecommerce/"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "E:/appSource/eCommerce/static_cdn/static_root" <Directory "E:/appSource/eCommerce/static_cdn/static_root"> Require all granted </Directory> Alias /media "E:/appSource/eCommerce/static_cdn/media_root" <Directory "E:/appSource/eCommerce/static_cdn/media_root"> Require all granted </Directory> </VirtualHost> i have tried everything that i know Please help to solve this Thanks -
using python variable in django sql query
@staticmethod def getdata(backdays): cursor = connections['MMY'].cursor() query ="Select * from temp WHERE DAY_OF_MONTH=TO_CHAR(sysdate-?,'DD')" cursor.execute(query,(backdays)) rdict = namedtuplefetchall(cursor) return rdict i am getting attribute error , I can see this value is getting printed when i am using print but above is failing can any one please help . it is python . Value is being passed using axios in javascript .