Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
embedding geojson.io with iframe
i am using django and i have a method that generates a URL for a certain map on geojson.io Now i am trying to implement this into my html code. When using a button that opens a new tab with the url everything works fine, but now i want to embed this onto my page instead of opening a new tab when clicking a button. So for this i read about "iframe". Now the problem is when passing my URL to src into "iframe" it doesnt display the map into the frame but rather opens the URL as if one would type the URL into the browser. I tried it using an absolut path and using a variable, both had the same result as mentioned above. Is this a problem with geojson.io or am i doing something wrong with my code? The URL is encoded with encodeURIComponent doing it in django with the urllib package. Here is my html code i implemented with the absolut path of the generated URL. <iframe id="Example" title="Example" width="300" height="200" src="http://geojson.io/#data=data:application/json,%7B%22features%22%3A%20%5B%7B%22geometry%22%3A%20%7B%22coordinates%22%3A%20%5B8.6792%2C%2050.1171%5D%2C%20%22type%22%3A%20%22Point%22%7D%2C%20%22properties%22%3A%20%7B%7D%2C%20%22type%22%3A%20%22Feature%22%7D%2C%20%7B%22geometry%22%3A%20%7B%22coordinates%22%3A%20%5B11.5727%2C%2048.1404%5D%2C%20%22type%22%3A%20%22Point%22%7D%2C%20%22properties%22%3A%20%7B%7D%2C%20%22type%22%3A%20%22Feature%22%7D%2C%20%7B%22geometry%22%3A%20%7B%22coordinates%22%3A%20%5B%5B8.6792%2C%2050.1171%5D%2C%20%5B11.5727%2C%2048.1404%5D%5D%2C%20%22type%22%3A%20%22LineString%22%7D%2C%20%22properties%22%3A%20%7B%7D%2C%20%22type%22%3A%20%22Feature%22%7D%5D%2C%20%22type%22%3A%20%22FeatureCollection%22%7D"> </iframe> So my question is, how do i embed a generated geojson.io URL with "iframe" (or others) and why is it linking to the … -
django error reporting request url - how to use this locally?
I have a django project which used the normal email admins on an unhandled exception when debug is set to False. ie in production. I normally just review the error message and the stack trace. However I clicked on the request url link, which managed to recreate the error on the prouduction site (which then fired off another email). What is this request url? Does it recreate the full http request (including the session etc..) which resulted in the original error? Can I get the link to point to a local version of the site? (As after fixing a previous error clicking on the earlier request url has manged to create a recent error that we have been unable to reproduce, so it would be good to recreate this locally so it can be debugged. -
How to fix 'RecursionError: Problem installing fixture' in Django (django-mptt)
I have a Category model which is a subclass of MPTTModel (django-mptt). I'm trying to load some test data using Django fixtures. My version of django is 2.2.1. And django-mptt is 0.10.0. Category Model: class Category(MPTTModel): name = models.CharField(max_length=128) slug = models.CharField(max_length=128) parent = TreeForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.SET_NULL, db_index=True) objects = models.Manager() tree = TreeManager() class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name_plural = 'categories' Fixture file categories.json [ { "pk": 1, "model": "products.category", "fields": { "rght": 20, "name": "PC & Video Games", "slug": "pc_video_games", "parent": null, "level": 0, "lft": 1, "tree_id": 1 } }, ... ] Test class GetCategoriesTestCase(APITestCase): fixtures = ['categories.json'] def test_get_categories(self): response = self.client.get(reverse('mobile-categories-list')) self.assertEqual(response.status_code, status.HTTP_200_OK) When I run ./manage.py test products, I get this error: RecursionError: Problem installing fixture '..../fixtures/categories.json': maximum recursion depth exceeded while calling a Python object -
'BaseList' object has no attribute 'items'
I am getting error 'BaseList' object has no attribute 'items' while trying to return get_queryset method. views.py def get_queryset(self): try: data = Overview.objects.filter(account_id=account_id) # serializer = OverviewSerializer(data, many=True) print(data) # data = serializers.serialize('json',data) # data = json.dumps(data) # print(serializer.data) logger.info('overview data retrieved successfully for linked account id'.format(self.kwargs['account_id'])) return data except Exception as e: logger.exception(e) I have tried serializer to serialize my data and then return it, but I am getting an empty list, also json.dumps is returning an empty list. -
Problems with uploading my blog to pythonanywhere.com
I have uploaded my blog to pythonanywhere. On my localhost everything is working fine, but on pythonanywhere it is not working. I configured pythonanywhere like i did on my localhost, installed everything (Tinymce is also installed), but im getting this Error: 2019-05-16 12:24:14,263: Error running WSGI application 2019-05-16 12:24:14,264: ImportError: No module named 'tinymce' 2019-05-16 12:24:14,264: File "/var/www/urosdobricic_pythonanywhere_com_wsgi.py", line 15, in <module> 2019-05-16 12:24:14,264: application = get_wsgi_application() 2019-05-16 12:24:14,264: 2019-05-16 12:24:14,265: File "/home/UrosDobricic/.virtualenvs/urosdobricic.pythonanywhere.com/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-05-16 12:24:14,265: django.setup(set_prefix=False) 2019-05-16 12:24:14,265: 2019-05-16 12:24:14,265: File "/home/UrosDobricic/.virtualenvs/urosdobricic.pythonanywhere.com/lib/python3.5/site-packages/django/__init__.py", line 24, in setup 2019-05-16 12:24:14,265: apps.populate(settings.INSTALLED_APPS) 2019-05-16 12:24:14,266: 2019-05-16 12:24:14,266: File "/home/UrosDobricic/.virtualenvs/urosdobricic.pythonanywhere.com/lib/python3.5/site-packages/django/apps/registry.py", line 91, in populate 2019-05-16 12:24:14,266: app_config = AppConfig.create(entry) 2019-05-16 12:24:14,266: 2019-05-16 12:24:14,266: File "/home/UrosDobricic/.virtualenvs/urosdobricic.pythonanywhere.com/lib/python3.5/site-packages/django/apps/config.py", line 90, in create 2019-05-16 12:24:14,266: module = import_module(entry) I have installed Tinymce with pip3 install django-tinymce --user, like i did on my localhost. Can´t figure out what is happening. -
Python django error OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
enter image description here Please help me it not working having try several thing on internet. I am new to django so i have less information about this error. Looking forward for your response. I had browse it all over internet but doesnot find a solution yet. -
How to Save file in database instead of upload,using models.FileField?
I want to save file in database instead of upload it in server media file and save URL in Database,I want directly save file in Database using models.FileField(). if possible Right now i am doing this model.py File = models.FileField(upload_to='CSR/', null=True , blank = True) template.html <td> {{certificate.File.url}} </td> -
Use custom manager method for MPTTModel
I am struggling to apply a custom manager method to a subclass of QuerySet. Specifically, I have a model that inherits from MPTTModel in order to implement a hierarchy. As such, instances have the get_decsendants method which returns an instance of TreeQuerySet. My model also has a custom manager w/ some custom methods. But I cannot apply any of those methods to a TreeQuerySet. Here is some code: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class MyModelQuerySet(models.QuerySet): def red(self): return self.filter(color="red") class MyModel(MPTTModel): objects = MyModelQuerySet.as_manager() color = models.CharField(max_length=255, blank=True, null=True) parent = TreeForeignKey("self", blank=True, null=True, related_name="children", on_delete=models.CASCADE) In order to get all descendants of an instance of MyModel that happen to be "red" I would like to do something like this: my_model = MyModel.objects.get(pk=123) my_red_descendants = my_model.get_descendants().red() But this returns the error: AttributeError: 'TreeQuerySet' object has no attribute 'red' Any suggestions? It seems like what I want to do is to cast the result of get_descendants to MyModelQuerySet. -
Django: Paginator returns all the data from db, and ordering is not working
I have this ListView and i am trying to get only 12 cars from my db, and order them by price, i have 20 entries in my db and in the buttons of pagination it shows 6 buttons, aka 6 pages, so it is returning all possible data from db, at this point I am lost and can't find the bug, any help would be very much appreciated for both, pagination and ordering. class CardListView(ListView): model = Car template_name = 'home.html' context_object_name = 'cars' ordering = ['-price'] paginate_by = 5 limit = 12 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 10 max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if end_index >= max_index: end_index = max_index page_range = paginator.page_range[start_index:end_index] cars = Car.objects.all()[:self.limit] car_types = CarCategory.objects.all() context['cars'] = cars context['car_types'] = car_types context['page_range'] = page_range return context -
Django pass instance of model in function
Context I have the models Customer, DeviceGroup & CustomerDevice. When a DeviceGroup object is deleted, the related CustomerDevice objects are put in the DeviceGroup that is default for the specific Customer. I get the default DeviceGroup with the function get_default_group(). I also use this function in an API view to create a CustomerDevice object and put it in the default group. My models.py looks like this: # models.py def get_default_group(): try: return DeviceGroup.objects.get(is_default=True) except DeviceGroup.DoesNotExist: return None class Customer(models.Model): customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class DeviceGroup(models.Model): group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) customer_uuid = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) is_default = models.BooleanField(default=False, editable=False) class CustomerDevice(models.Model): customer_uuid = models.ForeignKey(Customer, on_delete=models.CASCADE) customer_device_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) group_uuid = models.ForeignKey(DeviceGroup, on_delete=models.SET(get_default_group)) Problem The get_default_group() function only works when there is just 1 Customer and thus 1 DeviceGroup with is_default=True. Goal I would like to change the get_default_group() function, so it returns the default DeviceGroup for the related Customer of the instance. I am not sure how I would achieve this. What I tried I tried to remove the get_default_group() function and replace the on_delete functionality by using a pre_delete signal like this: @receiver(pre_delete, sender=DeviceGroup) def place_back_in_default_group(sender, instance, **kwargs): customer_instance = instance.customer_uuid customer_instance_uuid = Customer.objects.get(customer_uuid=customer_instance.customer_uuid) default_group = … -
Upend a new Http header using django request.META
i am using django-rest framework and i am able to get the custom headers using the below META information, request.META['HTTP_X_EXTRA'] Now like the same way how can I update a new header into the request so that I can avail it in any part of my code in the request module. I am planning to do it django middle wares. -
how to save original password if no password input is given in django
I am currently using my own custom admin template instead of default django admin.And here i want to update the user information .while updating the user if the user's don't change any password then the password should be the same as original. here i am getting error with saying password1 password2 is empty if i changed only email and active/staff status.How can i manage this? views.py def updateusers(request, id): if not request.user.is_superuser: messages.warning(request, 'Permission Denied.You have no permission to perform this action.') return redirect('students:our_users') user = get_object_or_404(User, id=id) form = EditRegisterForm(request.POST or None, instance=user) if form.is_valid(): password1 = form.cleaned_data['password1'] password2 = form.cleaned_data['password2'] user = form.save(commit=False) user.password1 = password1 user.password2 = password2 user.save() messages.success(request, '{} updated'.format(user.username)) return redirect('students:our_users') else: # messages.error(request,'Error in Form.Try Again') # return redirect('students:edit_user', user.id) return HttpResponse(form.errors) def users_change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) return render(request, 'students/change_password.html', { 'form': form }) forms.py class EditRegisterForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if self.instance and self.instance.pk and not User.objects.filter(email=email).exists(): return email return email class Meta: model = User fields = … -
Establishing connection using django-pyodbc-azure
I'm using django-pyodbc-azure (https://pypi.org/project/django-pyodbc-azure/) to connect to azure database. I'm getting the following error while running the server " django.db.utils.Error: ('HYC00', '[HYC00] [Simba][ODBC] (11470) Transactions are not supported. (11470)(SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT))') ". i tried puttin "AUTOCOMMIT: True" as shown in the code below, but still facing the same issue. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'databse', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': 'port', 'AUTOCOMMIT': True, 'OPTIONS': { 'driver': 'Simba Spark ODBC Driver', 'dsn': 'dsn_name' } } } -
Can't do a simple redirect after POST request in Django (using HttpResponseRedirect)
I am trying to return an HTTP Response after a POST request in Django, it does not seem to be working. I have illustrated that below using HttpResponseRedirect. When executing below code, I see the 'hello' message but it does not redirect. if I move the 'return HttpResponseRedirect('/account/')' line to the bottom then it does redirect upon loading the page, so the line does work otherwise. if request.POST: print('hello') return HttpResponseRedirect('/thank-you/') else: return render(request, 'account.html') -
Formatting timestamp in django template
I've got this timestamp: 2019-05-16T09:06:39Z I'd like to know how could I format it to something more readable in my django template using date. -
retreive objects except that created by the user
This question might be weird, but i want to retrieve objects except the objects created by the login in user Well i tried this code in my view def getobjects(request): products=Products.objects.filter(user!= request.user) But does not work. In model class Products(models.Model): name=models.Charfield() user=models.ForeignKey(User) I will need help with the right query function to handle this. Thanks in advance -
Django: composite user interfaces?
Django noob here... What is the Django way of building composite user interfaces, i.e. user interfaces composed from multiple components? As an example, how would one build a finder/explorer-like interface, with a icon toolbar on the top, a list of items on the left side and a detail pane for the selected list item? I understand that the Django way of presenting it in the UI is views. Is there a way of composing views? Or does this require building a new custom view? Looking for keywords and concepts for further reading, not necessarily for detailed solutions. -
django.urls.exceptions.NoReverseMatch: Reverse for 'change_view' with keyword arguments
i am getting error django.urls.exceptions.NoReverseMatch: Reverse for 'change_view' with keyword arguments '{'view_type': 'sla', 'curr_url': '/home/'}' not found. 1 pattern(s) tried: ['change_view\/(?P[^/]+)\/$'] Using django 2.1.7 and python 3.6 version i have tried to add both the arguments as dynamic fields in urls.py home.html <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true"><i class="fa fa-eye fa-fw"></i>View<span class="caret"></span></a> <ul class="dropdown-menu"> <li {% if session.view == 'sla' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='sla' curr_url=request.get_full_path %}"><i class="fa fa-bar-chart-o fa-fw"></i>SLA</a></li> <li {% if session.view == 'priority' %}class="disabled"{% endif %}><a href="{% url 'change_view' view_type='priority' curr_url=request.get_full_path %}"><i class="fa fa-trophy fa-fw"></i>Priority</a></li> </ul> </li> urls.py urlpatterns = [ path('change_view/<str:view_type>/', views.change_view , name='change_view'), ] view.py def change_view(request,view_type=None): request.session['view'] = view_type request_data = json.loads(request.body) curr_url = request_data['curr_url'] return redirect(curr_url) I want the function change_view to set the request.session['view'] to user selected input and stay on the same url. -
Django webframeworks
Django settings.py issue Syntax error The code line :- python manage.py runserver under virtualenv condition It should give a webpage showing django running successfully but instead it's giving an syntax error. -
Display specific object according to try/except and conditions in django
I'm working on my django project and I need a little help in order to manage and display userguide with some conditions. Userguide can be displayed: in english in french in english and french no userguide Then, there are several cases: If there is no userguide in choosen language, it displays existing on the server, no matter about the language. If there is no userguide at all, I display the homepage with error message. Up to now, if userguide in specific language doesn't exist, it redirects automatically to my homepage with error message instead of display the userguide existing with another language. This is my code: def get(self, request): if request.user.is_anonymous: try: curr_lang = '' if '_language' in request.session: curr_lang = request.session['_language'] else: curr_lang = 'en' if request.cur_app.guides.get(profile_type='', profile_level='', language=curr_lang).exists(): guide = request.cur_app.guides.get(profile_type='', profile_level='', language=curr_lang) else: guide = request.cur_app.guides.get(profile_type='', profile_level='') except UserGuide.DoesNotExist: messages.error(request, _('No user guide is available')) return redirect('home') How I can manage my different cases ? Thank you very much -
How to make a ajax request using post method
I made an ajax request using post method in django..its wokring perfectly..the problem is its calling the complete html page rahter than a div..i want to call only a div..i tried but unable to find the exact solution.. <script> $(document).ready(function(){ $('#Category').change(function(event){ event.preventDefault(); var e = document.getElementById("Category"); var value = e.options[e.selectedIndex].value; $.ajax({ url: "/charts/", type: "post", dataType: "html", data: value, success: function(data) { $('#div1').html(data); }}); return false; }); }); </script> I want only div content with id #div1..i already tried find and replace method -
Django UserSocialAuth matching query does not exist
I'm developping a web app with github API. I want to get the token of the user i've authenticated with Python Social Auth, but I get the following error "UserSocialAuth matching query does not exist." when i'm trying to access the token of the user. I really don't know what to do to access this extra data. here's my code when i'm trying to access the token : if request.user.is_authenticated: gituser = request.user.social_auth.get(provider ='github-oauth2') extra_data = str(gituser.extra_data['access_token']) Thanks by advance ! -
fixing admin page server error django.utils.translation
I am trying to login to admin page but getting server error. It shows in sentry: ==================== AttributeError django.utils.translation.trans_real in do_translate NoneType' object has no attribute 'replace' It seems the message value is None. I have no idea how to fix that and what happend. Where should I start to fix that problem? # str() is allowing a bytestring message to remain bytestring on Python 2 eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n')) -
Django - how to get the value in the ListView from the HTML?
Using Django, I have created the Book class and the BookManager class in the models.py. The BookManager class has the method to count the number of the book title containing the keyword. How can I show the book title count to the HTML file using the Classe-based view? I know how to do it using the function-based view but not with the ListView class based view. I want to display the book title count on the HTML file using the Classe-based view. -
What does "UserWarning: No PROJECT_APPS settings, coverage gathered over all apps" mean?
So I am researching and testing the continuous integration of Django and Jenkins for my company. I successfully connected them but this warning keeps popping up. I already tried googling for this and to my dismay did not find what I was looking for. So I read in some articles that I needed to insert a line of code into a config file but I am not sure if this is right. Below is the code JENKINS_TASKS = ( 'django_jenkins.tasks.run_pep8', 'django_jenkins.tasks.run_pyflakes', 'django_jenkins.tasks.run_jslint', 'django_jenkins.tasks.run_csslint', 'django_jenkins.tasks.run_sloccount' ) The problem is, my Django and Jenkins would not run if I put this in settings.py so I am utterly confused on to where I should put this. The documentation for Django-Jenkins only stated that to enable it you need to install on Jenkins server manually and I did not find any guide on how to install it so I am doing my last choice of asking here.