Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to prevent the resubmition of the form in Django template
{% extends 'base.html' %} {% load buttons %} {% load static %} {% load custom_links %} {% load helpers %} {% load plugins %} {% block content %} <form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal" id="reportForm"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-heading"> <strong>Add Report</strong> </div> <div class="panel-body"> <table class="table table-hover report-body attr-table"> <tr> <td>URL</td> <td> <input type="text" required="required" name="src"> </td> </tr> <tr> <td>WIDTH</td> <td> <input type="number" required="required" name="width"> </td> </tr> <tr> <td> HEIGHT</td> <td> <input type="number" required="required" name="height"> </td> </tr> <tr> <td> NAME OF THE REPORT</td> <td> <input type="text" required="required" name="report_name" > </td> </tr> </table> <input type="submit"> </div> </div> </form> {% endblock %} i don't have the database for the checking the exiting record . Here is one problem in my from when the user click on the reload on top of the web page ...then same form with same record will generated again ...how to prevent this resubmition the form -
How to clear selection in Django autocomplete field
I have a model admin. class Some(admin.ModelAdmin): ... autocomplete_fields = ['user', ...] When user is selected I cannot clear selection in admin interface. Is there some setting I missing? -
How to retrieve latest model object of a logged in user who has already submitted the form?
I tried something like this customer=Customer.objects.filter(id=request.user.id).latest('first_name', 'last_name') customer.first_name However this fetches me the old data of the logged in user. I read about latest() method and implemented this customer=Customer.objects.latest('id') but as we know this will only render the last submission details not necessarily of the user who has logged in. Here is my model.py for reference class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) So, how would I query that information? -
Filter data based on intervals in Django
I have following model: class MyModel(models.Model): due = models.DateTimeField(null=True) max_days_before_due = models.IntegerField() I would like to filter out instances or rows that are past this due, ie. when due minus max_days_before_due is in the past. I am using this query: current_date = timezone.now() MyModel.objects.annotate( counted_days=Case( When( due__isnull=False, then=ExtractDay(F('max_days_before_due')-current_date) ), default=0, output_field=IntegerField() ) ).filter( due__gt=F('counted_days') ) I am receiving this error: django_1 | File "/usr/local/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute django_1 | return self.cursor.execute(sql, params) django_1 | django.db.utils.ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist django_1 | LINE 1: ... '2020-08-26T15:03:11.111165+00:00'::timestamptz) AT TIME ZO... django_1 | ^ django_1 | HINT: No function matches the given name and argument types. You might need to add explicit type casts. When I delete the subtration from the annotation, the error does not show, but I need to be able to count the timedelta. Otherwise if I set the due to, let's say, 2020-08-30 and current_date is 2020-08-26 it returns 30 in the counted_days field instead of 4. I've been trying to use this question and these docs as reference. I am using PostgreSQL in version 10 and Django in version 1.11, Python 3.4. -
Can't go to the detail view in Django
my detail view supposed to give me the primary key but why I got this error? error I got django.urls.exceptions.NoReverseMatch: Reverse for 'leaveform_detail' with no arguments not found. 1 pattern(s) tried: ['student\\-leaveform\\-detail/(?P<pk>[0-9]+)/$'] models.py class StudentLeave(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) leave_from_date = models.CharField(max_length=200) leave_till_date = models.CharField(max_length=200) student_name = models.CharField(max_length=200) leave_reason = models.TextField() def __str__(self): return self.student_name views.py class Student_leaveform_detailView(DetailView): model = StudentLeave template_name = "attendance/content/student/student_leaveform_detail.html" urls.py path('student-leaveform-detail/<int:pk>/', Student_leaveform_detailView.as_view(), name="leaveform_detail") I used this button to got to the route <a href="{% url 'leaveform_detail' %}" class="btn btn-info mt-3 ml-auto">View</a> -
Extending graphene-django FILTER_DEFAULTS does not work
I am generating dynamically schema definitions iterating over django models in my project like so: My project includes some custom model fields that need to have mapped filters to them or otherwise graphene-django will throw errors like: AssertionError: MyModelSet resolved field 'custom' with 'exact' lookup to an unrecognized field type CustomField. Try adding an override to 'Meta.filter_overrides'. See: https://django-filter.readthedocs.io/en/master/ref/filterset.html#customise-filter-generation-with-filter-overrides I have extended the graphene_django.filter.filterset.GrapheneFilterSetMixin.FILTER_DEFAULT with my custom field->filter mapping as suggested in graphene-django github issue Extending global filter set overrides #1031. This makes the aforementioned error go away, however it does not seem to use the filter class that I map to the custom field. It rather uses default django_filter ChoiceFilter from which that filter inherits: class CustomChoiceField(forms.ChoiceField): def valid_value(self, value): """Check to see if the provided value is a valid choice.""" print('VALIDATING !!!!!') text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class ChoiceFieldFilter(CustomChoiceField, ChoiceIteratorMixin): iterator = ChoiceIterator class CustomChoiceFilter(ChoiceFilter): field_class = ChoiceFieldFilter Running query to … -
Django not picking up the functions
I have tried every thing from making new function and saving every file thrice but nothing seems to work. And its my first time using Django if any one find anything please point it out... Note: Django ver 3.1 Server Error: path('', views.home_view), AttributeError: module 'pages.views' has no attribute 'home_view' settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'pages', ] views.py from django.http import HttpResponse # Create your views here. def home_view(*args, **kwargs): return HttpResponse("Hello world") urls.py from django.contrib import admin from django.urls import path from pages import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view), ] -
Django Rest Framework Generic ViewSet doens't show parameters and models in Swagger
I try to develop an backend API using Django, the rest framework and swagger (using drf_yasg). To get started quickly I tried to generate the viewsets and serializers, but in Swagger the parameters and schemata/ models aren't shown. If I would manually code this for each model it would work, but I would need to adjust each serializer/ viewset for each change in the models. This is my code for the generation: # Template class for serializing class GenericSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' depth = 3 # Unified Generic API view for all models in shop.models class GenericAPIView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) lookup_fields = ['id'] def dispatch(self, request, *args, **kwargs): for model_name, model in apps.get_app_config('api').models.items(): if request.path.split('/')[2] == model._meta.verbose_name_plural.title().lower(): self.model = model self.queryset = self.model.objects.all() serializer = GenericSerializer serializer.Meta.model = self.model self.serializer_class = serializer return super().dispatch(request, *args, **kwargs) This way the default ModelViewSet routes show up in swagger, but the parameters for each model are missing and the models itself. I confirmed that the model is assigned and despite my code it shows a warning in the console that I should provide a serializer_class or override the method (but I think it should be fine because I assign it manually). -
Can't set any background image for jumbotron-local or remote
I have just overridden the bootstrap here and I made sure it's pulling from my local css, any other changes to it do work, but when I try to insert a background-image nothing happens. I tried all local path variations for images and remote URLs as well. I'm using Django and had a problem earlier with my settings.py -can that be causing it?? Thanks #settings.py STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' #this is the jumbotron html <section class="jumbotron text-center"> <div class="container"> <h1>Album example</h1> <p class="lead text-muted">Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely. </p> <p> <a href="#" class="btn btn-primary my-2">Main call to action</a> <a href="#" class="btn btn-secondary my-2">Secondary action</a> </p> </div> </section> #and the custom .css .jumbotron { padding: 2rem 1rem; margin-bottom: 2rem; background-color: #c5b8b8; border-radius: .3rem; background-image: url("https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png"); background-repeat: no-repeat; background-position: bottom center; background-size: cover; } -
Logout function provides RecursionError error
I have this function in views.py: def logout(request): logout(request) return HttpResponse('Logged out succesfully!') and this is the error I get when going to /logout RecursionError at /logout/ maximum recursion depth exceeded -
DRF how to update email with @action?
When I try to update User it's create new user. Where is my problem? View class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get_object(self): return self.request.user Action @action(methods=['PATCH'], detail=False) def change_email(self, *args, **kwargs): user = self.get_object() serializer = serializers.UserEmailSerializer(data=self.request.data, context={'request': self.request}) serializer.is_valid(raise_exception=True) serializer.save() self.send_email(user.email) return Response({'Confirm yours new email'}, status=status.HTTP_200_OK) Serilializer for action class UserEmailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email') read_only_fields = ('id',) -
`groupby` by date with timezone influence among Django/Jinja2 environment
In PostgreSQL I store time information in INT (meaning UNIX timestamp) with django-unixtimestampfield. Now I am using django-jinja (Jinja2 backend) to render templates, and also, I am using groupby to group results from transaction data, like this: {% for d, t_day in transactions|groupby('updated_at.day') %} <p>{{ d }}</p> {% for t in t_day %} ... {% endfor %} {% endfor %} But updated_at.day will be calculated by UTC, not by the local timezone. How should we influence local timezone information into groupby()? -
Not displaying my navbar {% extends 'base.html' %} when I use django {% block content %}
When I use {% extends 'base.html' %} my navbar displays correctly but when I use {% block content %} Hello World{% endblock content %} my navbar disappears and I only see the text "Hello World". I dont really know what to try it appeared to be straight forward but apparently it isn't until you actually know. {% extends "base.html" %} {% block content %}<h1>Hello World</h1>{% endblock content %} My 'base.html' file {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block head %} <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>my title goes here</title> {% endblock %} </head> <body> {% block content %} <div class="container-fluid"> <div class="row"> <div class="col"> <nav class="navbar custom-navbar"> <h1>World Truthers</h1> <div class="col navbar-buttons"> <button class="btn custom-button"><p><b>Contact</b></p></button> <button class="btn custom-button"><p><b>About</b></p></button> <button class="btn custom-button"><p><b>Returns</b></p></button> <button class="btn custom-button"><p><b>Payment</b></p></button> <button class="btn custom-button"><p><b>Delivery</b></p></button> <button class="btn custom-button"><p><b>Store</b></p></button> </div> </nav> </div> </div> </div> {% endblock %} </body> -
send multiple files Json file django rest framework
Hi I am submitting data like this as raw data with Content-Type : application/json in header. { "myData": { "name": "name", "title": "journalist", "type": "Media", } } Now I want to send multiple files with this . how I can achieve in this scenario ? -
pikepdf - how to return in memory pdf object from django view
I currently have the following code: pdf = Pdf.open(f"cover.pdf") page = pdf.pages[0] for i, a in enumerate(page.Annots): print(a.T) a.V = str(i) pdf.save("output_test.pdf") I can't find anywhere online that describes how to return the in-memory pdf object from a django view. This is diving me nuts, can anyone help? -
Filter DateTimeField by rounded time ( 10 minutes for examples ) using only the ORM?
I came up with a solution but it's using a model method ( as far as i understand it cannot be used with X.objects.filter() ) and then use the python method sorted. I've read that it's way faster to use django ORM than direct python so I'm searching for a solution. I precise that adding fields to my model is not possible as the database is already well populated. Basically I've an Articles model : class Articles(models.Model): title = models.CharField(max_length=200, null=False, blank=False) image = models.URLField(null=False, blank=False) summary = models.TextField() link = models.URLField(null=False, blank=False) pub_date = models.DateTimeField(default=timezone.now) source = models.ForeignKey( Sources, on_delete=models.CASCADE, related_name="souurce") category = models.ManyToManyField(Categories) and what I want to do is filtering result by approximate publication date ( for example an article published at 5:34 and an another one published a 5:31 are both considered published at the same time ), then I can perform other filters like per category, source or even by title. Here is my class method to do that (by closest 10 minutes ): def get_approximate_date(self): pub_date = self.pub_date def timeround10(dt): """timertound closets 10 minutes""" a, b = divmod(round(dt.minute, -1), 60) h = (dt.hour + a) % 24 m = b new = dt.replace(hour=h, minute=m, … -
Problems with installing psycopg2 in Django [duplicate]
In my Django project, I tried to add this line to requiements.txt, and pip install -r requirements.txt, I had problems with install. psycopg2==2.7.1 Here's the error: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/psycopg2-2.7.1.dist-info' Consider using the --user option or check the permissions. Than I tried installing manually: pip install psycopg2 I had the following error: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'cc' failed with exit status 1 Than I tried to install with --user: pip install psycopg2 --user ...but it's still the same error. Edit: I already set virtualenv in the project directory. UPDATE When I look to the first error, I see that it has a warning for Python2.7, but I'm working with Python3. This might be source of problems. -
How to make a `FileHandler` strip terminal escape sequences (colors) from a log message?
I have a single Logger with two Handlers: StreamHandler and FileHandler. I want to log colored output to the terminal using escape sequences (see Logger usage) via the StreamHandler. However, I don't want to log such escape sequences via the FileHandler: Log to StreamHandler: \033[39m{}\033[0m\033[91m{}\033[0m\033[39m{}\033[0m Log to FileHandler: {}{}{} In order words, the FileHandler should strip the terminal escape sequences. Is there any solution besides creating two Loggers configured with a StreamHandler and FileHandler, respectively? I really don't want to carry two separate Loggers around in the code, if it can be avoided. Logger usage: fmt = 'Match: {} ({}/v{}): \033[39m{}\033[0m\033[91m{}\033[0m\033[39m{}\033[0m ({}) {}' self.logger.info( fmt, o.type.lower(), o.id, o.version, remove_control_chars(match.left), remove_control_chars(match.text), remove_control_chars(match.right), match.regex, suffix ) Logger configuration: def init(log, level, no_console): formatter = logging.Formatter( '{asctime:s} -- {levelname:<5s} -- {name:s} -- {process:d} -- {funcName:s} -- {message:s}', datefmt='%m/%d/%Y %I:%M:%S %p', style='{' ) logger = logging.getLogger('watchdog') if getattr(logging, level.upper()) is None: raise common.exc.WatchdogException(f'Failed to set level for logger: {level.upper()}') logger.setLevel(getattr(logging, level.upper())) if not no_console: handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) try: handler = logging.FileHandler(log, mode='w+') handler.setFormatter(formatter) logger.addHandler(handler) except Exception as exc: raise common.exc.WatchdogException(f'Failed to initialize file handler: {log}') from exc -
how to call and use my pk given in urls in a class based view?
I have this code in urls from .views import testview urlpatterns = [ path('test/<pk>', testview.as_view(), name='test') ] And this is my view : class testview(FormView): template_name = 'test/test.html' form_class = ExampleForm def form_valid(self, form): cl = form.cleaned_data book= Book(user_id='pk', book = cl['book'], price = book.price ) return create_book(self.request, book) So how can I take that pk in the urls and use it inside the view? -
Display data according to users as in Facebook,Amazon [closed]
I have built the ecommerce website.How can I display the content according to their username and password as like in facebook,Amazon -
How to automatically change a Django Model field after a specific amount of time?
I'm working on an e-commerce website that includes an auction process. For this I have created an Auction Model with different status options: (e.g.: active, closed, canceled, completed, etc.). I want to give users a fixed amount of time (say 5 hours) to partake in the auction and add their bids, after which the auction status will automatically be change from "active" to say "completed" and the users won't be able to submit bids anymore and a winner will be determined. What is the best way to achieve this in Django? I have read about using background tasks like django-backgound-tasks or Celery. But this would require me to check every minute to see if the task if the 5 hours have passed or not. The other things option I cam across are using some type of timer or Django signals. I'm not sure which would be the best strategy here and therefore am asking the community for their opinion, thank you! -
How to recognize urls with get parameters un django?
I am learning Django, usually I use urls like www.mysite.com/post/1, and I have understood them because they are well described in the documentation. Now I need to create a url like: www.mysite.com/calendar/?day=21&?month=12&year=2020, I don't understand what should I write in my ulrpatterns list. I have tried something like this: url(r'^search/(?P<parameter>\w+)', views.calendar, name='calendar') but it doesn't work. What should I write as regex expression? Thanks -
Django - middleware inserting code in template
I need middleware just like contib.messages, but to insert specific JS code to page from views instead of message. Is there a ready-made solutions or any ideas how to do this? -
How to show data according to heading in Table (Django Template)
I am having a following model class Project(models.Model): project = models.CharField(max_length=255, blank=True, null= True) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() start_date = models.DateField() I need to print the details in an html table format Here is my query set in views.py table_heading = Project.objects.values_list( "start_date", flat=True).distinct() heading = ['project']+list(table_heading) q = Project.objects.values('start_date').filter(user=request.user).annotate( total_hours=Sum((F('end_time') - F('start_time')),project =F('project')) context{ 'heading': heading, 'query : q } In my html <table class="table"> <thead> <tr> {% for value in heading %} <th>{{value}}</th> {% endfor %} </tr> </thead> <tbody> {% for value in query %} <tr> <td>{{value.project}}</td> <td>{{value.total_hours}}</td> </tr> {% endfor %} </tbody> </table> But it's coming as all the total hours are printing in the first column..... But what I need is if the date is today total_hour need to print down to that heading ...... if the date in heading is yesterday it need to print down to that date But now all the values are printing only in the first column Thanks -
what is this main this error "TypeError: expected str, bytes or os.PathLike object, not NoneType django 3 [closed]
hi how are you i have problem : what is this main this error "TypeError: expected str, bytes or os.PathLike object, not NoneType [26/Aug/2020 16:58:02] "GET /static/images/favicon.png HTTP/1.1" 500 84143" and admin page have no style