Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detect mobile devices with Django and Python 3
I am struggling to find an easy way to detect if the request comes from a mobile device in my Django views. I am trying to implement something like this: #views.py def myfunction(request): ... if request.mobile: is_mobile = True else: is_mobile = False context = { ... , 'is_mobile': is_mobile, } return render(request, 'mytemplate.html', context) And in mytemplate.html: {% if is_mobile %} show something {% else %} show something else {% endif %} Everywhere I checked (for instance here or here), minidetector is recommended. I have installed different versions: pip install minidetector, pip install minidetector2, as well as directly a couple of github repositories, but from all of them I get different sort of errors such as AttributeError: 'dict' object has no attribute 'has_key', which seems to be because I am using Python 3 and minidetector is not compatible with it. So here my question: Is there any version/fork of minidetector that is compatible with Python 3? If not, what are the alternatives? -
django function doesn't return HttpResponse
this is a long one! Sorry in advnace for the long code! So I have this function, which does something. A little explain:: Depending on what the user chooses the function either returns a form(so he can choose some extra stuff) or an HttpResponse. Now ,regarding choices: If the user chooses 3 or 4 it opens the form it's supposed to open. If the user chooses 1 or 2 ,a jquery confirm dialog window pops up and if the user confirms it's supposed to reload the page. Which it doesn't!! I am guessing it is an identation error..I have tried some alterations, but nothing. I am displaying below the structure of my function. I didn't put the actual function because I don't have a problem with if the function works correctly or not. The function does indeed what it is supposed to do, even if the choice is 1 or 2(if I hit refresh after I hit confirm in the jquery dialog, it has indeed performed the action it was supposed to.) Oh I am coding in Python/Django. So what do you think? def myFunction(some args): a_var = a_value a_var1 = a_value2 #some other vars if choice == '3': template … -
How to comeback in calling function with response data in django?
I am designing add money to wallet application, in that i am transferring money one wallet to another wallet but if my account balance is insufficient than transfer amount,then i am redirecting to add money function adding money to my wallet and after that i want to come back to taht function where i left before with response -
Django rest framework, serializer for reverse related field
I'd like to serialize one instance of reverse related instances. I have User and Seller. For each (user, seller) pair, there is single SellerCustomerInfo. and I want to retrieve and update this single seller_customer_info for a given user and seller. Here are my models class User(models.Model): pass class Seller(models.Model): pass class SellerCustomerInfo(models.Model): user = models.ForeignKey(User, related_name='seller_customer_infos') seller = models.ForeignKey(Seller) I'm serializing a user instance, and I also have a specific seller so that I can retieve single SellerCustomerInfo. class UserSerializer(serializers.ModelSerializer): seller_customer_info_read = serializers.SerializerMethodField() seller_customer_info_write = SellerCustomerInfoSerializer(write_only=True) class Meta: model = User fields = [ 'id', 'seller_customer_info_read', 'seller_customer_info_write', ] def get_seller_customer_info_read(self, obj): user = obj seller_id = self.context.get('seller_id') seller_customer_info = user.seller_customer_infos.get(seller=seller_id) return SellerCustomerInfoSerializer(seller_customer_info).data I have seller_customer_info_read and seller_customer_info_write because I don't know how I could unify them. Is there a way to do that? -
Filter for reverse relation that points to self in Q object
I want to filter the lookup in a reverse Foreignkey field to fields that do not have any reverse references. This is easily done: class MyBaseClass(models.Model): name = models.CharField(max_length=4) def block_filter(): return {'myreferenceclass__isnull': True} class MyReferenceClass(models.Model): mybase= models.ForeignKey(MyBaseClass, on_delete=models.CASCADE, limit_choices_to = block_filter) That works well if not for that if I want to update an instance of the MyReferenceClass I cannot save it (in the admin) as the referred object is not in the lookup. So the field is empty though it has already a value in the database. Now I want to use a Q object that filters is_null=True plus the entry that refers to self. However, I am stuck with the latter. Can I do this in the Q object? -
Django: Login banner in my site
I am coding my first django site. I'd like to include a login banner on my whole site that will be turned off in case user is authenticated and logged in. For instance, if I connect to /video url, if user is not connected, banner will either prompt a login form or a message telling user is logged. How to proceed in an optimal way: for each view called by an url I should test whether user is logged in and then render accordingly the template? Should I instanciate the login form in those views? OR should I use builtin auth module and add decorator for each view? In this case how to include login form inside my banner? OR something merging previous ideas OR something else? It is a newbie question, but I have read a lot of documentation and could'nt figure out clearly how to do it! Thx for your answers! -
I there any way to find from whre this get rquest comingin Django
TemplateDoesNotExist at /quiz/simple_admin/delete/1/ quiz/question_confirm_delete.html Request Method: GET Request URL: http://127.0.0.1:8000/quiz/simple_admin/delete/1/ Django Version: 1.10.5 Exception Type: TemplateDoesNotExist Exception Value: quiz/question_confirm_delete.html Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loader.py in select_template, line 53 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/user/django/qsystem', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Thu, 16 Feb 2017 10:19:40 +0000 My forms only consist of post request and I am getting an error TemplateDoesNotExist at /quiz/simple_admin/delete/1/ that may arising due to get request.I want to know from which form is producing this get request. Is there anyway? Thankyou -
Using a variable from ManyToMany as fields in UpdateView Django 1.10
The models which I have defined consist of RestaurantFeature which has a many-to-many relationship defined with RestaurantServing. The code of my models.py: class RestaurantServing(models.Model): name = models.TextField(default="") class RestaurantFeature(models.Model): location = models.OneToOneField( Location, on_delete = models.CASCADE, primary_key = True, ) serving = models.ManyToManyField(RestaurantServing) I am now trying to implement and restaurantfeatures_edit page where the serving can be removed/added/selected ect. The views.py class based method I have written: class RestaurantFeatureEdit(UpdateView): template_name = 'Restaurants/restaurantfeature_edit.html' model = RestaurantFeature fields = ['name', ] success_url = '/restaurant' template_name_suffix = '_update_form' This code returns the error that Unknown field(s) (name) specified for RestaurantFeature... I already have tried fields = ['serving.name',] and adding the multiple models as model = RestaurantFeature, RestaurantServing. Could someone help me to get the name in my UpdateView? -
Django searches for a template in an unspecified location
In the base.html, <a href="/login">Log In</a> In the main urls.py, from ... from accounts.views import login_view, logout_view, register_view urlpatterns = [ ... url(r'^login/', login_view), .... ] In the accountsviews.py, def login_view (request): request.session.set_expiry(request.session.get_expiry_age()) form = UserLoginForm(request.POST or None) title = "Login" if form.is_valid() : username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request,user) return HttpResponseRedirect('/') return render(request, 'accounts/login_form.html',{ "form" : form, "title": title}) When the Log In is clicked, the login_form template is searched in 'registration/login.html' instead of 'accounts/login_form.html'. Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /Users/***/Desktop/django/mysite/personal/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/***/Desktop/django/mysite/blog/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/***/Desktop/django/mysite/landing/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/***/Desktop/django/mysite/accounts/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/crispy_forms/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/pagedown/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/markdown_deux/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/tracking/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/admin/templates/registration/login.html (Source does not exist) django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/auth/templates/registration/login.html (Source does not exist) All of this was working fine until I tried over-ridding registration/password_reset_form.html, registration/password_reset_done.html, registration/password_reset_confirm.html, registration/password_reset_complete.html to achieve password reset functionality. The main urls.py had included, url(r'^user/password/reset/$','django.contrib.auth.views.password_reset',{'post_reset_redirect' : '/user/password/reset/done/'},name="password_reset"), url(r'^user/password/reset/done/$','django.contrib.auth.views.password_reset_done'), url(r'^user/password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$','django.contrib.auth.views.password_reset_confirm',{'post_reset_redirect' : '/user/password/done/'}), url(r'^user/password/done/$','django.contrib.auth.views.password_reset_complete'), Any suggestions ? Thanks ! -
bootstrap modal is shown in background
I am trying to add modal to the html page, But unable to bring modal to the front, I've copied bootstrap sample code. Also i tried to keep JSFiddle, Although it's working in JSFiddle, Not in my program. so it's better to show the whole code. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> It should work like this but, in my code this type output will be produced... Image link Hope for help... -
Django urlconf fails to resolve valid regex
I'm experiencing problems in routing urls to views in Django. Specifically, I use URLs with the pattern: url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetables$', views.compiledata, name='compiledata') An example url would be My data/current/managetables. I checked that the regex returns the expected captured groups on www.pyregex.com (http://www.pyregex.com/?id=eyJyZWdleCI6Il4oP1A8aWQ%2BW0EtWmEtejAtOVxcIF0rKS8oP1A8c3ViaWQ%2BW0EtWmEtejAtOVxcIF0rKS9tYW5hZ2V0YWJsZXMkIiwiZmxhZ3MiOjAsIm1hdGNoX3R5cGUiOiJtYXRjaCIsInRlc3Rfc3RyaW5nIjoiTXkgRGF0YS9jdXJyZW50L21hbmFnZXRhYmxlcyJ9) However, actually visiting the url does not result in the view being called. Most importantly though, it works for a highly similar url: url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetab$', views.compiledata, name='compiledata') If I visit My data/current/managetab the view is called as expected. Additionally, appending a "/" in the urlconf works also - but it is not clear to me why, i.e.: url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetables/$', views.compiledata, name='compiledata') and visiting My data/current/managetablesresults in a redirect to My data/current/managetables/which calls the view. I appreciate any hints how to solve this issue. -
Template for reusable app is not rendering
I have a separate app, and I'd like to render its template. urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^guestbook/', include('guestbook.urls', namespace='guestbook', app_name='guestbook')) ] guestbook/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] guestbook/views.py def index(request): entries = Entry.objects.all().order_by('-date') return render(request, 'guestbook/index.html', {'entries': entries}) templates/guestbook/index.html {% extends 'guestbook/base.html' %} {% block content %} <a href="{% url 'guestbook:add_comment' entry.pk %}">Comment</a></span> {% endblock %} But I'm getting error: Error during template rendering In template /Users/bulrathi/Yandex.Disk.localized/Learning/Code/Test tasks/myproject/templates/guestbook/index.html, error at line 27 Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 27 <span class="meta-chunk"><a href="{% url 'guestbook:add_comment' entry.pk %}">Комментировать</a></span> I'll be so grateful for advice. -
how can I create this kind of filter box for a certain field in admin pages? django
let's say I have an employee model with the field username which can be selected. Usually in admin > employee page, we will see a dropdown of a list of employee username but instead of doing that, is it possible to have like a select list and on top of that there's a filter so it'll be easier to find what is needed instead of scrolling through the whole dropdown if there are like hundreds.... an example of what I want is like this.... so in the box it'll be like list of the employee's name so I can click and choose whichever needed and also use filter to find the username. this image is actually cropped from admin > users Thanks in advance for any suggestions. -
How to change string to html format?
I develop a django project. I want to show output string on html. My view is : def strategy_run(request): output = "hello world!\nstring test" return render_to_response('strategy_run.html', locals()) My strategy_run.html is: <!DOCTYPE html> <html lang="en"> <body> {{output}} </body> </html> But I want the html showing like: hello world! string test Their html might be "hello world!<br>string test". So How to change string to html format? Is there a python or django function for changing the format? Thank you. -
django 'LineChart' object has no attribute 'get'
I am trying to make a line chart in django, I am using the jchart module, When I try and load the chart I get the below error. error 'LineChart' object has no attribute 'get' view from jchart import Chart from jchart.config import Axes, DataSet, rgba class LineChart(Chart): chart_type = 'line' responsive = False scales = { 'xAxes': [Axes(type='time', position='bottom')], } def get_datasets(self, **kwargs): data = [{'y': 0, 'x': '2017-01-02T00:00:00'}, {'y': 1, 'x': '2017-01-03T00:00:00'}, {'y': 4, 'x': '2017-01-04T00:00:00'}, {'y': 9, 'x': '2017-01-05T00:00:00'}, {'y': 16, 'x': '2017-01-06T00:00:00'}, {'y': 25, 'x': '2017-01-07T00:00:00'}, {'y': 36, 'x': '2017-01-08T00:00:00'}, {'y': 49, 'x': '2017-01-09T00:00:00'}, {'y': 64, 'x': '2017-01-10T00:00:00'}, {'y': 81, 'x': '2017-01-11T00:00:00'}, {'y': 100, 'x': '2017-01-12T00:00:00'}, {'y': 121, 'x': '2017-01-13T00:00:00'}, {'y': 144, 'x': '2017-01-14T00:00:00'}, {'y': 169, 'x': '2017-01-15T00:00:00'}, {'y': 196, 'x': '2017-01-16T00:00:00'}, {'y': 225, 'x': '2017-01-17T00:00:00'}, {'y': 256, 'x': '2017-01-18T00:00:00'}, {'y': 289, 'x': '2017-01-19T00:00:00'}, {'y': 324, 'x': '2017-01-20T00:00:00'}, {'y': 361, 'x': '2017-01-21T00:00:00'}, {'y': 400, 'x': '2017-01-22T00:00:00'}, {'y': 441, 'x': '2017-01-23T00:00:00'}, {'y': 484, 'x': '2017-01-24T00:00:00'}, {'y': 529, 'x': '2017-01-25T00:00:00'}, {'y': 576, 'x': '2017-01-26T00:00:00'}, {'y': 625, 'x': '2017-01-27T00:00:00'}, {'y': 676, 'x': '2017-01-28T00:00:00'}, {'y': 729, 'x': '2017-01-29T00:00:00'}, {'y': 784, 'x': '2017-01-30T00:00:00'}, {'y': 841, 'x': '2017-01-31T00:00:00'}, {'y': 900, 'x': '2017-02-01T00:00:00'}] return [DataSet( type='line', label='Time Series', data=data, )] def some_view(request): render(request, … -
django-user-accounts and anymail: Invalid email address format
I have set up django-user-accounts. When I try to use the password reset function and type in a valid email address I get the following error: AnymailInvalidAddress at /account/password_reset/ Invalid email address format '': No email found This is the full traceback: Request Method: POST Request URL: http://127.0.0.1:8000/account/password_reset/ Django Version: 1.10.5 Python Version: 3.5.2 Traceback: File "C:\Anaconda3\lib\site-packages\anymail\utils.py" in __init__ 120. raise ValueError('No email found') During handling of the above exception (No email found), another exception occurred: File "C:\Anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Anaconda3\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Anaconda3\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Anaconda3\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "C:\Anaconda3\lib\site-packages\account\views.py" in form_valid 582. self.send_email(form.cleaned_data["email"]) File "C:\Anaconda3\lib\site-packages\account\views.py" in send_email 608. hookset.send_password_reset_email([user.email], ctx) File "C:\Anaconda3\lib\site-packages\account\hooks.py" in send_password_reset_email 33. send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, to) File "C:\Anaconda3\lib\site-packages\django\core\mail\__init__.py" in send_mail 62. return mail.send() File "C:\Anaconda3\lib\site-packages\django\core\mail\message.py" in send 342. return self.get_connection(fail_silently).send_messages([self]) File "C:\Anaconda3\lib\site-packages\anymail\backends\base.py" in send_messages 87. sent = self._send(message) File "C:\Anaconda3\lib\site-packages\anymail\backends\base_requests.py" in _send 56. return super(AnymailRequestsBackend, self)._send(message) File "C:\Anaconda3\lib\site-packages\anymail\backends\base.py" in _send 116. payload = self.build_message_payload(message, self.send_defaults) File "C:\Anaconda3\lib\site-packages\anymail\backends\mailgun.py" in … -
How do this please
I'm a new in dango, please I have a question if you can help me, I have a code python for the mobility for 2 point X,Y and I want to apply it on my django project, more specifically, to recover it in my map, knowing that I get the marker position (X, Y) with rest API. And I have already add the python file of the mobility in django project Please help me I have a deadline for tomorrow. Thank you in advanceenter image description here enter image description here -
Celery - Read unstructured message from queue
I'm writing a Django application and I want to read messages from rabbitMQ and apply some changes into my database. My problem is the producer in not using celery and I get an error from celery because the message is invalid. The error is: [2017-02-16 08:31:11,416: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!? The full contents of the message body was: body: {'value': '4', 'type': 'edit', 'rate': 1} (39b) How can I handle it? I have also tried kombu but the problem is it's not as easy as celery; It doesn't work in the background so it is hard to be integrated with Django app. -
Django: relation does not exist
I have pulled myproject updates from bitbucket and tried following commands 'python3 manage.py makemigrations', 'python3 manage.py migrate vehicle', 'python3 manage.py migrate'. But I am getting the following error. vehicle app is new and some of its models use foreign keys from other apps which were migrated before and are in database. I tried different ways, but cannot find the solution. I am using django-1.7.4 I appreciate any advice. return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/apps/tulpor/beta/apps/site/admin.py", line 7, in from .forms import MenuSubItemAdminForm, MenuChildrenAdminForm File "/apps/tulpor/beta/apps/site/forms.py", line 18, in class AdvancedVehicleSearchForm(forms.Form): File "/apps/tulpor/beta/apps/site/forms.py", line 24, in AdvancedVehicleSearchForm make_choices = [(make.id, '{} ({})'.format(make.name, make.stock_count)) for make in Make.objects.get_public().filter(stock_count__gt=0)] File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/models/query.py", line 141, in iter self._fetch_all() File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/models/query.py", line 966, in _fetch_all self._result_cache = list(self.iterator()) File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/models/query.py", line 265, in iterator for row in compiler.results_iter(): File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter for rows in self.execute_sql(MULTI): File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/backends/utils.py", line 81, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/apps/tulpor/.virtualenvs/beta/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in … -
Padding command doesn't work with html2pdf landscape format
I'm working with html2pdf in order to generate PDF from Django template file and I get a problem when I'm using padding-left and padding-right in order to make spaces between border and elements. My PDF (just the above part) looks like : My PDF is in landscape format and I wrote this script to do what I want : <html> <head> {% load staticfiles %} <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'css/BC_base.css' %}"/> <style> body { font-family: Courier New, Courier, monospace; list-style-type: none; } #upp { width: 100%; } .alignleft, .alignright { display: inline-block; } .alignleft { padding-left : 1000px; } .alignright { padding-right: 100px; } .title { border-top: 150px; font-size: 7; } {% block style %} @page { size: landscape; } {% endblock %} </style> </head> <h2 class = "title" align="center" > ATTESTATION DE RECENSEMENT </align> </h2> <table id="upp"> <tr> <td> <p class="alignleft">Le maire de la commune <br />de {{mairie.city}}</p> </td> <td></td> <td align="right"> <p class="alignright">Imprimé n° {{ar.id}}<br/> Loi n° ... du XX XX XXXX</p> </td> </tr> </table> <br></br> <br></br> I don't overcome to put spaces as I described above. Then, I would like to put a rectangle all around and I get the same … -
State sharing and deletion in model inheritance
I have a Django 1.6 model structure where instances share a common model instance as a subclass. In database terms, there is a row for A a row for B and a row for C using the parent_link for ids. When calling .delete() on C' the row for A and C is deleted but there is an orphan record for B. Instantiating A directly and calling delete will cascade the delete to B and C instances. How can I, in the simplest way, ensure deleting an instance of B or C will delete both the parent and sibling state? Deleting an instance of A causes linked instances of B and C to be deleted. Deletion of B causes B and A deletion. Deletion of C causes C and A deletion. How can I have it such that deletion of any A, B or C instance deletes all other instances regardless of the instance delete() is being called on? Here's the classes: class A(models.Model): # Fields here class B(A): a_ptr = models.OneToOneField(A, parent_link=True) # More fields class C(A): a_ptr = models.OneToOneField(A, parent_link=True) # More fields # Code shared_state = A() shared_state.save() sharer_b = B(a_ptr=shared_state.id) charer_c = C(a_ptr=shared_state.id) sharer_b.save() sharer_c.save() # Objective, … -
how can I recreate the user permissions box in admin page? django
Image would be a lot easier to tell what I want to do. I want to reproduce this in another model so I don't have to keep on using dropdown boxes when there are hundreds of selections. Anyone has any idea? Thanks in advance -
How to add a python element directly to a <img> HTML element?
guys. i heave a little issue, that i'm not able to decide myself. I'm using Django and trying to add this Python code: {{ question.question_logo }} that means "1", into HTML element this way: <img id = image src ="{% static "polls/images/question_logos/{{ question.question_logo }}.jpg"%}/> To check myself i tried: <img id = image src ="{% static "polls/images/question_logos/1.jpg" %}"/> <h1>{{ question.question_logo }}</h1> It works perfectly I need to let HTML know somehow, that {{ question.question_logo }} is not a raw part of a link Thank's for your time -
How to change template based on user authentication in django
If user successfully login i need to show one template. if user not login i need to show another template. I created two templates one is base.html another one is base_login.html template. IF user successfully login i need to call base_login.html other wise base.html. i am using below to achieve this. it's not giving expected result. How do achieve this? {% if user.is_authenticated %} <p>Welcome {{ user.username }} !!!</p> {% extends "base_login.html" %} {% else %} {% extends "base.html" %} {% endif %} -
How to Extract Dates in DateRangeField in Django
I'm trying to extract the dates in the DateRange field in django. I'm trying to see if a date is within the range of that DateRange but I'm unable to extract the dates in DateRange. Here's a sample: 'date_range': DateRange(datetime.date(2017, 2, 17), datetime.date(2017, 2, 18), '[)') So I'm trying to get the first date and the second date and check if a certain date is within that range of DateRange. How do I do that? Thanks!