Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which cloud is best for open edX
I want to deploy my open edX devstack. I just want which cloud is best for open edx and why? AWS or Azure. -
Checkout process for django-oscar is not working properly
I have created a eCommerce site using django oscar. When i click on proceed to checkout, after filling shipping address it redirect directly to /checkout/preview/ page it is not going to /checkout/payment-details/ do i need to do any changes in settings or code. -
ImportError at / when deploying application to Azure Cloud
I have a boilerplate application, that I wanted to deploy on Azure. Locally it runs fine, but when I deploy to Azure cloud, I get: ImportError at / cannot import name 'views' from 'eve' (unknown location) I tried changing the import to my eve app.. but I get same error. Here is my traceback: http://dpaste.com/3Q23GMD -
Problems connecting Django project to Oracle
I'm working on PyCharm on a django project version 1.11. I set up the credentials in settings.py: 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xe', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '000.000.000.000', 'PORT': '1521', Obviously not those are not the real credentials. The fact is that PyCharm is already connected to the database, i can see the tables, create new ones etc with the Database Navigator of PyCharm. However, when I try to start the server of django I get this error: error in Terminal Moreover, I already have Instant client installed, I'm working on Mac OS Mojave I would really appreciate if you can help me -
Django asymmetric relationship: return intersect
I'm using Django 2.1.3 with Python 3.6.6. I have two models, a custom User model and a Connection model to track relationships between users, defined as follows: from django.db import models from django.contrib.auth.models import class User(AbstractUser): # (additional fields) connections_sent = models.ManyToManyField( 'self', through='Connection', # through_fields=('from_user', 'to_user'), related_name='connections_received', symmetrical=False, ) def __str__(self): return self.email def add_connection(self, user): connection, created = Connection.objects.get_or_create( from_user=self, to_user=user, ) return connection def remove_connection(self, user): Connection.objects.filter( from_user=self, to_user=user, ).delete() return class Connection(models.Model): from_user = models.ForeignKey(User, related_name='from_users', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='to_users', on_delete=models.CASCADE) class Meta: unique_together = ('from_user', 'to_user') def __str__(self): return "Connection from {} to {}".format(self.from_user, self.to_user) The idea is that (similar to LinkedIn), Users can send connection requests to other users (connections_sent), which the receiving user must confirm before further interaction can occur. I would like to define a function User.get_confirmed_connections(self) which filters connections_sent so that only confirmed connections are returned. I.e. it should return the intersect between connections_sent and connections_received. Can this be done with filters? -
success url to the current url
Im using django class based view and forms.I want the view to stay on the same page after a new message has been submitted. The url is like localhost:8000/chat/messages/username/ where 'username' is the username of the user to which the message is being sent class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'thread.html' form_class = ComposeForm success_url='/' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): thread = self.get_object() user = self.request.user message = form.cleaned_data.get("message") ChatMessage.objects.create(user=user, thread=thread, message=message) return super().form_valid(form) Rn now if i give success_url='./' Its going to locahost:8000/chat/messages/ which results in a 404 error -
Django Crispy forms not using bootstrap 4 to build Accordion
I'm using crispy-forms app for django to bootstrap forms. I'm using bootstrap 4 have no problems when just using the {form|crispy} output but now I want to add an accordion and crispy is generating the HTML for bootstrap 3 instead of 4. I've included in the settings.py the line: CRISPY_TEMPLATE_PACK = 'bootstrap4' My view.py looks like this: from app.models import Model1 from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit from crispy_forms.bootstrap import Accordion, AccordionGroup class Model1Create(CreateView): model = Model1 fields = ['field1', 'field2', 'field3'] template_name = "model1_form.html" def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper() form.helper.add_input(Submit('submit', 'Creates', css_class='btn-primary')) form.helper.layout = Layout( Accordion( AccordionGroup('First Group', 'field1' ), AccordionGroup('Second Group', 'field2', 'field3' ) ) return form Any ideas why this is happening? Or what should I do to force bootstrap 4 html? Thanks in advance for the help! -
Issues to fully delete a hash key in redis
i'm using Redis with Python and Django and i have some trouble with the delete of Redis. I create hash key to store multiple informations about a vehicule, but the user is finished with it, i'm deleting the key with : r = redis.StrictRedis(host=settings.REDIS_AD, port=settings.REDIS_PORT, db='14') key = 'TEST_GMA' r.delete(key) Most of the time the hash gets deleted, but sometimes it only erase part of the hash and i don't understand why since it seem to be very random. -
how can i get username when he/she signup in django?
i want the username when the user signUp class SignUp(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' i need to access the username of the user who has been signed up . -
How to simplified these code with for loop?
Here is my code: phones = Customer.objects.filter(active=True).values('name')\ .annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[0])) .annotate(count1 = Count('phone',filter=Q(phone__model__icontains=model_list[1])) .annotate(count2 = Count('phone',filter=Q(phone__model__icontains=model_list[2])) .annotate(count3 = Count('phone',filter=Q(phone__model__icontains=model_list[3])) .annotate(count4 = Count('phone',filter=Q(phone__model__icontains=model_list[4])) ........ html {% if phones %} {% for phone in phones %} <tr> <td>{{ phone.name }}</td> <td>{{ phone.count }}</td> <td>{{ phone.count1 }}</td> <td>{{ phone.count2 }}</td> <td>{{ phone.count3 }}</td> <td>{{ phone.count4 }}</td> </tr> {% endfor %} {% enfif %} My model_list still got many model, what should I do to simplify these using for loop? If my model_list has 100 model, these will be very complicated. I've tried this: for i in range(len(model_list)): phone= Customer.objects.filter(active=True).values('name')\ .annotate(count = Count('phone',filter=Q(phone__model__icontains=model_list[i])) html {% if phones %} {% for phone in phones %} <tr> <td>{{ phone.name }}</td> <td>{{ phone.count }}</td> </tr> {% endfor %} {% endif %} But the result is not what i want, beacause i only get one of the data. For example : model_list[0] -
Implementing multi layer role on Django
Working with django Group and Permission. Normally works fine. Now want to add sub admin who can give permission only particular model. How to implement? -
Django forms: how to show only objects associated with user in dropdown
I am a vet hospital, with class Pet and class Records. Each pet can have many records, i.e. everytime it visits the hospital it gets a new record. At the moment, my form shows all the pets ever associated with my app (please view https://i.stack.imgur.com/8j7V8.png). I want only the user's registered pets to appear (why would Bob be bringing a stranger's cat to the vet?) View to add a record: @login_required(login_url="/accounts/login/") def record_create(request): #this line retrieves Pets only belonging to the user logged in pets = Pet.objects.filter(author=request.user) if request.method == 'POST': form = forms.CreateRecord(request.POST, request.FILES) print(form) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('records') else: form = forms.CreateRecord() return render(request, 'records/record_create.html', {'form': form,}) forms.py class CreateRecord(forms.ModelForm): class Meta: model = models.Record fields = ['feedID', 'amountLeftOver', 'amountDispensed', 'additionalInfo', 'selectPet'] How do I get the selectPet dropdown to show only Bob's registered pets? Thanks for your time! -
Get Django variable in Javascript : undefined value
I have a little issue and I don't overcome to solve it. I have a list of Django objects generated in my views.py file and I would like to display these variables in my Javascript part. I get the list in my Javascript code, but each variable are 'undefined'. In my views.py file, I have : context['results2'] = SubMethod.objects.values_list('name', flat=True).all() Then, in my HTML/JS part : function get_sub_method_options(keep_cur) { var sel_option = $('select#id_method-group').find("option:selected"); var sel_val = sel_option.val(); if (!sel_val) { $("select#id_method-sub_method").empty(); var all_sub_methods = "{{ results2 }}"; console.log(all_sub_methods.name); for (var i = 0; i < all_sub_methods.length; i++) { $("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods } return; } data = { 'test_method': $('select#id_method-test_method').find("option:selected").val(), 'group': sel_val }; $.ajax({ method: "GET", url: '{% url 'ajax_method_submethod' %}', data: data }).done(function (result) { reset_select('id_method-sub_method'); for (var i = 0; i < result['results'].length; i++) { if (keep_cur > 0 & keep_cur == result['results'][i].id) $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>'); else $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>'); } ; }); } As you can see, I pick up my context variable result2 in this part : if (!sel_val) … -
LinkedIn OAuth2 calling from Django..not working
When I click the LinkedIn Auth link, I am getting this usa url and the document says linkedin.com/oauth2/auth... https://www.linkedin.com/uas/oauth2/authorization?client_id=xxxl&redirect_uri=http:xxx/auth/complete/linkedin-oauth2/&state=xxxEfQE01&response_type=code&scope=r_basicprofile+r_emailaddress In settings.py AUTHENTICATION_BACKENDS = ( 'social_core.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'keys...' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'secret...' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] MIDDLEWARE_CLASSES = [... ... 'social_django.middleware.SocialAuthExceptionMiddleware', ... ] INSTALLED_APPS = [... 'social_django', ...] In html <a href="{% url 'social:begin' backend='linkedin-oauth2' %}">login with LinkedIn Are settings not correct? -
Django - Is the path to my socket correct for nginx configuration
This is in my site1_nginx.conf which is present in the folder /etc/nginx/sites-enabled Now in my site1_nginx.conf , I specified the following upstream django { server unix:/home/ec2-user/FooVenv/FooWeb/site1.socket; # for a file socket } The path to my socket file is /home/ec2-user/FooVenv/FooWeb/site1.socket; However I am not sure if I specified it correct most of the samples I have seen have three leading ///. Currently I am getting the error 2018/11/26 08:40:24 [emerg] 1253#0: invalid host in upstream "/home/ec2-user/FooVenv/FooWeb/site1.socket" in /etc/nginx/sites-enabled/site1_nginx.conf:6 2018/11/26 08:41:37 [crit] 1276#0: *1 connect() to unix:/home/ec2-user/FooVenv/FooWeb/site1.socket failed (13: Permission denied) while connecting to upstream, client: 71.231.182.18, server: qiggz.com, request: "GET /admin/ HTTP/1.1", upstream: "uwsgi://unix:/home/ec2-user/FooVenv/FooWeb/site1.socket:", host: "www.foo.com:8000". I have changed the actual web address to foo for security. Anyways I launched my uwsgi using this uwsgi --socket site1.socket --module main.wsgi --chmod-socket77 -
How to integrate Dialogflow with Django python and consume RESTful APIs?
Good day everyone, I am currently developing a chatbot using Google's Dialogflow and I am really in need of help. I have already seen How to integrate Dialogflow with Django (Python)? but I am still confuse and I have no idea what to do next. Our Django project has already been set up and I have already created my agent in Dialogflow, I also learned how to use ngrok so to connect Dialogflow to fulfillment/webhook. I am new to Django python as well and these are just the things that I've done so far. I've already searched almost, if not all, tutorials/articles/videos on how to integrate Dialogflow to Django python with RESTful APIs and I found none on how to do it. Most tutorial uses Flask and NodeJS as their backend. Although this tutorial uses Flask https://www.pusher.com/tutorials/chatbot-flask-dialogflow/, I tried doing it just to have an idea on how to integrate dialogflow to a backend and call RESTful APIs. I manage to replicate what has been done in the tutorial, but unfortunately, I didn't understood the coding part in the backend or the code in setting up the webhook as I am very new to it. I am really lost right … -
how to change automatically django Formset with each iteration
I would like my formset to change automatically with each iteration but alas it is not the case, it only takes into account the last added value. views.py : class VenteFormView(View): VenteFormSet = formset_factory(VenteForm) template_name = "venteH.html" def get(self, request): return render(request, self.template_name, {'form': self.VenteFormSet()}) def post(self, request, totalvente=0, totalarticle=0): vente_formset = self.VenteFormSet(self.request.POST,error_class=ParagraphErrorList) #try: if vente_formset.is_valid(): for temp in vente_formset: vente =temp.save(commit=True) article = vente.id_article print('article au depart :',article) print('quantité article au depart :', article.quantite) entre = article.quantite entre -= vente.quantite_v if entre >= 0: article = vente.id_article article.quantite -= vente.quantite_v print('article final :', article.quantite) totalvente +=article.prix_de_vente * vente.quantite_v print('Total à payer :',totalvente) article.save() print('article sauve',article.quantite) else: vente.delete() messages.warning(request, 'Stock insuffisant pour cette opération! ') return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente':totalvente}) else: messages.warning(request,'Formulaire invalide!!!') return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente':totalvente}) #except: # vente.delete() # messages.warning(request, 'Recommencer une nouvelle fois, présence !!!') #return render(request, self.template_name, {'form': self.VenteFormSet(),'totalvente': totalvente}) -
Set template and wrapper_class parameters and render single form field not form
Related Q&A. You can consider this question follow up of it My form class is: class RoomForm(ModelForm): room_in_type = forms.ChoiceField(choices = [(elem[0], elem[1]) for elem in filter(lambda x: x[2] == False, memcache.Client().get("room_in_type_choices"))], widget=forms.RadioSelect()) class Meta: model = Room def __init__(self, *args, **kwargs): super(RoomForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = form_action self.helper.label_class = 'col-md-8' self.helper.form_class = 'form-horizontal' self.helper.layout = Layout( InlineRadios('room_in_type', required=True, css_classes="col-md-8", template='some_template.html'), Field('country', required=True, css_class="country-container", wrapper_class ='toto-class'), Field('fb_user', type='hidden') ) relevant part of my template is: {{ form.country | as_crispy_field}} {{ form.room_in_type | as_crispy_field}} in this case: neither template='some_template.html' nor wrapper_class ='toto-class' is considered but if I render {% crispy form%} both field take place. My question is: Isn't it possible, to give those parameters while rendering as single field? -
django Date time input
I need that in my castration form in the part of chckin and checkout it appears a calendar with date and time, so that the usurario does not have to type manually, I tried using widgets, but the input of the form appears like normal input. And I need the calencario with day, month, year and hour and minute models.py from django.db import models import math class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) forms.py from django.forms import ModelForm from django import forms class DateTimeInput(forms.DateTimeInput): input_type = 'datetime' class MovRotativoForm(forms.ModelForm): class Meta: model = MovRotativo fields = '__all__' widgets = { 'checkin': DateTimeInput(), 'checkout': DateTimeInput(), } -
Exclude nested model field in django serializer
So I have two django models but one of them has a field I need to exclude called code. I haven't found a way to exclude this field using the serializer class. class ModelA(models.Model): modelBs = models.ManyToManyField('ModelB') class ModelB(models.Model): # assume all sorts of fields here like name, location, etc.. code = models.CharField(max_length=200) My issue is I can't exclude the modelB code when serializing model A like so: class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA exclude = ('modelBs__code') The serializer above does not work. Anyone know how to go about this? -
Django admin current file path
I can upload files in a section in admin panel. in models.py file = models.FileField(verbose_name="Upload",upload_to='static/teaching/') when I want to see this file it goes like this; http://127.0.0.1:8000/admin/teaching/teaching/1/change/static/teaching/Ads%C4%B1z.png I want it to go like this; http://127.0.0.1:8000/static/teaching/Ads%C4%B1z.png how can I fix this? enter image description here -
How to write raw query in ElasticSearch Django?
I was trying to implement elastic search in Django where I try to use raw query to find data. Now How could I write a raw query? Here is my Code. def searchPage(request): q = request.GET.get('q') if q: # here I try use raw but I'm Getting Error that 'Search' object has no attribute 'raw' titleInfo = GetItem.search().raw("select * from item WHERE title LIKE % %s %", [q]) else: titleInfo = '' return render(request, 'searchPage.html', {'titleInfo': titleInfo}) -
Taking site screenshot whit python and django or javascript
i want create feedback plugin by python-django, in this app user should take screenshot of problem and edit it, which best way for write this plugin? i am using canvas model but in Persian language some part is don't show correct -
Django modify object only during comparsion in custom Lookup Field
I have models like these: class Product(models.Model): id = models.IntegerField(null=False) name = models.TextField(null=False) quantity = models.IntegerField(default=None) price = models.IntegerField(default=None) bar_code = models.ForeignKey(Manufacturer, related_name='manufacturers') class Manufacturer(models.Model): name = models.TextField(null=False) country_of_origin = models.TextField(null=True) local_naming = models.Textfield(null=False) At the beginning, field Manufacturer.local_naming looked like AAA001, AAA002 and so on and this gave me easy way to query less or equal local_naming, because Python handles string comparison very well and Product.objects.filter(manufacturers__local_naming__lte='AAA003) would get me objects with AAA001 and AAA002 as value in relation with class field Manufacturer.local_naming. But naming convenction has changed reciently and I want to preserve custom order - new names contain current year prefix so it looks like this - 18AAA001and Python can't keep my custom order, because '18AAA001' > 'AAA01' returns False, when I wanted True. So I came up with idea to add prefix before those three letters in the name if there's none, so name AAA001 would change to 00AAA001, but what's important, I do not want to modify existing values in any way and because of that I was thinking about creating custom lookup and change the values only for the time of lookup. I wrote this code @Field.register_lookup class LocalNamingLessThanEqual(Lookup): lookup_name = 'ln_lte' def as_sql(self, compiler, … -
Calcul Time on django
I have the following code: def index(request): events_list = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).order_by('-working_hour') total_hours_week = Timesheet.objects.annotate(total_hours_per_week=Sum('working_hour')).filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]) return render(request, "timesheet/index.html", {'events_list': events_list, 'total_hours_week': total_hours_week}) the total_hours_week retun the current error: You cannot use Sum, Avg, StdDev, and Variance aggregations on date/time fields in sqlite3 since date/time is saved as text. Do you know how to fix ? thanks per advance