Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create base layout file in django
In templates folder i have 2 HTML files, index.html and add.html file i want to create one layout file and want to add header and footer in that, and in middle content i want to override my 2 files into that layout file, can anyone please help me how can i do that ? here is my 2 html files index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <table> <tr> <th>Page Title</th> <th>Update Date</th> <th>Action</th> </tr> {% if pagelist %} {% for page in pagelist %} <tr> <td>{{ page.title }}</td> <td>{{ page.updated_date }}</td> <td><a href="{% url 'crud:update' page.id %}">Edit</a></td> </tr> {% endfor %} {% else %} <tr> <td colspan="2">Np Pages are available</td> </tr> {% endif %} </table> add.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <form method="post" action="{% url 'crud:add' %}" name="page_form" id="page_form"> <input type="text" name="title" value="{{ title }}"> <input type="text" name="permialink" value="{{ permialink }}"> <input type="text" name="updated_date" value=""> <input type="text" name="bodytext" value=""> <input type="hidden" name="pages_id" value="{{ page_id }}"> {% csrf_token %} <input type="submit" name="submit" value="Submit"> </form> -
When I try open web-site page i have an a 'NoReverseMatch' error, how I can fix it?
When I try to open http://127.0.0.1:8000/blog/ i have this error : NoReverseMatch at /blog/ Reverse for 'BlogList' with arguments '('test-post',)' not found. 1 pattern(s) tried: ['blog/$'] main urls urlpatterns = [ ... url(r'^blog/', include('blog.urls', namespace='blog')), url(r'^', include('main.urls', namespace='shop')), ... ]\ app urls url(r'^$', views.blog_list, name='BlogList'), url(r'^(?P<slug>[-\W]+)/$', views.blog_detail, name='BlogDetail'), views.py def blog_list(request): template = 'blog/blog.html' posts = Post.objects.filter(available=True) page = request.GET.get('page') paginator = Paginator(posts, 9) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = { 'posts': posts, 'page': page } return render(request, template, context) def blog_detail(request, slug): post = get_object_or_404(Post, slug=slug, available=True) template = 'blog/detail.html' return render_to_response(template, {'post': post}) models.py class Post(models.Model): name = models.CharField(max_length=32) slug = models.SlugField(db_index=True, unique=True) ... class Meta: ordering = ['-updated'] index_together = [ ['id', 'slug'] ] def __str__(self): return "%s" % self.name def get_absolute_url(self): return reverse('blog:BlogList', args=[self.slug]) -
Django / Mezzanine url routing not working
I have django / mezzanine webapp and I want to route the URLs for an index page and a blog page. Instead of rendering index.html or blog_post_list.html mezzanine is catching everything and rendering base.html without additional content. urls.py urlpatterns = i18n_patterns( url("^admin/", include(admin.site.urls)), ) if settings.USE_MODELTRANSLATION: urlpatterns += [ url('^i18n/$', set_language, name='set_language'), ] urlpatterns += [ url("^blog/", blog_views.blog_post_list, name="blog"), url("^$", views.IndexView.as_view(), name='home'), url("^", include("mezzanine.urls")), ] -
Cannot find reference 'DjangoWhiteNoise' in django.py
I tried edit 'wsgi.py' file like this: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjanoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) But I get an error: Cannot find reference 'DjangoWhiteNoise' in 'django.py' When I make a command `python manage.py collectstatic' I get some errors. There is log: Traceback (most recent call last): File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: /home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/yalef/PycharmProjects/DjangoEdu/venv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line … -
Redirecting from model custom button to Django views
I have a model in Django admin panel.I have created a custom button for this model.I want that when someone clicks the button it should redirect it to a function in Django views.py.I have tried looking for the solution but couldnt find anything.Is it possible in Django?Any help would be appreciated -
distinguish whether page was reloaded or not in Django views or in template
Django question I would like to ask whether it is possible or not to distinguish in view or in template if page was reloaded or page was reached by url from the other page? If shorten it out, need to know if it is any marker that would indicate that page got reloaded by F5 or whatever? Perhaps it is probably possible to figure out by analyzing request. Only 1 idea that comes to my mind is following: request.get_full_path()# – specifies full address of the current page request.META.get('HTTP_REFERER')# – specifies full address of previous page So that theoretically if former == last – page is reloaded, but it doesn't work this way. If you know any solution or hint -please communicate it. Thank you and have a nice day! -
Google calendar authentication page opens in terminal instead of client browser
I am integrating google calendar with my web application which is a django app. when i am doing it on localhost server, its working fine. Google authentication page opens in client browser, but when i am uploading that code to the server and integrating google calendar, then Google authentication page opens in terminal where i run my django server. ` def get_credentials(request): creds = None # If there are no (valid) credentials available, let the user log in. if os.path.exists('token.pickle_' + request.GET.get('bot_id')): with open('token.pickle_' + request.GET.get('bot_id'), 'rb') as token: creds = pickle.load(token) print(creds) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRET_FILE, SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.pickle_' + request.GET.get('bot_id'), 'wb') as token: pickle.dump(creds, token) serializer = CalenderIntegrationSerializer(data={'bot_id': int(request.GET.get('bot_id')), 'status': True}) if serializer.is_valid(): serializer.save() if os.path.exists('token.pickle_' + request.GET.get('bot_id')): context = {'signin_url': creds} return JsonResponse({'status': 200, 'data': 'Integration done!', 'is_integrated': True}) ` And this is my reference google calendar code python -
How to get the other fields of a ForeignKey in Django
I have two models as Author and Comment One is Comment and it has a ForeinKey points to Author(BlogUser) class Comment(models.Model): body = models.TextField('body', max_length=500) created_time = models.DateTimeField('create_time', default=now) last_mod_time = models.DateTimeField('last_mod_time', default=now) author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='author', on_delete=models.CASCADE) article = models.ForeignKey(Article, verbose_name='article', on_delete=models.CASCADE) parent_comment = models.ForeignKey('self', verbose_name="parent_comment", blank=True, null=True, on_delete=models.CASCADE) is_approved = models.BooleanField('is_approved', default=True, blank=False, null=False) is_enabled = models.BooleanField('is_enabled', default=True, blank=False, null=False) is_deleted = models.BooleanField('is_deleted', default=True, blank=False, null=False) Author Model class BlogUser(AbstractUser): qq_number = models.CharField('QQ', max_length=20, default='') I am trying to get all the comments related to a specified Article and display the comments list by the format of usernames and comment bodys. In the view I filter all the comments by the article id, but after serializing the filter queryset, it gives me only the Author's primary id, how could I get the other feilds of Author? Shall I write a function by myself or there is some easier way to do it? The view: def get_comment_list(request, article_id): if request.GET: comment_list = models.Comment.objects.filter(article_id = article_id) data = serializers.serialize('json',comment_list) return HttpResponse(data, content_type="application/json") else: PermissionDenied('Not accept post') -
Django trying to add "_id" to the primary key OneToOne column
I have 2 models. Radusergroup and expiration. username is primary key on Radusergroup and a OnetoOne Field in expiration with primary_key=True. Django is trying query for username_id in expiration model although the field itself is username only. When I dont explicitly define Managed=False it also tries to change the expiration table from the database to username_id as well. class Radusergroup(models.Model): username = models.CharField(max_length=64,primary_key=True) groupname = models.CharField(max_length=64) priority = models.IntegerField() class expiration(models.Model): username = models.OneToOneField(Radusergroup,on_delete=models.CASCADE, to_field='username', primary_key=True) expiration = models.DateTimeField() python .\manage.py shell >>> help(expiration()) Help on expiration in module panel_app.models object: class expiration(django.db.models.base.Model) | expiration(*args, **kwargs) | | expiration(username, expiration) | | Method resolution order: | expiration | django.db.models.base.Model | builtins.object | | Methods defined here: | | expiration = <django.db.models.query_utils.DeferredAttribute object> | get_next_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=True, ** kwargs) | | get_previous_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=Fals e, **kwargs) | | username_id = <django.db.models.query_utils.DeferredAttribute object> | ---------------------------------------------------------------------- -
How to limit a like counter based on the cookie of the user instead of logged in user?
I use Intercooler.js for a small like counter I have. It is basically just a IntegerField field in a Django model named value and then all the logic gets handled in the view like this: from django.shortcuts import render from .models import Counter def index(request, template_name="counter.html"): if request.GET.get('ic-request'): counter, created = Counter.objects.get_or_create(pk=1) counter.value += 1 counter.save() else: counter, created = Counter.objects.get_or_create(pk=1) print(counter.value) context = dict( value=counter.value, ) return render(request, template_name, context=context) In the template you write it like HTML, without a single line of JavaScript: <button ic-get-from="{% url 'index' %}" ic-target="#wrapper" ic-select-from-response="#wrapper" class="btn btn-success btn-sm my-2 mr-1" ><i class="fe-icon-heart"></i>&nbsp;<div id="wrapper">Like {{ value }}</div></button> So that's pretty cool. However right now you can just hit the like button forever. Is there some way to add a bit of (JavaScript) to limit the likes to one based on the cookie of the user rather than the person logged in? But still using Intercooler.js -
How can I show only some options using django and select?
Hello I have this code using Django in a HTML file : <select class="form-control" data-formsource="test" id="id_test1" name="type"> {% for x,y in opt %} <option value="{{ y }}" data-select="{{ y }}">{% trans y %}</option> {% endfor %} </select> And there is an option which is "available" but I don't want to see this option ... How can I do this ? Thank you very much ! -
How to get, change or clear a django-autocomplete-light field value with javascript
I'm using django-autocomplete-light and want to add action buttons do update/delete choices. So, I don't understand clearly how I can update/delete value and trigger change specific field. Is there a clear documentation about that somewhere ? -
Django Show selected data from database based on user input in html
I am a newbie. I create restaurant system by using Django. I want to display data (table number, item, and quantity of the food) which has been inserted to database. I want to show the data based on the random id which has been generated while the customer doing the food ordering. Hence, I do not know how to do it. Anyone can help me please I have tried these codes, but it only shows the back button. I cannot retrieve the data based on the random id from database here is my models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) Item = models.TextField() Qty = models.IntegerField(blank=False) Price = models.TextField() Status = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=100, null=True) my html file: <form action="" method="post"> {% csrf_token %} <!--<input type="Submit" name="submit" value="See Order"/>--> {% for order in so1 %} <table width="800"> <tr> <th width="800">Table Number</th> <th width="800">Item</th> <th width="800">Quantity</th> <th width="800">Status</th> <th width="800">Order Id</th> </tr> <tr> <td width="800">{{ order.Table_No }}</td> <td width="800">{{ order.Item }}</td> <td width="800">{{ order.Qty }}</td> <td width="800">{{ order.Status }}</td> <td width="800">{{ order.OrderId }}</td> </tr> {% endfor %} <input action="action" onclick="window.history.go(-1); return false;" type="button" value="Back" /> my view: def see_order(request): if request.method == "POST": Table_No = request.POST.get("Table_No") Item = request.POST.get("Item") Qty … -
Remove/Hide Save,Save and add another buttons for one of my models in admin panel
I have created a custom button for my application in Django admin panel by overriding the template.I was wondering if there is any way I could remove the save and save and add another button from my django admin panel.I just want my custom button on that page.Any help would be appreciated -
how to redirect to admin/login url after admin password reset in django
In the project urls.py i have set these password reset url for forgot password.These url works fine .it resets the password but after reset completed in the login link , the login link redirects to the accounts/login url instead of admin/login url.How to redirect to admin/login url ?? urls.py path( 'admin/password_reset/', auth_views.PasswordResetView.as_view(), name='admin_password_reset', ), path( 'admin/password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done', ), path( 'reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm', ), path( 'reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete', ), path('admin/', admin.site.urls), -
How to set the jwt token?
I have two separate but dependent django projects, let's say A and B. B has multiple microservices. I login into A and then login into B-microservices before calling its apis. In case of successful login to A, I create a JWT and store it in the form of a cookie. I can use this cookie for authorization of requests. I want to use the same JWT for B, for Token Authentication. How do I implement this? Is there a way to send the token to these microservices(In the form of a header or something)? -
``Variable Variable`` in django template
view.py name = 'John' variable_name = name In such case, is it possible to use Variable Variable like PHP? I know it might be not a good practice, but sometimes it could provide very powerful features. Thanks. -
Multistage build with docker from multiple sources
I have a django project with different applications and I am trying to build a docker image for every single app. However in development I want a docker image to contain the whole project. I was using some multistage before to handle dev dependencies. Is there any way to achieve the following in a different way? FROM python:3.7-stretch AS base RUN pip install -r /projectdir/requirements.txt FROM base AS app1 RUN pip install -r /projectdir/app1/requirements.txt FROM base AS app2 RUN pip install -r /projectdir/app2/requirements.txt FROM app1, app2 AS dev RUN pip install -r /projectdir/requirements_dev.txt -
How to get list of timezone with time difference in django
I am using Django for one of my apps and I have hardcoded TIME ZONE list something like this:- TIMEZONE_CHOICES = ( ("<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>", "<DstTzInfo 'Africa/Abidjan' LMT-1 day, 23:44:00 STD>"), ("<DstTzInfo 'Africa/Accra' LMT-1 day, 23:59:00 STD>", "<DstTzInfo 'Africa/Accra' LMT-1 day, 23:59:00 STD>"),.....) I know that I can use pytz library to get a list of all timezones like this pytz.all_timezones_set. Its output is like: LazySet({'America/Argentina/La_Rioja', 'America/Campo_Grande', 'America/Winnipeg', ......) I need the time difference with the name of timezone as well. How can I do that? -
How to process Ajax Data in Python (Django)
I want to push front end data (Form inputs) to the server via Ajax. For this, I created an Ajax post request but I'm very unsteady... At my first attemps, I constantly receive errors by python Ajax call: //Get journey time for the stated address jQuery.ajax({ type: 'post', url: 'http://127.0.0.1:8000/termin/get-journey-time/', data: { 'method': 'get_journey_time', 'mandant_id': 1, 'customer_address': customer_address, 'staff_group': staff_group_id }, error: function (jqXHR, textStatus, errorThrown) { console.log("Error") }, timeout: 120000, }); I've created a view in Python, in which I want to do something (views.py) class get_journey_time(generics.ListAPIView): """ Handle Ajax Post to calculate the journey time to customer for the selected staff group """ permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): print(request) In my url route file I have this code lines (urls.py) urlpatterns = [ XXXXXXXXXXXXXXXXXXXXXXXXX, path('termin/get-journey-time/', views.get_journey_time.as_view()), XXXXXXXXXXXXXXXXXXXXXXXXX, XXXXXXXXXXXXXXXXXXXXXXXXX, ] I got the Error code 500: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` Is there a mistake in my approach, did I miss anything or is it completely crap? -
How can I do a query using Django but with more filters and update?
I know that to do a query using Django I have to do this : MyModel.objects.filter(pk=some_value).update(field1='some value') But if I have more values about the filter and the update does this work ? MyModel.objects.filter(pk=some_value, pk1=some_value1).update(field1='some value', field2='some value2') Thank you ! -
Issue while populating data from jquery success to modal
I have a function that uses ajax request to fetch data from a view and returns data in the form of a list that is in the model. Now in my model, the data is entered with a new line character, however in my jquery output the \n character is ignored , can anyone help ? Data in Model object: ankit: Hi govind! (then a new line ) go358938: Hi Ankit, how are you ? Data passed as list to jquery: {'list': 'ankit: Hi govind!\r\ngo358938: Hi Ankit, how are you ?'} Data visible in Modal : ankit: Hi govind! go358938: Hi Ankit, how are you ? Function: <script> $('#chatbox').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) var recipient = button.data('whatever') $.ajax({ url: "{% url 'fetcher' %}", data: { 'search': recipient }, dataType: 'json', success: function (data) { list = data.list; $('#chatbox').find('.modal-body').html(list); } }); }); </script> Views.py def fetcher(request): if request.is_ajax(): name = User.objects.get(username=request.GET.get('search', None)) b = ChatMessage.objects.get(user2 = name) print(b.message) data = { 'list': b.message, } return JsonResponse(data) -
RawQuerySet - Alias table columns are not coming in response
Here is the code query = 'SELECT policy_agreement.*, policy.* from policy_agreement INNER JOIN policy ON policy_agreement.policy_id=policy.id WHERE policy.policy_parent_id IN (12,16,18,46) AND status=1' policy_agreements = list(PolicyAgreement.objects.raw(query)) I'm getting the columns only in policy_agreement table, not getting columns of policy table. Thanks in advance. -
My user is not saving to a group - Django
There is my Form Code: enter image description here enter image description here And There is my View Code: enter image description here -
Django form action "." reloads same page with missing slug
I'm following a basic tutorial which adds commenting to a blog post detail page. I am navigating to the detail page with the absolute_url method and it works perfectly fine. def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) Here is a sample url created by the get_absolute_url http://localhost:8000/blog/2019/5/2/second-post However, when I submit the form within the detail page with the action=".", it only returns the date parameters and missing the slug part. <form action="." method="post"> {% csrf_token %} {{ comment_form.as_p }} <p><input type="submit" value="Add comment"></p> </form> Here is the returned url http://localhost:8000/blog/2019/5/2/ adding action="{{ post.get_absolute_url }}" seems to solve the problem but the book I am following Django 2 By Example tells it should just work fine with action="." I'm new to Django and Development so thank you for your help and understanding if the question is noob in any way :)