Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search with ajax + django view
can u please help me. I want to create search using ajax function and django view. There are input and submit button. When I clicked on submit button, jQuery takes value of input and create ajax request. Its good. But in the view, when i want to print serch_by value in console, there is an output: None qwer asdf zxvc <- value of input I think it is a problem. But maybe no. Help me, please. HTML: <form id="searchform" {% csrf_token %} <input name="q" type="text" id="search"> <button type="submit" id="searchsubmit"></button> </form> JS: function initSearchForm(){ $('#searchsubmit').on('click', function(e){ e.preventDefault(); q = $('#search').val(); updateContentBySearch(q); }); } function updateContentBySearch(q) { var data = {}; data['search_by'] = q data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val(); $.ajax({ url: "/search_products/", type: 'GET', data: data, success: $('.product_content').load(url, function() { ... }), }); } View: def search_products(request): data = request.GET search_by = data.get('search_by') print(search_by) # The console is displayed first 'None' and at the next line value of search_by if search_by: q = Q() for tag in search_by.split(): q |= Q(brand__brand_name__iexact=tag) | Q(model__iexact=tag) products = Product.objects.filter(q) return render(request, 'main/product_content.html', {'products': product}) -
In a tree filter nodes and its childs
I have an app with categories and products, categories and products can be inactive, on inactive category do not show its children, for example: All categories are active, tree looks like this: Category 1-1 Product 1-1 Category 2-1 Product 2-1 Category 3-1 Product 3-1 Category 3-2 Category 2-2 Product 2-2 If I set Category 2-1 to inactive, I want to see result like this: Category 1-1 Product 1-1 Category 2-2 Product 2-2 I have created a method which do a filter, but I am using a recursion, if a tree has a very high deep for example depth=100 and category is inactive in depth = 2, I get max depth recursion error. def filter_category_products(self): inactive_category_ids = get_inactive_categories_ids() queryset = Category.objects.exclude(id__in=inactive_category_ids).prefetch_related(Prefetch('product_set', queryset=Product.objects.filter(is_active=True))) return queryset def get_inactive_categories_ids(): inactive_categories_ids_query = Category.objects.filter(is_active=False).values_list('id', flat=True) inactive_ids = [] for i in inactive_categories_ids_query: inactive_ids.append(i) ids = [] while inactive_ids: for inactive_id in inactive_ids: if(inactive_id not in ids): ids.append(inactive_id) inactive_ids = Category.objects.filter(parent_id__in = inactive_ids).values_list('id', flat=True) return ids My question would be is there any other algorithm how could I filter that without recursion so I would avoid the error and editing max recursion limit in python sys resource. -
Angular 5 + Django - How to handle user permissions
I have an Angular v5 web application backed by Django REST Framework. Previously the application was totally relying on Django templates. Now, I'm using Angular and it is not clear to me how permissions are managed. The application has different sections. Regarding the product section, the permissions can be summed up as follow: Course grain permissions Can the user see a product? Can the user change a product? Can the user delete a product? Can the user create a product? Fine grain permissions Can the user see product SKU? Can the user see product pricing? ... Fine-grained permissions are very important because there're users that can see the product list where on Angular has been implemented as a table, but few users cannot see certain columns. My question is how I can handle permissions on Django and Angular? My idea was, when the user logs in, Angular got from backend all user permissions and then Angular won't show accordingly to the user. Anyway, I don't think this is a safe solution since permissions can easily manipulated by the user from JS console. What's usually the best practice for this? -
Django: foreign key access through related objects
Suppose I have a model Profile that relates to the standard User model through either a ForeignKey with unique=True relationship, or a OneToOne relationship: class Profile(models.Model): user = (either a ForeignKey/OneToOne relationship) ... If I have understood the documentation, the database representation of the column will be user_id, from Django automatically adding _id. This user_id will contain a series of integers. Suppose again I instantiate an object of this model in the shell, and try and access the user attribute: a_profile = Profile() a_profile.user From what I have read, the user attribute should now be a descriptor, and accessing it will invoke it's __ get __ method, giving me access to the related model instance - in this case the User instance. MY QUESTION: I have noticed that I can access the Profile instance through the User instance as well, through: user_profile = User.objects.all()[0] user_profile.profile What is happening here? Is this working the same way as accessing the user attribute of the Profile instance - is the profile attribute on a User instance a descriptor as well? Thank you! -
How to display all session variables in django 2.0?
How to display all session variables in Django 2.0? result, data1 = GetLoginUser(request) request.session['profile']=data1 ipdb> request.session['profile'] [{'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'}] ipdb> request.session['profile'][0] {'address': 'asdfsd', 'email': 'nitesh@scaledesk.com', 'mobile': '9570277820', 'category': 'getpass', 'designation': 'dsfsd', 'name': 'employee'} how to print data in template template.html.j2 {{request.session.GET['profile']}} getting error This page isn’t working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS -
Django forms - maximum recursion depth exceeded on get_context_data
I'm getting a maximum recursion depth exceeded error on one of my Django forms. The trace is pointing to get_context_data but I am unsure as to why or what the underlying issue is/may be. I use this same code on all my other forms without issue. ive read this is usually due to URLs but I can't seem to find the fault with that either. the add view works which uses almost the same code too traceback is: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/itapp/itapp/circuits/views.py" in dispatch 317. return super(EditFile, self).dispatch(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 236. return super(BaseUpdateView, self).get(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get 174. return self.render_to_response(self.get_context_data()) ... File "/itapp/itapp/circuits/views.py" in get_context_data 332. context = EditFile().get_context_data(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in __init__ 43. for key, value in six.iteritems(kwargs): Exception Type: RecursionError at /circuits/file/edit/5/7/site_cl Exception Value: maximum recursion depth exceeded my view is as follows: class EditFile(UpdateView): model = CircuitFiles form_class = FileForm … -
Configure codehilite in Django
I'm a beginner to Django, so I haven't had much luck; what I'm trying to do is seemingly simple. I am working with the Django wiki package, and I'm trying to find out where I can modify the config variable in to the highlight function in wiki/core/markdown/mdx/codehilite.py: def highlight(code, config, tab_length, lang=None): code = CodeHilite( code, linenums=config['linenums'], guess_lang=config['guess_lang'], css_class=config['css_class'], style=config['pygments_style'], noclasses=config['noclasses'], tab_length=tab_length, use_pygments=config['use_pygments'], lang=lang, ) html = code.hilite() html = """<div class="codehilite-wrap">{}</div>""".format(html) return html By simply modifying guess_lang=config['guess_lang'], to guess_land=False, the problem is temporarily fixed by simply ignoring the input value. I'm looking for a permanent solution. -
django rest framwork Column 'product_id' cannot be null
i have this view i want save a record in db when product id recived with post method class PeymentAPIView(APIView): def post(self, request, *args, **kwargs): serilizer = PeymentSerializer(data=request.data) if serilizer.is_valid(): serilizer.save(user=request.user, status=0) return Response("ok") else: #return Response(serilizer.errors) return Response(status=status.HTTP_400_BAD_REQUEST) with post man im sending this with post method : { "product": 2 } but i have this error can you please tell my why (1048, "Column 'product_id' cannot be null") this is my serializer : # product peyment class PeymentSerializer(ModelSerializer): product = serializers.SerializerMethodField() def get_product(self, obj): return obj.product.product_id user = serializers.SerializerMethodField() def get_user(self, obj): return obj.id class Meta: model = Peyment fields = [ 'product', 'status', 'user', 'transfer_id', 'created_date', 'updated_date', ] read_only_fields = ['user'] and it is related model : class Peyment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_peyment') status = models.CharField(max_length=30, null=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) transfer_id = models.CharField(max_length=100, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) -
source command no work in bash ubuntu 17.10
I am use ubuntu 17.04 and not work the next command,I work with this command an other time and it worked for me. !/bin/bash APP=personalBlog USER=root cd /opt/src/personalblog/conf/ source /opt/venv/ecomex/bin/activate uwsgi -c uwsgi.ini the error show is: /opt/src/personalblog/conf/run.sh: 7: /opt/src/personalblog/conf/run.sh: -c: not found /opt/src/personalblog/conf/run.sh: 8: /opt/src/personalblog/conf/run.sh: uwsgi: not found -
how to get the USER_TOKEN and USER_SECRET in linkedin
I am not able to get the User_TOKEN and USER_SECRET from linkedin. I got only Client ID and Client Secret and i am unable to fallow steps to get User_TOKEN and User_SECRET please help me to get the steps for interaction for outh 2 -
Allow user to edit once in django
Details: I have a teacher dashboard where a teacher can create and share worksheets with other teachers. When any worksheet is shared with other teachers they can (but not necessary) provide feedback on that worksheet, which will be visible to the creator of worksheet. Now I have a model which stores this sharing thing as follows: class SharingWS(TimeStampWS): shared_by = models.ForeignKey('members.Profile', on_delete=models.CASCADE, related_name='shared_by') shared_with = models.ForeignKey('members.Profile', on_delete=models.CASCADE, related_name='shared_with') worksheet = models.ForeignKey('WorkSheet', on_delete=models.SET_NULL, null=True) flag = models.BooleanField() reason = models.TextField(blank=True) as soon as the worksheet is created, an entry is created in the model with default flag=True. Problem Now how can I give only one chance to other teachers to review the worksheet. Once they have given a feedback, they cant do it again and if they dont give feedback it will be assumed approved after 2 days. There are similar questions but for voting, where there is no previous entry in db and you can lookup. In my case an entry is already created so I cant use that concept. -
Delete object in template using DeleteView without confirmation
I'm trying to write DeleteView for deleting posts: Del - delete button. How can i delete object properly? urls.py urlpatterns = [ # url(r'^$', views.index, name='index'), url(r'^feed$', views.FeedView.as_view(), name='feed'), url(r'^summary(?P<pk>\w{0,50})', views.SummaryCreate.as_view(), name='summary'), url(r'^summary(?P<user_id>\w{0,50})/(?P<pk>\w{0,50})/', views.SummaryDelete.as_view(), name='delete_summary'), url(r'^dashboard$', permission_required('reed.view_dashboard')(views.DashboardListView.as_view()), name='dashboard'), url(r'^dashboard/(?P<pk>\w{0,50})', permission_required('reed.view_dashboard')(views.DashboardUpdate.as_view()), name='review_summary'),] views.py class SummaryDelete(LoginRequiredMixin, generic.DeleteView): model = Summary def get_success_url(self): return reverse('summary', args=(self.request.user.id.hex,)) def get(self, *args, **kwargs): print('i\'m trying to delete') return self.delete(*args, **kwargs) template.html <h3> <a class="delete" href="{% url 'delete_summary' user.id.hex summary.id.hex %}" aria-hidden="true">Del</a> {{summary.title}} </h3> -
Dictionary inside a dictionary in django template
Eg: i have dictionary which has: a = {'card1' :{'name':'abc,'amount':'145820'},'card2':{'name':'dba','amount':'258963'}} now i want to print the crad1.amount in django template. -
Django url with parameters in template in multiple lines
I have this type of url in my template: <a href="{% url 'company-detail' region=ownership.company.city.province.region.slug province=ownership.company.city.province.slug city=ownership.company.city.slug company=ownership.company.slug %}"> That is, as you can see, monstrously long. There is some way to do the same thing in multiple lines? Something like this: <a href="{% url 'company-detail' region=ownership.company.city.province.region.slug province=ownership.company.city.province.slug city=ownership.company.city.slug company=ownership.company.slug %}"> -
Enable static for django-tinymce when using amazon-s3
The website on Django 1.10. Can't understand the work TinyMCE. The site statics are located on AWS S3. settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'orpro-assets' AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} REGION_NAME = 'us-east-1' AWS_LOCATION = 'static' AWS_MEDIA = 'media' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://{}/{}/".format(AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) AWS_PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = "https://{}/{}/".format(AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage' TINYMCE_DEFAULT_CONFIG = { 'theme': "lightgray", 'relative_urls': False} TINYMCE_JS_ROOT = STATIC_URL + 'tiny_mce' TINYMCE_JS_URL = STATIC_URL + 'tiny_mce/tiny_mce.js' TINYMCE_INCLUDE_JQUERY = False storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When you load the home page, at the end of the load appears scripts that link to the folder static site. There are no such scripts in the templates. But the addition of the block is enabled: {% block additional_scripts %} {% endblock %} All other static files are loaded correctly with amazon-s3 -
How to get a duplicate instance on save in Django?
Supposing I already have a created instance of a Django's model. I want to get another instance that is a duplicate in the database. Is there a universal way to do it without finding out which unique index is responsible for this duplication: class MyModel(models.Model): ... instance = MyModel(...) print(instance.id) # None ... duplicate = get_duplicate(instance) print(duplicate.id) # Some ID in DB -
rendering 2 real time video to browser using flask
I tried with https://blog.miguelgrinberg.com/post/video-streaming-with-flask to render the webcam footage to the browser in real time. Similar to this, I need to render 2 different videos to the browser in real time (frame by frame). I tried editing the above-mentioned code to work for 2 different streams, but it didn't work. So please someone could help me in how to render 2/+ videos to a browser in real time using python flask or Django or any other library in python? Thanks in advance -
Error: 'Uncaught SyntaxError: Unexpected token <' (Django + React + Webpack)
I was following this tutorial to set up Django to serve templates with webpack-generated bundles. I have set it up just like in the tutorial. However the problem is when i go to localhost:8000 I get Uncaught SyntaxError: Unexpected token < exception when I open the console in chrome devtools. Other html I put in the template file gets rendered except the reactjs bundle. My folder structure is as follows: . ├── djangoapp │ ├── db.sqlite3 │ ├── djangoapp │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ ├── reactapp │ │ └── static │ │ ├── bundles │ │ │ └── main-fdf4c969af981093661f.js │ │ └── js │ │ └── index.jsx │ ├── requirements.txt │ ├── templates │ │ └── index.html │ └── webpack-stats.json ├── package.json ├── package-lock.json └── webpack.config.js settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates"), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } STATIC_URL = 'static/' webpack.config.js var path = require("path"); var webpack = … -
Logging in with e-mail as ldapUser in Django
I am currently working on my webapp. As of now, I can login with the username (sAMAccountName) but I want to login with the e-mail-adress. I looked up some backends, but none of them could help me. Here are my setting.py AUTH_LDAP_SERVER_URI = "ldap://192.168.4.123" AUTH_LDAP_BIND_DN = "username" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "dn": "distinguishedName", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=users,cn=users,DC=domain,DC=com", "is_staff": "CN=users,cn=users,DC=domain,DC=com", "is_superuser": "CN=users,cn=users,DC=domain,DC=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stream_to_console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django_auth_ldap': { 'handlers': ['stream_to_console'], 'level': 'DEBUG', 'propagate': True, }, } } Maybe you have a good backend or I am missing something. I also tried: AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sbvg,DC=ch", ldap.SCOPE_SUBTREE, "(mail=%(user)s)") but then it creates a user with the username user@domain.com, which is also wrong. If you have any advise, do not … -
Formsets validate_min is not working properlly
I have a formset with multiple forms: PodFormSet = forms.inlineformset_factory(parent_model=PodP, model=Prod, form=PofModelForm, min_num=1, max_num=4,validate_min=True, extra=3) The issues is that validate_min is not working properly: If the user complete another form than the first one, validate_min doesn't work, say is invalid, which is not, because at least a form is completed but not the first one. How can I override/fix this behavior ? -
How to serve user uploaded images with Django on Heroku in production
In my website an user can upload images. This works fine in development when DEBUG=True, but if I set it to False, the images give error "Not found". I understand that the images disappear after 30 minutes of inactivity, but for me they aren't working at all. I have Whitenoise installed on my settings.py middleware and on requirements.txt. On settings.py I also have these lines: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') And on urls.py I have this: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The user uploads the files to an ImageField. What do I have to change to make the user uploaded images also work on production? As the tile says, I'm deploying the project to Heroku. -
In django app received desktop apple device like a mobile device
I have an application in django, where I use http://detectmobilebrowsers.com/ to detect mobile devices or not. Unfortunately, the user agent gets to the Apple desktop: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36, where the words Android and Mobile are simultaneously and this redirects to mobile mode. My code in python: def local_detect_is_mobile(request): reg_b = re.compile( r"(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino", re.I | re.M) reg_v = re.compile( r"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-", re.I | re.M) user_agent = request.META.get('HTTP_USER_AGENT', '') b = reg_b.search(user_agent) v = reg_v.search(user_agent[0:4]) if b or v: return True else: return False There is some solution to broke this problem? -
Django: How to Iterate over an Object one by one in my View?
I am trying to write a Quiztool with Django. I have created an index where all surveys are listed. Clicking at one brings you in the detail view. Right now there are listed all questions with answers with a submit button going to nothing. What i am asking for is how to manage there will be only one question and when I submit the answer the next question will aply wihtout jumpin out of the detail view. If the answer is to easy i also would be happy for just getting a hint about what I have to read... Here is some Code from my views.py def detail(request, survey_id): #try: question = Survey.objects.get(pk=survey_id).question.all() question_dict = { 'question': question, } return render(request, 'survey/detail.html', question_dict) And here is my deatil.html {% if question %} <form method="post"> {% for x in question %} <fieldset style="width:10%;"> <legend>{{x.question_text}}</legend> {% for y in x.answer.all %} <p style="display: flex;justify-content: space-between;"> <label for="{{ y.answer_id }}">{{ y.answer_text }}</label> <input name="{{x.question_id}}" type="radio" value="{{y.answer_id}}" id="{{y.answer_id}}"/></p> {% endfor%} </fieldset> {% endfor %} <input type="button" value="Senden" onclick="var Sende=()=>{console.log('gesendet');}; Sende();"> </form> {% else %} <p>No questions are available.</p> {% endif %} Thank you in advance Flotzen -
missing default filters in django admin while applying bootstrap3
i had developed a project based on django-admin and when i have been changed the admin theme to django-bootstrap3 the default filters on admin panel are missing. these are the two screen shorts before bootstrap theme and after bootstrap this image is without bootstrap3 at the right side filters are visible this is the bootstrap image -
django InlineFormsets errors reporting with formset error list being empty
I have a strange error on creation using Django inline formsets. Django is reporting formset errors, so it doesn't finish the creation. Also I tested is_valid and it returns true. What is wrong ? but if I check them there is nothing in the dictionary of errors: 1. {{formset.errors}} [{}, {}, {}, {}, {}] 2. {% if formset.errors %} {% for error in formset.errors %} error {{ error }} {% endfor %} {% endif %} {}