Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form action
I just started with Django and already scratching my head, I have a simple form with action set to null, On submit it goes to a url which I cannot find since I have to put a condition there as to which url should it hit. template: {% extends 'base.html' %} {% block body_block %} <div class="container"> <div class=""> <h2>Education Details</h2> <form action="" method="post"> {{ form.as_p }} {% csrf_token %} <div class="d-flex justify-content-end"> {% if '/attorney-profile-wizard/additional-information/' not in request.META.HTTP_REFERER %} <a href="{% url "attorney_edit" url_key %}" class="material-button bg-red pl-2">Cancel</a> {% else%} <a href="/attorney-profile-wizard/additional-information/" class="material-button bg-red pl-2">Cancel</a> {% endif %} <!--<a href="{% url "attorney_edit" url_key %}"--> <!--class="material-button bg-red pl-2">Cancel</a>--> <input type="submit" class="material-button" name="" value="Save Education"> </div> </form> </div> </div> {% endblock %} Model: class Education(models.Model): degree = models.CharField(max_length=256) school_name = models.CharField(max_length=256) accolades = models.TextField(null=True) start_year = models.IntegerField(blank=True, null=True) end_year = models.IntegerField(blank=True, null=True) is_law_school = models.BooleanField(default=False) position = models.PositiveSmallIntegerField(blank=True, null=True) attorney = models.ForeignKey(AttorneyProfile, related_name='educations') created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-id'] def __str__(self): return '{} - {}'.format(self.attorney, self.degree) views.py class AttorneyEducationEditMixin(AttorneyEducationMixin, AttorneyEditMixin): form_class = EducationForm template_name = 'attorney/education/form.html' class EducationCreateView(AttorneyEducationEditMixin, CreateView): permission_required = 'educations.add_education' class EducationUpdateView(AttorneyEducationEditMixin, EducationPermissionMixin, UpdateView): permission_required = 'educations.change_education' class EducationDeleteView(AttorneyEducationMixin, EducationPermissionMixin, DeleteView): template_name = "attorney/shared/title_delete.html" … -
django foreign key Cannot assign must be a instance
I am developing a web app using Django. I have created the table in MySQL database and then generated the models.py using inspectdb. I am able to fetch details and connect to the database without any issues. But while saving the values to the particular table, below error is shown sav_list = List(id=4, item_name ='name1', item_desc='desc1', location='location', reason='rfp', pid=3) Cannot assign "3": "List.id" must be a "Order" instance. my models class List(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. item_name = models.CharField(db_column='Item_Name', max_length=255) # Field name made lowercase. item_desc = models.CharField(db_column='Item_Desc', max_length=300) # Field name made lowercase. location = models.CharField(db_column='Location', max_length=100, blank=True, null=True) # Field name made lowercase. reason = models.CharField(db_column='Reason', max_length=100, blank=True, null=True) # Field name made lowercase. pid = models.ForeignKey('Order', models.DO_NOTHING, db_column='PID') # Field name made lowercase. class Order(models.Model): poid = models.IntegerField(db_column='POID', primary_key=True) # Field name made lowercase. po = models.CharField(db_column='PO', unique=True, max_length=20) # Field name made lowercase. quote = models.CharField(db_column='Quote', unique=True, max_length=20) # Field name made lowercase. condition = models.CharField(db_column='Condition', max_length=15) # Field name made lowercase. I have tried relate_name for foreign key but still same behaviour. Same values can be stored on database without any issues. Only Django throws an error. Please someone help … -
multiple image upload with one form for django admin
I want to upload multiple images with one form i think i have somewhere problem here is my view def home(request): if request.method == 'POST': form = DocumentForm(request.POST) files = DocumentForm(request.FILES.getlist('photo')) if form.is_valid(): for f in files: f.save() return render(request , 'core/home.html') else: form = DocumentForm() return render(request, 'core/home.html', { 'form': form }) model.py : class Document(models.Model): title = models.CharField(max_length = 150 ) photo = models.FileField(upload_to= 'media') def __str__(self): return self.title form.py : class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('title', 'photo', ) widgets={"photo":forms.FileInput(attrs={'id':'files','required':True,'multiple':True})} -
Showing listview and detailview in the same template using forloops in Django
I would like to add some Order details(DetailView) in the Order history page(ListView), See image example below ( I have made the image on photoshop). I was able to get the grey part (order list to show) But I am not able to get the item details to show in this page correctly. If I click View Order Detail it goes to detail page where I can show all this. But I need a small summary in the ListPage too. See example below. How do I change my views or templates to achieve this? See my views and templates below Below is how I need my order history page to look like Below are my my models.py class Order(models.Model): token = models.CharField(max_length=250, blank=True) total = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='USD Order Total') emailAddress = models.EmailField(max_length=100, blank=True, verbose_name='Email Address') created = models.DateTimeField(auto_now_add=True) billingName = models.CharField(max_length=350, blank=True) billingAddress1 = models.CharField(max_length=350, blank=True) billingCity = models.CharField(max_length=100, blank=True) billingZipcode = models.CharField(max_length=10, blank=True) billingCountry = models.CharField(max_length=50, blank=True) class OrderItem(models.Model): product = models.CharField(max_length=250) quantity = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='USD Price') order = models.ForeignKey(Order, on_delete=models.CASCADE) image = models.ImageField() Below is my template {% block body %} <div> <div class="text-center"> <br/> <h1 class="text-center my_title">Order Purchase History</h1> <br/> {% if … -
django View Model.py Field via View.py
I have a model.py that link 3 Classes to a USER class Organization_Information(models.Model): Organization_name = models.CharField(max_length=25) Organization_address = models.CharField(max_length=40) Organization_admin = models.OneToOneField(MyUser, on_delete=models.CASCADE, null=True, blank=True) class Project(models.Model): project_name = models.CharField(max_length= 25, default='') organisation_name = models.ForeignKey('Organization_Information', on_delete=models.CASCADE) class Project(models.Model): project_name = models.CharField(max_length= 25, default='') organisation_name = models.ForeignKey('Organization_Information', on_delete=models.CASCADE) class Asset(models.Model): asset_note = models.TextField(default='',) project_name = models.ForeignKey('Project', on_delete=models.CASCADE) Each Instance of a Class refer to the above, And the First Refer to the USER"MyUser" custom model. I got Stuck on the View I tried re-reading it and figuring it out But I got Stuck. Almost All the "walk-through" tutorial and explanation are old and invalid. Using "Django==2.0.7 - Python3.6" All I want is to display the model Fields into the Views.py and their child for e.g: MyUser ID = 3, and The Organization_Information refer to it By the ID, I want to display all the Information from The User Information to the Assets Information to be viewed depending on the user ID when He/She Login. I tried to user Query-set But it didn't work as desired is their any simple solution. Thank you. -
how to pass a list of numbers in URL Django
I want to pass a list through the url in GET method. Like I have a URL http://127.0.0.1:8000/api/modeling/emp_id/ here is my regex in django url(r'^emp_id/(?P<emp_id>[\w\d@\.-]+)/$', ModelingView.as_view(), name='model-res'), and I want to pass a emp_id list like [123,456,789,121,432] is there any way to do it. -
git init shows fatal: unable to access
I'm new to git, and while creating new repository with command: git init Im getting an error: fatal: unable to access 'C:\Users\mubee;C:\Program Files (x86)\graphviz-2.40.1;/.config/git/config': Invalid argument I have no idea how to resolve this, i have installed a 'python-git-package'. Any help would be appreciated. Thanks -
Speed up django rest framework gui performance
When i open my list API in browser using .json at the end of url(like http://server/api/staff-list.json) it works very fast, but when i try to open it without .json it sometimes throw 504 error. I think the reason in rendering filters(there are a lot of them). Is there a way to speed up DRF template rendering? -
Heroku deploy fails while installing dependencies with Pipenv
I am trying to deploy my Django app on Heroku, I have specified Pipfile, requirements.txt but while installing the dependencies on heroku through Pipenv I get this error `remote: selective_upgrade=selective_upgrade, remote: File "/app/.heroku/python/lib/python2.7/site-packages/pipenv/core.py", line 1785, in do_install remote: pre = project.settings.get('allow_prereleases') remote: File "/app/.heroku/python/lib/python2.7/site-packages/pipenv/project.py", line 446, in settings remote: return self.parsed_pipfile.get('pipenv', {}) remote: File "/app/.heroku/python/lib/python2.7/site-packages/pipenv/project.py", line 392, in parsed_pipfile remote: parsed = self._parse_pipfile(contents) remote: File "/app/.heroku/python/lib/python2.7/site-packages/pipenv/project.py", line 441, in _parse_pipfile remote: return toml.loads(contents) remote: File "/tmp/build_cc0ee874a65b17c85d752f621d489ad2/.heroku/python/lib/python2.7/site-packages/pipenv/vendor/toml.py", line 176, in loads remote: item + "'. Try quoting the key name.") remote: toml.TomlDecodeError: Found invalid character in key name: ':'. Try quoting the key name. remote: /app/.heroku/python/lib/python2.7/site-packages/pipenv/_compat.py:86: ResourceWarning: Implicitly cleaning up <TemporaryDirectory '/tmp/pipenv-IB9dWl-requirements'> remote: warnings.warn(warn_message, ResourceWarning) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to demo-bpstash. remote: To https://git.heroku.com/demo-bpstash.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/demo-bpstash.git' ` -
Select related on 3 tables in Django ORM
I need some help to perform a select_related in Django framework. My model is: models.py class Richiesta(models.Model): # TIPOLOGIE_DISPOSITIVO can be = BK or SC codice = models.CharField(max_length=20, null=True, blank=True, unique=True) ufficio_registrazione = models.ForeignKey(UfficioRegistrazione, null=True, blank=False) tipologia = models.CharField(max_length=50, null=False, blank=False, choices=TIPOLOGIE_DISPOSITIVO, default=TIPOLOGIE_DISPOSITIVO[0][0]) tipo = models.IntegerField(null=False, blank=False, choices=TIPO_CHOICES, default=TIPO_PRIMO_RILASCIO) data_produzione = models.DateTimeField(null=True, blank=True) class UfficioRegistrazione(models.Model): cliente = models.ForeignKey(Cliente, null=False, blank=False) class Cliente(models.Model): # provider can be = 1 or 2 denominazione = models.CharField(max_length=100, null=False, blank=False) codice_cliente = models.PositiveIntegerField(null=False, blank=False, db_index=True) provider = models.IntegerField(null=False, blank=False, choices=PROVIDER_CHOICES) and there is the raw sql query I need to perform with Django ORM: select cms_richiesta.id, cms_richiesta.tipologia, cms_richiesta.data_produzione, cms_richiesta.ufficio_registrazione_id, cms_ufficioregistrazione.id, cms_ufficioregistrazione.cliente_id, cms_cliente.id, cms_cliente.provider, cms_cliente.denominazione, cms_cliente.codice_cliente from cms_richiesta INNER JOIN cms_ufficioregistrazione on cms_richiesta.ufficio_registrazione_id=cms_ufficioregistrazione.id INNER JOIN cms_cliente on cms_ufficioregistrazione.cliente_id = cms_cliente.id where data_produzione>'2011-01-01' and data_produzione<'2017- 12-31' and cms_cliente.provider = 2 and cms_richiesta.tipologia='BK' can someone help me? -
django modelAdmin displayed title
I am new to django. I have the following codes: model: class MyUser(AbstractUser): profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) My profile model contains only some personal fields like full_name, gender, birthdate, etc. admin: class MyUserInline(admin.StackedInline): model = MyUser exclude = ('first_name', 'last_name', 'username', 'plan', 'password') fieldsets = ( (_('Personal info'), {'fields': ('email',)}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser def clean_password(self): return "" class ProfileAdmin(admin.ModelAdmin): inlines = (MyUserInline,) change_user_password_template = None form = MyUserChangeForm change_password_form = AdminPasswordChangeForm ordering = ('myuser__email',) def save_model(self, request, obj, form, change): obj.myuser.username = obj.myuser.email obj.save() list_display = ('full_name', 'myuser_email', 'myuser_is_staff', 'myuser_is_superuser', 'myuser_is_active') def user_change_password(self, request, id, form_url=''): if not self.has_change_permission(request): raise PermissionDenied user = self.get_object(request, unquote(id)) if user is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(self.model._meta.verbose_name), 'key': escape(id), }) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() # rest of method # other minor methods The problems are: In recent actions or after editing a user, I see Profile Object instead of username or email. enter image description here I cannot change user password, at first the change password page doesn't open … -
Django - how to send mail 5 days before event?
I'm Junior Django Dev. Got my first project. Doing quite well but senior dev that teaches me went on vacations.... I have a Task in my company to create a function that will remind all people in specyfic Group, 5 days before event by sending mail. There is a TournamentModel that contains a tournament_start_date for instance '10.08.2018'. Player can join tournament, when he does he joins django group "Registered". I have to create a function (job?) that will check tournament_start_date and if tournament begins in 5 days, this function will send emails to all people in "Registered" Group... automatically. How can I do this? What should I use? How to run it and it will automatically check? I'm learning python/django for few months... but I meet jobs fot the first time ;/ I will appreciate any help. -
Django, scrapping: What's the best way to detect "changes" while scrapping?
This is not typical code problem, instead, it's a design problem I'm facing right now. Let's say I do have a webpage (which is not mine), and I'd like to scrap a few pieces of information. Most important information, for me, would be when (datetime) character logged in, and when he logged off, but I collect other information as well. Login is known from point 2(see below), but logout i have to calculate I can access 2 pages: http://x/online.php - It gives me list of online nicknames (200 - 500 entries) http://x/character.php?name=nickname - it gives me details of each nickname like: Character name, Guild, Sex, Level, Class (Vocation), Status (offline/online), Last login. I make only 2 "operations" in tasks.py which are: A - update_or_create using information from point "2" B - Get online list - using information from point "1" So, how it works now is (each minute, thanks to Celery, I do this): Set transaction autocommit to False Do A for characters, that have login registry, but does not have logout (From database point they are still "online") If at this point character's status is "OFFLINE", add database entry to logout as datetime.now Do A for characters from list … -
how to call a class based template tag from views.py in Django?
CoinbaseWalletAuth.py from django import template register = template.Library() API_KEY = '******************' API_SECRET = '***************' class CoinbaseWalletAuth(AuthBase): def __init__(self, api_key, secret_key): self.api_key = api_key self.secret_key = secret_key def __call__(self, request): timestamp = str(int(time.time())) message = timestamp + request.method + request.path_url + (request.body or '') signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest() request.headers.update({ 'CB-ACCESS-SIGN': signature, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': self.api_key, }) print('hello') return request register.tag('CoinbaseWalletAuth', CoinbaseWalletAuth(API_KEY,API_SECRET)) Views.py def test(request): if request.method == 'POST': api_url = 'https://api.coinbase.com/v2/' auth = CoinbaseWalletAuth # call the class based function in views(This is not working) r = requests.get(api_url + 'user', auth=auth) data= r.json() return HttpResponse(data) -
Django DetailView for two seperate queries / models
I have a working detailview for my orders and wanted to add another queryset(for model Entry) to it to be able to read out some more data to the user, that I don't have stored in the orders model. What will be the best way to attack that since both models share the same foreignkey Cart? I suppose something in the direction of: entry_obj = Entry.objects.filter(cart=Order.objects.cart)? But how to implement it into the detailview? url(r'^(?P<order_id>[0-9A-Za-z]+)/$', views.OrderDetailView.as_view(), name="detail"), class OrderDetailView(LoginRequiredMixin, DetailView): def get_object(self): qs = Order.objects.by_request( self.request ).filter(order_id = self.kwargs.get('order_id')) if qs.count() == 1: return qs.first() return Http404 Models.py class Entry(models.Model): product = models.ForeignKey(Product, null=True) cart = models.ForeignKey(Cart, null=True) fabric = models.ForeignKey(Fabric, null=True) quantity = models.PositiveIntegerField() Models.py class Order(models.Model): billing_profile = models.ForeignKey(BillingProfile, null=True, blank=True) order_id = models.CharField(max_length=120, blank=True) shipping_address= models.ForeignKey(Address, related_name="shipping_address", null=True, blank=True) cart = models.ForeignKey(Cart) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=100) active = models.BooleanField(default=True) Thanks for help! -
django query syntax error
I performed django raw query in celery..When I performed the query and tested it at other files it worked, i tested it at views file, but when i put in celery it got the error just like message above : django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from telegram_accounts a join subscriptions b on a.member_id = b.member_id join ' at line 1") Here is my query: raw_query = ( "select x.telegram_user_id, x.id,x.member_id, x.list_group, x.telegram_engagement_id, " "coalesce(y.count_list_group, 0) as count_list_group, x.count_telegram_engagement " "from " "( select a.telegram_user_id, d.id as telegram_engagement_id, a.id, a.member_id, " "d.list_group, count(d.id) as count_telegram_engagement " "from telegram_accounts a join subscriptions b " "on a.member_id = b.member_id join products c on b.product_id = c.id " "left join telegram_engagements d on a.id = d.telegram_account_id " "and d.chatroom_id = '%s' and d.engagement_time = '%s' " "where a.active = 'Active' " "and b.package_due > now() " "and c.product_type = 'core_product' " "and a.telegram_user_id is not null " "and (a.jasmine_status = '%s') " "group by " "a.telegram_user_id, d.id, a.id, a.member_id, " "a.jasmine_status, a.sophie_status, a.theo_status, d.list_group ) as x " "left join " "( … -
django-celery: bind=True fails, takes 2 positional arguments but 3 were given
I am trying to retry a celery task if it fails. This is my task, @shared_task(queue='es', bind=True, max_retries=3) def update_station_es_index(doc_id, doc_body): """ Celery consumer method for updating ES. """ try: #es_client is connecting to ElasticSearch es_client.update_stations(id=doc_id, body=doc_body) except Exception as e: self.retry(exc=e) But I get this error when this task is called, TypeError: update_station_es_index() takes 2 positional arguments but 3 were given I have not found enough help on the web for this error, just this github issue, but that does not explain much. Can anyone tell me what is happening and what is the solution here? Using Django2.0.5 and celery4.2.0 -
Django API returns 404 error but only 30% of the time. How to identify error in Docker setup?
I have a script that hits a simple API on all my servers every hour to ensure they are functioning properly. My newest server isn't using my normal stack, so I suspect I've configured it improperly. It is currently returning occasional 404 errors to the logging script. Server Config Ubuntu, Nginx, PostgreSQL, Supervisor; Running a Docker container with Django/Wagtail and Gunicorn. Looks fine when I visit in webbrowser, but my script logged four 404s in the last 12 hours. My supervisor log shows the 404s but doesn't provide any additional useful information: [2018-07-16 20:22:35 +0000] [9] [INFO] Booting worker with pid: 9 [2018-07-16 20:22:35 +0000] [10] [INFO] Booting worker with pid: 10 [2018-07-16 20:22:35 +0000] [11] [INFO] Booting worker with pid: 11 Not Found: /_server_health/ Not Found: /_server_health/ Not Found: /_server_health/ There is no relevant information captured in the Nginx log. Can anyone recommend any steps I can take to gather further information? Or does this fit the pattern of any known problematic server configs? -
Django error external IP on production server
On my production server I keep getting errors similar to this one [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 't17.proxy-checks.com:443'. You may need to add 't17.proxy-checks.com' to ALLOWED_HOSTS. I don't know why and how this error is coming. Should I ignore these error messages ? -
grouping objects by date range in Django
in models.py we have: class Company(models.Model): name = models.CharField(max_length = 60) def __str__(self): return self.name class Contract(models.Model): name = models.ForeignKey(Company, on_delete=models.CASCADE) date_start = modelsDateField(default=datetime.date.today) date_end = modelsDateField(default=datetime.date.today) price = models.DecimalField(max_digit=20, decimal_places=0) def __str__(self): return self.id in template I want to see the monthly table for the summed contract's prices. So for the contracts query set like: <QuerySet[ {'company__name': 'Nike', 'date_start': datetime.date(2010, 10, 1), 'date_end': datetime.date(2015, 7, 15), 'price': Decimal('100')}, {'company__name': 'Reebok', 'date_start': datetime.date(2008, 5, 1), 'date_end': datetime.date(2015, 2, 23), 'price': Decimal('100')} ] In template for selected year 2015 the data were like: jan feb mar apr may jun jul aug sep oct nov dec 200 200 100 100 100 100 100 0 0 0 0 0 since Nike's contract is valid through all month of 2015 and Reebok's contract only until July. Can smb help me with the view and template for this task? -
Nginx is serving uwsgi on socket only if it is first run on a random port
There is really something strange. My nginx is not serving django project on socket on uwsgi with proj.ini file. I run below command and it is not serving. uwsgi --ini /etc/uwsgi/sites/proj.ini The strange thing is; If i first run "uwsgi --http :8889 --module proj.wsgi" It is served on browser with 8889 port. Then i cancel it. Then i run "uwsgi --ini /etc/uwsgi/sites/proj.ini" And now it is working on socket. More clear; If i run below dirctly, it is not working on socket : start : uwsgi --ini /etc/uwsgi/sites/proj.ini But if i run below consecutively the page is served on socket on Nginx. start : uwsgi --http :8889 --module proj.wsgi cancel start :uwsgi --ini /etc/uwsgi/sites/proj.ini now works I couldn't figure it out. Why should i call the project on the port first so that it will run on the socket then. -
How to nest choices with django models, so that it reflets pproperly in django admin?
Here is my models.py class BrandSection(models.Model): """ Model for storing page's section details """ brand_choices = ( ('brand1', 'Brand1'), ('brand1', 'Brand2'), ('brand1', 'Brand3') ) page_choices = ( ('Brand Page', 'Brand Page'), ('PRODUCT_LIST', 'Product List'), ('PRODUCT_DETAILS', 'Product Details') .... .... .... ) brand_name = models.CharField(choices=brand_choices, max_length=255, default='brand1') page_name = models.CharField(choices=page_choices, max_length=255, default='Brand Page') Now from django admin panel user can select the brand name and page name separately. What I want is that page_choices should be dependent on brand_choices, like if a person selects brand1 then page_choises should appear different and when he selects brand2 then page_choices should be different. Any leads will help. -
djangocms error at beginning of project
I'm working with the djangocms tutorial as shown in [https://django-cms.readthedocs.io/en/latest/introduction/install.html][1] and having troubles finding a solution to my error. I worked through the tutorial a couple of times but now everytime when I'm trying to make a new project I get this error: Request Method: GET Request URL: http://localhost:8000/de/admin/polls/poll/ Raised by: cms.views.details Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^media/(?P<path>.*)$ ^static\/(?P<path>.*)$ ^sitemap\.xml$ ^de/ ^admin/ ^$ [name='index'] ^de/ ^admin/ ^login/$ [name='login'] ^de/ ^admin/ ^logout/$ [name='logout'] ^de/ ^admin/ ^password_change/$ [name='password_change'] ^de/ ^admin/ ^password_change/done/$ [name='password_change_done'] ^de/ ^admin/ ^jsi18n/$ [name='jsi18n'] ^de/ ^admin/ ^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$ [name='view_on_site'] ^de/ ^admin/ ^sites/site/ ^de/ ^admin/ ^auth/user/ ^de/ ^admin/ ^cms/usersettings/ ^de/ ^admin/ ^cms/pagetype/ ^de/ ^admin/ ^filer/clipboard/ ^de/ ^admin/ ^filer/folder/ ^de/ ^admin/ ^filer/thumbnailoption/ ^de/ ^admin/ ^cms/staticplaceholder/ ^de/ ^admin/ ^cms/pageusergroup/ ^de/ ^admin/ ^auth/group/ ^de/ ^admin/ ^filer/file/ ^de/ ^admin/ ^filer/image/ ^de/ ^admin/ ^cms/pageuser/ ^de/ ^admin/ ^filer/folderpermission/ ^de/ ^admin/ ^cms/page/ ^de/ ^admin/ ^cms/globalpagepermission/ ^de/ ^admin/ ^djangocms_snippet/snippet/ ^de/ ^admin/ ^(?P<app_label>sites|auth|cms|filer|djangocms_snippet)/$ [name='app_list'] ^de/ ^ ^cms_login/$ [name='cms_login'] ^de/ ^ ^cms_wizard/ ^de/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^de/ ^ ^$ [name='pages-root'] The current path, /de/admin/polls/poll/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a … -
Iframe in jQuery dialog doesn't have any style
I have a Django admin application that displays a jQuery dialog showing a page in an iframe inside the dialog that I show using: function opendialog(page, dialog_title) { var $dialog = $('#applied-assay') .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>') .dialog({ title: dialog_title, autoOpen: false, dialogClass: 'dialog_fixed,ui-widget-header', modal: true, draggable:true }); $dialog.dialog('open'); } function open_modal(url, title) { opendialog(url, title); return false; } So far, so good. However the content of the iframe doesn't have any style: The html template rendered inside the iframe looks like: {% extends "admin/base_site.html" %} {% load i18n admin_urls static admin_list %} {% block extrahead %} {{ block.super }} {{ media.js }} <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/start/jquery-ui.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> {% endblock %} <div class="modal-dialog"> <div class="modal-content"> <form role="form" action="{% url 'myapp:applied_assay' 1 %}" method="post"> <div class="modal-header"> <h3>Select applied assay type 1</h3> </div> <div class="modal-content"> {% csrf_token %} <div class="panel panel-default"> <div class="panel-body"> {{ form.as_p }} </div> </div> </div> <div class="modal-footer"> <div class="col-lg-12 text-right"> <input type="submit" class="btn btn-primary" name="submit" value="Accept"> <button type="button" class="btn btn-default" onclick="return close_modal()"> Cancel </button> </div> </div> </form> </div> </div> Any ideas? -
How can I deal with filter object in HTML
enter image description here I tried with above to see how I can use with objects in showing in homepage. few people recommend me to use this code below infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id) and my model code is like this. class Group(models.Model): name = models.CharField(max_length=20) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Type(models.Model) : name = models.CharField(max_length=20) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Info(models.Model): name = models.CharField(max_length=20) email = models.EmailField(null=True, blank=True, unique=True) memo = models.CharField(max_length=200, null=True) birthday = models.CharField(max_length=12,null=True, blank=True) group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) regdt = models.DateTimeField(auto_now_add=True) updatedt = models.DateTimeField(auto_now_add=True) class Number(models.Model): number = models.CharField(max_length=11) info = models.ForeignKey(Info, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) regdt = models.DateTimeField(auto_now_add=True) updatedt = models.DateTimeField(auto_now_add=True) and in my views.py. def addcontract(request) : if request.user.is_authenticated : pk = request.user.id name = request.POST['name'] email = request.POST['email'] memo = request.POST['memo'] birthday = request.POST['birthday'] group_id = request.POST['group_id'] type_id = request.POST['type_id'] number = request.POST['number'] user_id = pk newc = Info( name = name, email = email, memo = memo, birthday = birthday, group_id = group_id, user_id = pk) newc.save() number = Number(number = number, type_id= type_id, user_id = pk, info = newc) number.save() infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id) grouplist = Group.objects.filter(user_id = request.user.id) …