Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check if a model is in a models foriegn key set? Django, django rest framework
I have a room model which has a many to one relation with a venue. A venue can have many rooms. I am trying to set up my http methods in my rest framework so that way when I add permissions things work well. So if say someone wants to delete a room from a venue, I must make sure that 1 that person has permissions to that venue 2 that room is attached to that venue I would like to get a venue model then get the venue models room_set and check the room_set to see if a room exists with the room primarykey of the model I wish to delete. What I have so far: class GetEditDeleteVenueRoom(APIView): def get(self, request, *args, **kwargs): pass def post(self, request, *args, **kwargs): print('wait its over here') def delete(self, request, *args, **kwargs): venuepk = kwargs.get('venuepk', None) venue = get_object_or_404(Venue, pk=venuepk) venuerooms = venue.room_set print(venuerooms) return Response({}) my hope is I could just interate venue rooms and check each object in venue rooms but I have a strong feeling its not going to work because venuerooms is not python objects? Perhaps it is. I will be updating this question after I do the for … -
Django Authentication Using 3rd Party App
So I'm writing a third-party application in C# to communicate with my Django application. A user registers on the Django application and saves their credentials to a PostGresQL database. I'm encrypting the password with their BCrypt plugin, so the password is stored in the database like so: bcrypt_sha256$$2b$12$R8G3wRDSMV1albrI6.7PT.sv4Po3A1XerBZmP/20hpvdGKRBwi7vi In my C# application, I attempt to login with the following code: NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; Password=PASSWORD;Database=DATABASE_NAME;"); conn.Open(); string query = "SELECT password, setup_stage FROM main_user WHERE email = '" + txtUsername.Text + "'"; NpgsqlCommand cmd = new NpgsqlCommand(query, conn); NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { string[] pass_params = ds.Tables[0].Rows[0]["password"].ToString().Split(new char[] { '$' }, 2); string myHash = BCrypt.Net.BCrypt.HashPassword(txtPassword.Text, pass_params[1]); if (myHash.Equals(pass_params[1])) { int stage = Convert.ToInt32(ds.Tables[0].Rows[0]["setup_stage"]); if (stage == -1) { Setup setup = new Setup(); setup.setStage(stage); setup.Show(); } else { MainForm main = new MainForm(); main.Show(); } this.Close(); }else { lblError.Text = "No username/password match for the credentials entered."; lblError.Visible = true; } }else { lblError.Text = "No username/password match for the credentials entered."; lblError.Visible = true; } My problem is that when myHash is created, is is not creating an equivalent hash. I've passed the correct password, … -
Which payment gateways can be integrated with django? Does Django support any of the existing payment gateways?
I want to build a django website and want to integrate a payment gateway that supports Bangladeshi payment methods. Is it possible? -
Django sum for each distinct value in another field
Say you have a model for order line items: class OrderLine(models.Model): product = models.ForeignKey(Product) quantity = models.DecimalField() unit = models.ForeignKey(Unit) Is it possible to summarize each product's total quantity for each distinct unit in one object? If not, how would you go about displaying it on one line? I've tried this which seems to be sort of on the right track but at the expense of losing the foreign key relationship. lines = lines.values_list('product', 'order_um').distinct().annotate(sum=Sum('order_qty')).order_by('product', 'order_um') -
Django Can't find my template
I've found many questions like this but no one have solved this mine. When I visit the url http://localhost:8000/catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ that is handled by this urls.py path: path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), than my view in the end returns this: I have a view that returns this: return render(request,'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) But I get the template error: TemplateDoesNotExist at /catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ catalog/book_renew_librarian.html Request Method: GET Request URL: http://localhost:8000/catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ Django Version: 2.0.3 Exception Type: TemplateDoesNotExist Exception Value: catalog/book_renew_librarian.html Exception Location: C:\Users\Araujo\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\Araujo\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.4 Python Path: ['C:\\Users\\Araujo\\Desktop\\first_django\\locallibrary', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Wed, 14 Mar 2018 19:19:10 +0000 But I have the template in the \catalog\templates\book_renew_librarian.html How to solve it? -
Django Formset: saving only the first form of formset
SubTaskFormSet are my SubTasks Forms that i'm having troubles to save properly. In html template i'm dynamically adding/removing inputs thats correspond to elements of my formset, the problem is: only the first form from de formset is being saved. This is how its being created the formset(extra=1 displays 1 input when page loads). SubTaskFormSet = inlineformset_factory(Task, SubTask, form=SubTaskCreateForm, extra=1) This is how im passing the formset to context dict in "get_context_data" method from TemplateView context['form_sub_tasks'] = SubTaskFormSet(self.request.POST or None) Saving a task form and forms of the formset: if all((task.is_valid(), sub_tasks.is_valid())): task.user = self.request.user task = task.save() sub_tasks.instance = task sub_tasks.save() I noticed that when the value of this field changes, the equivalent number of forms from formset is successfully saved in database. <input name="sub_tasks-TOTAL_FORMS" value="1" id="id_sub_tasks-TOTAL_FORMS" type="hidden"> So my question is: how can i change this TOTAL_FORMS input to be possible save more than one form from formset? Of course it could be done via javascript or manually but i'm searching for a better way to accomplish it. -
Django get value in a single currency based on exchange rate
I have a model which has amounts donated in different currencies. Schema: class Donation(BaseSiteModel): """Donation to Fundraising Project""" donor = models.ForeignKey(UserProfile, related_name='donations', on_delete=models.PROTECT) amount = models.DecimalField(max_digits=12, decimal_places=2, default=0) currency = models.SmallIntegerField(choices=CURRENCIES, default=C_USD) Also, I have a table that contains exchange rates. class CurrencyExchangeRate(models.Model): from_currency = models.SmallIntegerField(choices=CURRENCIES) to_currency = models.SmallIntegerField(choices=CURRENCIES) rate = models.DecimalField(decimal_places=3, max_digits=10) Now, in order to get the sum of donations by a donor based on currency, the query will be Donation.objects.filter(donor=donor).values('currency').annotate(total_amount=Sum('amount')) The output should be something like [{'currency': 1, 'total_amount': Decimal('4.50')}, {'currency': 2, 'total_amount': Decimal('10001.00')}] Here I want the amount to be converted in a single currency (suppose USD) and should be sum of USD amount + non USD amount(multiplied by exchange rate) Is there any way to achieve this in a single query? -
Django template tag a model object.
I'm trying to return a different value for my model object rather than the information stored in the field. I'm running this in my html file. I've passed a query of 'localcampaigns' to my html file. In my HTML file I have: {% for campaign in localcampaigns %} <a href="/campaigns/{{campaign.id}}/">{{campaign.title}}</a> {{campaign.time}} {{campaign.event_date}} {{campaign.project_focus}} {% endfor %} So specifically, say I run this and for the {{campaign.project_focus}} I receive the database object of 'community001' - I want to take this and return something different than this 'community001' like "Community Project" I've tried to do this by: {% if '{{campaign.project_focus}}' == 'community001' %} Community Project {% endif %} But I'm unsuccessful. whenever I run != in the template tag, I get the response. So I know that the two don't match. How do I make the two match? Thanks. -
Django get resized image from model
I want to have method that will give me resized image, if i call this method on object, how can i do this with Pillow? my model: class Item(models.Model): title = models.CharField(max_length=255, null=True) img = models.ImageField() def __str__(self): return self.owner.first_name def get_image(self): image = Image.open(self.img) resized_image = image.resize((128, 128)) return resized_image This one always gives me something like that <PIL.Image.Image image mode=RGB size=128x128 at 0x7F001CF92D30> -
Accessing all children of abstract base class in django?
I am still researching whether to use abstract base classes or proxy models for my control panel application. I'm looking at the abstract base classes right now. Assume that I have a few models like this: class App(models.Model): name = CharField(max_length=100) class Meta: abstract = True class CMSMonitorApp(App): alerts = PositiveIntegerField() class PasswordResetApp(App): login = CharField(max_length=100) token = CharField(max_length=100) On the main page of the control panel, I want to display all of the available applications for my users. An easy way to do this would be to get everything that inherits the App abstract class. How can I all of the classes that inherit an abstract base class? -
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.