Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I connect to a Samba 4 server from a Django application installed on IIS 7 using LDAPS?
I have a very specific problem. I had to install a Django application in Windows Server 2008 with IIS 7. For authentication I used the django-auth-ldap package and connected to the Samba 4 server via LDAP without difficulty. The problem begins when the LDAPS connection is tried because I do not know how to configure the application to recognize the security certificate in Windows. In Debian I know the procedure, I need to configure settings.py for this purpose. Thanks for the help. -
Adding a trailing slash to a Django root URL
I am serving through Apache and wsgi a Django Project. The server url is http://example.com and the alias for the project is myProject I'm trying to add automatically a trailing slash to the root url, therefore: http://example.com/myProject should become http://example.com/myProject/ In the Apache settings, I have the project alias: WSGIScriptAlias /myProject /path/to/wsgi.py In the myProject's main urls.py file for Django, I have these entries: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('externalModule.urls')), # I need to add the urls of an external module at this point. ] But doing in this way, if I request http://example.com/myProject the trailing slash is not added and it causes errors later on, during the site usage, due to some relative links. Intrestingly, if I change urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'foo/', include('externalModule.urls')), ] It works: http://example.com/myProject/foo becomes http://example.com/myProject/foo/. How can I get the same behavior at the root level? -
what is best choice to create charts in django? [on hold]
I am still confused what is best chart framework for Django. i am already tried google charts,fusion charts,etc... -
Django's adding parentheses itself to the model name in the admin panel
I don't know why this is happening to my website.. As my perspective, I'm doing all these things right. But there should be something which hid from my eyes. Here is a screenshot of the current result: And here is my models.py and admin.py files. models.py: from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.dispatch import receiver from . import managers class Profile(models.Model): # Relations user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='profile', verbose_name=_('user'), on_delete=models.CASCADE ) # Attributes - Mandatory interaction = models.PositiveIntegerField( default=0, verbose_name=_('interaction') ) # Custom Properties @property def username(self): return self.user.username # Methods # Meta and String class Meta: verbose_name = _("Profile"), verbose_name_plural = _("Profiles"), ordering = ('user',) def __str__(self): return self.user.username @receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) def create_profile_for_new_user(sender, **kwargs): if kwargs['created']: profile = Profile(user=kwargs['instance']) profile.save() admin.py: from django.contrib import admin from . import models @admin.register(models.Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['username', 'interaction'] -
Django relations between Models
What I currently have in my models is this: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') Now my question is: Users should be able to have multiple Projects - so I obviously can't use a OneToOne-Field in the Profile-Model. Later I want to use it for example to just show a user news which are only related to the projects he participates in. What would be the best strategy to make this possible? Any input is highly appreciated. -
Installed Django and virtualenvwrapper-win. "mkvirtualenv myproject" command giving "DNS server not authoritative for the zone" error.
I am running Windows 7 with Python 3.6 and no other versions. I installed Django through pip successfully. Yet when I try to make new virtual project, I get "DNS not authoritativer error". I am logged in and running cmd prompt as Admin. What could be the issue here? -
I can't access the primary key in django?
I am sure I have made a rookie mistake somewhere down here. So I have a details page for a particular link. Suppose I have list of incubators on my page, and if I click on one of them, I want to show its details. I am sure this can be done by using primary key but I keep getting errors. Models.py class Incubators(models.Model): # I have made all the required imports incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner class Details(models.Model): incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE) inc_name = models.CharField(max_length = 30) inc_img = models.FileField() inc_details = models.TextField(max_length= 2500) inc_address = models.TextField(max_length = 600, default = "Address") inc_doc = models.FileField() inc_policy = models.FileField() def __str__(self): return self.inc_name views.py def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) return render(request, 'main/details.html', {'inc': inc}) This is my urls.py but m sure there's no error her: url(r'^incubators/(?P<pk>[0-9]+)', views.details, name = 'details'), Also can you explain a little why I am getting this error ? -
Django Rest - Swagger with JWT
I am using JWT token for authentication with Django Rest Framework. Trying to use the library django-rest-swagger, only problem is with authentication when user wants to test the various API endpoints. I added the following in settings.py (Django project): SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization', } }, } But unfortunately it doesn't allow the user to insert the 'bearer' which is JWT. Example in the header: Authorization: JWT my_token_here Instead, Swagger sends: Authorization: my_token_here I am using django-rest-swagger==2.1.2 to generate the Swagger documentation. Any idea how to solve this issue? -
vue.js and django. action, component updating, function execution
Purpose of vue.js components Aim of DataTable component is to display backend database' data. Aim of NewDataPanel.vue component is to add data to backend database. Required behavior After creating new data via NewDataPanel it should appear in backend database and at the DataTable. Problem After creating new data they appears in backend database but there is a problem with refreshing DataTable component. As required methods are in sequence: this.$store.dispatch('postResult') this.$store.dispatch('getResult') it's supposed that some data would first created and then all data would be retrieved from backend and the store would be mutated to display refreshed data at DataTable. But after adding first data element nothing happened with DataTable. And only after adding second data element the first one would appear here. How should I realize DataTable refreshing after adding new data? P.S.: Sources and components diagram are below. DataTable.vue export default { // ... computed: { // ... ...mapGetters(['resultTable']) // ... } // ... beforeMount () { this.$store.dispatch('getResult') } } NewDataPanel.vue export default { // ... methods: { // ... addData () { // ... this.$store.dispatch('postResult') this.$store.dispatch('getResult') // ... } // ... } // ... } vuex store's actions work with Django Rest Framework via API: postResult just send … -
Django channels 'No application configured for scope type 'websocket''
I am trying to implement chat with django and channels according to this tutorial (http://channels.readthedocs.io/en/latest/tutorial/part_2.html). I add chanels and chat app to installed apps. I make following routings for project: # mysite/routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # (http->django views is added by default) }) Basically I did exactly the steps from tutorial. But after runserver I an still getting ValueError: No application configured for scope type 'websocket', after going to specific chat room. Can please someone help me ? -
"Didn't return an HttpResponse object. It returned None instead" on POST request
I'm trying to pass a selection from a dropdown form into views as a POST request, then using this selection to query some data from django. I'm then using these queries to try and follow this approach to map django models data to highcharts. The problem is I'm getting a "the view properties.views.property_list didn't return an HttpResponse object. It returned None instead" error when I submit the form. I've looked through similar questions on SO but none of the solutions seem to work/be applicable to my case. Below is the code that I've written: views.py def property_list(request): if request.user.is_authenticated(): current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties) property_meter_data = MeterData.objects.filter(meter__in=current_user_meters) class AccountSelectForm(forms.Form): accounts = forms.ModelChoiceField(queryset=current_user_meters) accounts.widget.attrs.update({'class' : 'dropdown-content'}) form = AccountSelectForm() if request.method == "POST": if form.is_valid(): selection = form.cleaned_data['accounts'] current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties) selected_meters = Meter.objects.filter(name=selection) selected_meter_data = MeterData.objects.filter(name=selection) usage_data = {'usage': [], 'dates': []} for meter in selected_meter_data: usage_data['usage'].append(meter.usage) usage_data['dates'].append(meter.usage) # data passing for usage chart usage_xAxis = {"title": {"text": 'Date'}, "categories": usage_data['dates']} usage_yAxis = {"title": {"text": 'Usage'}, "categories": usage_data['usage']} usage_series = [ {"data": usage_data['usage']}, ] return HttpResponseRedirect('properties/property-selected.html', { 'form': form, 'usage_xAxis': usage_xAxis, 'usage_yAxis': usage_yAxis, 'usage_series': usage_series, 'current_user_meters': current_user_meters, 'selection': selection, 'selectected_meters': … -
(Django) Model of particular person with this User already exists
Dear StackOverFlow community, Basing on a built-in user User model I've created my own model class called "ModelOfParticularPerson". The structure of it looks like this: class ModelOfParticularPerson(models.Model): user = models.OneToOneField(User) nickname = models.CharField(max_length=100, null=True, unique=False) uploaded_at = models.DateTimeField(auto_now_add=True, null=True) email_address = models.EmailField(max_length=200, blank=False, null=False, help_text='Required') description = models.CharField(max_length=4000, blank=True, null=True) created = models.DateTimeField(auto_now_add=True, blank=True) Unfortunately, after loggin in with the usage of particular account, whenever I am trying to reedit the profile, I do get following error: "Model of particular person with this User already exists." Any advice is priceless. Thanks. ps. views.py: [..] @method_decorator(login_required, name='dispatch') class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = ModelOfParticularPerson form_class = ModelOfParticularPersonForm success_url = "/accounts/profile/" # You should be using reverse here def get_object(self): # get_object_or_404 return ModelOfParticularPerson.objects.get(user=self.request.user) def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def post(self, request): form = ModelOfParticularPersonForm(self.request.POST, self.request.FILES) if form.is_valid(): print("FORM NOT VALID!") profile = form.save(commit=False) profile.user = self.request.user profile.save() return JsonResponse(profile) else: return render_to_response('my_account.html', {'form': form}) urls.py: urlpatterns = [ [..] url(r'^login/$', auth_views.LoginView.as_view(template_name='login.html'), name='login'), url(r'^accounts/profile/$', ProfileUpdateView.as_view(template_name='my_account.html'), name='my_account'), ] forms.py class ModelOfParticularPersonForm(ModelForm): class Meta: model = ModelOfParticularPerson fields = '__all__' widgets = { 'user':forms.HiddenInput(), 'uploaded_at':forms.HiddenInput(), 'created':forms.HiddenInput(), } -
How to deploy RQ (Redis Queue) to VDS on Debian 9?
Debian 9.3, Redis 3.2.6, Python 3.5.3, RQ 0.10.0, Gunicorn I have Django 2.0.3 and Django-RQ plugin for RQ (Redis Queue). How to start using RQ on VDS (Debian 9) and setting up service background demon? Maybe Gunicorn have function for works with RQ? -
img not showing in Django static
I use Django 2.0.3 and I want try static , I create one in app folder and my code like this. {% load static %} And for pic is : <img src="{% static 'images/ic_team.png' %}"> in setting the dir of static is : STATIC_URL = '/static/' but the pic comes like this : enter image description here -
Django and dropzone.js, dynamic component reload
I integrated dropzone.js into my django project and it is working so far. Here is my code: In my template view: <div class="col-md-8 ml-auto mr-auto"> <h2 class="title">Drop your image down below</h2> <form action="." method="post" enctype="multipart/form-data" class="dropzone dz-clickable" id="dropzone1"> {% csrf_token %} </form> </div> <div class="linear-activity"> <div class="indeterminate"></div> </div> In views.py: class SuperResolutionView(FormView): template_name = 'display/sr.html' form_class = SRForm success_url = '.' def get_context_data(self, **kwargs): context = super(SuperResolutionView, self).get_context_data(**kwargs) # context["testing_out"] = "this is a new context var" return context def form_valid(self, form): # My image from the form original_image = self.get_form_kwargs().get("files")['file'] # Show a loader in the template # Do some heavy operations on the file return super(SuperResolutionView, self).form_valid(form) So I do get the resulting image in original_image but what I want to do now is the <div class="linear-activity"> (which is actually a loader) to be shown only when the # Show a loader in the template is reached. Basically I don't want the whole page to reload, just this component to show up. Also when form_valid returns it actually returns a Http 302 (redirect) which doesn't seems to affect my webpage. Why is that? Thank you. -
Django 2.0 TestCase unexpected creation of Model objects for every test
I have some tests and I need one Board object which I created with Board.objects.create() to have one Object with the primary key 1. But i have figured out, that there are a new object for every test, so i there I have for example 'pk': 5. If i add more tests the 'pk': 5 could be wrong, because it change to 'pk': 6. How is it possible to create only one Board object with 'pk': 1 for all tests? I am using Django 2.0.3 from django.test import TestCase from django.urls import reverse, resolve from .views import home, board_topics, new_topic from .models import Board class BoardTopicsTests(TestCase): def setUp(self): Board.objects.create(name='Django', description='Django board.') def test_board_topics_view_success_status_code(self): url = reverse('boards:board_topics', kwargs={'pk': 5}) response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_board_topics_view_not_found_status_code(self): url = reverse('boards:board_topics', kwargs={'pk': 99}) response = self.client.get(url) self.assertEquals(response.status_code, 404) def test_board_topics_url_resolves_board_topics_view(self): view = resolve('/boards/1/') self.assertEquals(view.func, board_topics) def test_board_topics_view_link_back_to_homepage(self): board_topics_url = reverse('boards:board_topics', kwargs={'pk': 3}) response = self.client.get(board_topics_url) homepage_url = reverse('boards:home') self.assertContains(response, 'href="{0}"'.format(homepage_url)) def test_board_topics_view_contains_navigation_links(self): board_topics_url = reverse('boards:board_topics', kwargs={'pk': 2}) homepage_url = reverse('boards:home') new_topic_url = reverse('boards:new_topic', kwargs={'pk': 2}) response = self.client.get(board_topics_url) self.assertContains(response, 'href="{0}"'.format(homepage_url)) self.assertContains(response, 'href="{0}"'.format(new_topic_url)) -
Error : 'User' object has no attribute 'get' when trying to access current user in ModelForms for a ModelChoiceField dropdown
So below is the views.py and I'm trying to load a view with modelform. And within the modelform I need to load modelchoicefield depending on the current user logged in and tried the below solution(check forms.py.) When I run it, i get Attribute Error :object has no attribute 'get' Help is highly appreciated, there's nothing in stackoverflow. views.py: class HomeView(View): def get(self, request, *args, **kwargs): form=PreDataForm(request.user) return render(request, 'mainlist.html', { "form":form, }) models.py: class PreData(models.Model): journalname = models.CharField(max_length=400, blank=False, null=True, default='') forms.py: class PreDataForm(forms.ModelForm): class Meta: model=PreData fields=['journalname'] def __init__(self,user, *args, **kwargs): super(PreDataForm, self).__init__(user, *args, **kwargs) self.fields["journalname"].queryset = Journals.objects.filter(journalusername=user) html file: {% extends 'home-base.html' %} {% load crispy_forms_tags %} {% block title %} Welcome to Metrics - JSM {% endblock %} {% block content %} <div class="col-md-9 col-centered" > <div class="backeffect" > {% if data %} {% else %} <b>Seems you are first time around here, Why not <b>{% include 'modal_first_stage.html' %}</b> to get started? :)</b> {% endif %} {% endblock %} -
How to find serializer for a django model?
I am working on a project in which I am using django-polymorphic for retrieving polymorphic result sets. I have some models which inherit from a parent model. For example, Model B inherits from Model A and Model C also inherits from Model A. Model B and Model C have their own serializers and when I query all records for model A, I get a mixed resultset containing instance of Model B and C. How can I dynamically select serializer based on the instance? Thanks -
Postgres complains about non-existant constraint
I am in the progress of migrating our database schema in postgresql and i get this error in Django(1.11.11): django.db.utils.ProgrammingError: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" for relation "djstripe_charge" already exists However executing ALTER TABLE djstripe_charge DROP CONSTRAINT djstripe_charge_account_id_597fef70_fk_djstripe_account_id ; in psql gives the following error: ERROR: constraint "djstripe_charge_account_id_597fef70_fk_djstripe_account_id" of relation "djstripe_charge" does not exist I verified in psql with \d djstripe_charge and it doesn't show up on the relations list In django, the error occurs(90% sure) in the migration code: migrations.AddField( model_name='charge', name='account', field=models.ForeignKey(help_text='The account the charge was made on behalf of. Null here indicates that this value was never set.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='charges', to='djstripe.Account'), ), Why does dhango complain about this? -
How to add css to the default form elements in django
I am making an app which has login page. I am using default django username and password fields.I want to add some css to it.How can we modify the default style and make it look good My HTML is of this form <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Purple Admin</title> <link rel="stylesheet" href="{% static 'css/materialdesignicons.min.css' %}"> <!-- plugins:css --> <link rel="stylesheet" href="{% static 'css/perfect-scrollbar.min.css' %}"> <!-- endinject --> <!-- plugin css for this page --> <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}"> <!-- End plugin css for this page --> <!-- inject:css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- endinject --> <link rel="shortcut icon" href="{% static 'images/favicon.png' %}"> </head> <body> <div class="container-scroller"> <div class="container-fluid page-body-wrapper"> <div class="row"> <div class="content-wrapper full-page-wrapper d-flex align-items-center auth-pages"> <div class="card col-lg-4 mx-auto"> <div class="card-body px-5 py-5"> <h3 class="card-title text-left mb-3">Login</h3> <form method="post" action="{% url 'login' %}"> <div class="form-group"> <label>Username: </label> {{ form.username }} </div> <div class="form-group"> <label>Password: </label> {{ form.password }} </div> <div> {% if form.errors %} <font color="red">Your username and/or password didn't match. Please try again.</font> {% endif %} </div> <div class="form-group d-flex align-items-center justify-content-between"> <a href="#" class="forgot-pass">Forgot password</a> … -
A web app for users to easily create banners for my website (Python, Django/Flask)
I have a need to build a new tool to help me with my job and I wonder if anyone here can give me any advice. I want to build a simple website using Flask and Python (no issues there) that lets users create one of four types of banner for our website. The process would be something like: A. User goes to website url B. User enters the following information: Booking reference number (essential) Type of banner (drop down list) Upload jpeg C. The programme checks the dimensions of the uploaded image against the type of banner selected. If false, display some error text If true, move on D. User is asked to select some promotional text from a drop down menu E. The programme finds the matching image (stored in a database?) and places it over the submitted image F. The result is displayed to the user. User approves by pressing a submit button G. The image is sent to a location that I can access There's lots of ways I want to expand this but, this would save me up to 3 weeks worth of work every month and give some time to do some thinking. I … -
Error Could not import 'django.views.defaults.server_error'
In the error logs for a Django site my error logs are filled with thousands of these errors: ViewDoesNotExist: Could not import 'django.views.defaults.server_error'. Parent module django.views.defaults does not exist. For all different views. Judging by the timestamps it looks like a bot hammers my site making multiple requests every millisecond, thousands in total and these errors get produced. Is there a way of finding out what the actual exception is and any solutions? -
How do I reference a matplotlib plot returned from a view in an html template in Django?
I am trying to interactively display plots from matplotlib in django. From this answer, I see that I can send the plot from a view with this code: response = HttpResponse(mimetype="image/png") # create your image as usual, e.g. pylab.plot(...) pylab.savefig(response, format="png") return response So the view sends the plot as an Httpresponse, but how do I reference that in the html code of the template? I'm guessing it will be something like this but am having a tough time finding examples of html code: <img src={ some reference to the plot here }> Again, I think I can generate the plot in with a view but am not sure how to reference that output in the html template. -
Django request.get_full_path is not working on mobile
Does anyone know why {% if request.get_full_path %} is not working on mobile browser? It just works as expected on desktop. -
Difference between save() and pre-save and post-save
**I'm a newbie in Django and I have the following questions, and I need your advice.the Django documentation is not enough for me as it is missing the examples ** **here we put .save() function: and don't know should i use pre/post ** def update_total(self): self.total=self.cart.total+self.shipping_total self.save() in the postsave function we didtn't put save() def postsave_order_total(sender,instance,created,*args,**kwargs): if created: print("just order created ") instance.update_total() post_save.connect(postsave_order_total,sender=orders) and with m2m signal we put .save function , is it true and if it is why we didn't put .save() in pre_save or post_save() def cal_total(sender,instance,action,*args,**kwargs): # print(action) if action=="post_add" or action=="post_remove" or action=="post_clear": prod_objs=instance.products.all() subtotal=0 for prod in prod_objs: subtotal+=prod.price print(subtotal) total=subtotal+10 instance.total=total instance.subtotal=subtotal instance.save() m2m_changed.connect(cal_total, sender=cart.products.through) in the m2m signal why I specified the action: if action=="post_add" or action=="post_remove" or action=="post_clear" Also in the the update , i didn't use save() with it qs = orders.objects.filter(cart=instance.cart,active=instance.active).exclude(billing_profile=instance.billing_profile) if qs.exists(): qs.update(active=False)