Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
join 2 models through another model which they have a foreign key to it
i have 3 models temp1,temp2,temp3 which temp1 and temp2 have foreign keys to temp3.id. that means that temp1 and temp2 are related through temp3.id. Class temp1(models.Model): temp3 = models.ForeignKey('temp3', verbose_name=u"temp3", null=True, blank=True) i_y = models.IntegerField('i_Y',null=True, blank=True) iq = models.FloatField('IQ', null=True, blank=True) class temp2(models.Model): temp3 = models.ForeignKey('temp3', verbose_name=u"temp3", null=True, blank=True) q_y = models.IntegerField('Y', null=True, blank=True) eq = models.IntegerField('EQ', null=True, blank=True) q_c = models.CharField('category', max_length=1000, null=True, blank=True) class temp3(models.Model): title = models.CharField(_('Title'), max_length=400, null=True, blank=True) how can i do full outer join on temp1 and temp2 models using django ORM? Indeed i want to do an sql query like this with Django ORM: select temp3.title, temp1.i_y, temp1.iq, temp2.eq,temp2.q_c, temp2.q_y from (select temp1.i_y, temp1.iq, temp1.temp3_id AS first_table_id,temp2.temp3_id AS second_table_id,temp2.eq, temp2.q_c, temp2.q_y from temp1 full outer join temp2 on (temp1.temp3_id = temp2.temp3_id AND temp1.i_y = temp2.q_y)) AS t left outer join temp3 (t.first_table_id = temp3.id OR t.second_table_id = temp3.id) -
How to iterate over json object in python containing dictionary and list
{'PCCandidateDetails': {'BatchId': '456279', 'Candidate': 'Noori sahi ', 'CandidateId': '9124657', 'CenterName': 'K', 'ProjectName': 'PKKVY', 'QPName': 'Domestic Data Entry Operator(SSC/Q2212)', 'TrainingProviderName': 'OrionEdutechPrivateLimited'}, 'PCTestScores': [{'MaxScore': 12, 'PCId': 'SRC/N3022_PC1', 'PCName': 'obtain sufficient information from the customer /client to understand the need and perform initial task', 'Percentage': 0, 'YourScore': 0}, {'MaxScore': 15, 'PCId': 'SRC/N3022_PC10', 'PCName': 'compares transcribed data, as displayed on a visual screen, document and corrects any errors with the source', 'Percentage': 0, 'YourScore': 0}, {'MaxScore': 5, 'PCId': 'SSC/N3022_PC11', 'PCName': 'obtain help or advice from specialist if the problem is outside his/her area of competence or experience', 'Percentage': 0, 'YourScore': 0}]} I want to loop over this json object which I have got using web request. import requests,ast r = requests.get("some url") data = r.text data_dic = ast.literal_eval(data) When I try to loop over the Json I am not able to fetch the expected output in key- Value pair. I want output like this BatchId : 456279 Candidate : Noori sahi CandidateId :9124657 ... and so on. Below code is My approach but dictionary inside the list is causing problem in looping. for i in data_dic: for k,v in i.iteritems(): print k,v What I'm getting as error is 'str' object has no attribute 'iteritems'. … -
if form.is_valid() always false
I'm learning Django 1.11 and I'm creating a form with "widget_tweaks" tools. Could you please tell me what's wrong in my code and why the "form.is_valid()" always return false ? views.py #-*- coding: utf-8 -*- from django.shortcuts import render from .forms import MinimumRegisterForm # Create your views here. def view_about(request): return render(request, 'about.html', locals()) def view_first(request): return render(request, 'first.html', locals()) def view_second(request): form = MinimumRegisterForm(request.POST) if form.is_valid(): identifiant = form.cleaned_data['identifiant'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirm_password = form.cleaned_data['confirm_password'] code = "1" return render(request, 'second.html', locals()) template : second.html <div class="MinimumRegisterForm"> {% if code == "1" %} <p>Formulaire suivant</p> {% elif code == "0" %} <p>Une erreur est survenue</p> {% endif %} {% if not code %} <form action="{% url 'second' %}" action="POST"> {% csrf_token %} <p>{{ form.identifiant|add_class:"form-control"|attr:"placeholder:Quel sera votre identifiant unique ?" }}</p> <p>{{ form.email|add_class:"form-control"|attr:"placeholder:Indiquez-y votre email !" }}</p> <p>{{ form.password|add_class:"form-control"|attr:"placeholder:Créer votre mot de passe ici." }}</p> <p>{{ form.confirm_password|add_class:"form-control"|attr:"placeholder:Retaper votre mot de passe." }}</p> <input class="btn btn-lg btn-primary" type="submit" value="Continuer"> </form> {% endif %} forms.py from django import forms class MinimumRegisterForm(forms.Form): identifiant = forms.CharField( max_length=50, label="Choisissez un identifiant unique", ) email = forms.EmailField( label="Votre adresse mail", ) password = forms.CharField( widget=forms.PasswordInput, label="Entrer un mot de passe", ) confirm_password = … -
RStudio like authentication for Jupyterhub
I am trying to configure Jupyterhub using these instructions. However, instead of Github authentication I would like to use either 1) Rstudio server like authentication where credentials are the same as linux user ones, or 2) I would like to integrate it with my Django app where the users can login through the Django app login credentials. Something like Coursera has done here: https://hub.coursera-notebooks.org/hub/login (maybe with a different framework) How can i do it? -
Django Override Admin App with custom data per group
I'm trying to create a custom template for this part of the Django admin. I already know how to override the forms for custom apps, but now i'm stuk here. I need to change the following part of the django admin page: I need to create custom results in base of the user's group. How can i override this template and set a custom query? Any advice? Thx -
Python/Django - How to get the page URL before navigating to a new view
I have a link that links to a url, like so: <a href="{% url 'sign_in' %}" title="Click here to sign in">Sign in</a> This links to a new view in Django, my URL pattern looks like this: url(r'^sign-in/', sign_in, name="sign_in") In my sign_in view, I would like to have access to the URL where the user originally clicked the link. Specifically, I would like to add this URL has a parameter on the sign_in view URL. For example: The user clicks 'Sign in' The website navigates to example.com/sign-in/?returnUrl=example.com/whatever How can I achieve this in Django? My sign_in view looks like this... so far I the sign_in view redirects to the actual view/template where the user can sign in, appending a returnUrl parameter to a 'sign_in_page' URL: from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.core.urlresolvers import resolve def sign_in(request): return HttpResponseRedirect(reverse('sign_in_page') + '?returnUrl=example.com/whatever') def sign_in_page(request): return render(request, 'sign-in.html') -
"ImproperlyConfigured: The SECRET_KEY setting must not be empty" but SECRET_KEY is set
I'm working with Django 1.11 and Apache 2.2. My SECRET_KEY suddenly stopped working, I'm getting an error "ImproperlyConfigured: The SECRET_KEY setting must not be empty." even though the SECRET_KEY is definitely set in my settings.py -- settings.py SECRET_KEY = ['yaddayaddayadda'] I know that there are lot of similar questions and I've read many of the answers and I still don't understand what's going wrong here. It was working and to me it seemed like it suddenly stopped working. Deleting the *.pyc files did not help. manage.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") wsgi.py path_1 = '/home/path/proj_website/mysite' sys.path.append(path_1) path_2 = '/home/path/proj_website/mysite/mysite' sys.path.append(path_2) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") -
Images modelformset does not Validate and the boolean feature of featured image is not validated too
I have this modelformset that I want it to be validating when no image is attached, to alert the User and there fore it shouldn't save. (atleast 1 image should be attached). The same for the featured option too, if no image is checked to be featured, it shouldn't save. forms.py In the forms.py when I try this when I include form=ProductImagesForm as an argument in the ImagesFormset, the form doesn't save and nothing happens, when I remove it. It saves with out any validation performed class ProductImagesForm(forms.ModelForm): media = forms.ImageField(label='Image') featured_image = forms.BooleanField(initial=True) def __init__ (self, *args, **kwargs): super(ProductImagesForm, self).__init__(*args, **kwargs) self.fields['featured_image'] = forms.BooleanField( widget = forms.RadioSelect( attrs={'checked': True}, choices=((self.prefix, 'featured_image')),)) class Meta: model = ProductImages fields = ['media', 'featured_image'] def clean(self): media = self.cleaned_data.get("media") featured_image = self.cleaned_data.get("featured_image") if media is None: raise forms.ValidationError("Atleast 1 image is required") if featured_image is None: raise forms.ValidationError(" atleast 1 image should be checked as featured") ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=5) views.py class ProductCreateView(SellerAccountMixin, CreateView): form_class = ProductModelForm template_name = 'products/form.html' submit_btn= "Add Product" def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) def form_valid(self, form, formset): return HttpResponseRedirect(self.get_success_url()) def get(self, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = … -
How can I get back this in the admin panel of every user using AbstractBaseUser in Model
as you can see the picture, i am using AbstractBaseUser to customize my model User, but I cant add or delete permissions like this for a user which i could do in another django project, can any one tell how can i get back this for all the users in the admin panel? -
user type, parent, send all in form is better?
This is my Form, I think put parent, user_type, send email all in form's save is good choice, do you have more better solution? tell me the reasons. class StaffForm(forms.ModelForm): class Meta: model = User fields = ['name', 'email', 'perms'] def save(self, parent): user = super(StaffForm, self).save() user.parent = parent user.user_type = UserType.get_type(settings.STAFF) user.save() # send email return user class UserType(models.Model): name = models.CharField(max_length=200, choices=settings.USER_TYPES, unique=True) @classmethod def get_type(cls, user_type): return UserType.objects.get_or_create(name=user_type)[0] -
Django with MySQL "BLOB/TEXT column key specification without a key length"
I'm working on a Django project, which used an SQLite database during the early development. I've started over with a MySQL database to put wood behind the arrow. Amongst others the Django app has this model: class User(models.Model): name = models.CharField(max_length=255, unique=True) context = models.TextField(unique=True) Previously CharField(max_length=8192, unique=True) was used, but that did not work out with MySQL as there's this constraint: MySQL does not allow unique CharFields to have a max_length > 255. Thus it was changed to a TextField. python manage.py check worked out fine after the change: System check identified no issues (0 silenced). After makemigrations, sqlmigrate and migrate I'm looking at a new issue: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'context' used in key specification without a key length") I did come across this Stackoverflow question, but they're effectively using a BinaryField as a primary key. The context is not used as a primary key, as Django uses their own ID values, from what I know. It must be >255 characters long and unique. How could I resolve this issue? -
Problems with save several images in Django
I have problem with saving files in django. Pls can someone help me? I have form with 2 fields: description and image. By image field user can load several images. To create image field I used django-multiupload app. Also I load data to server by ajax. I tried next code but it riase error. How to fix this problem? Problems with saving image files. From Traceback I understand that problem started in this line of view: article = article_form.save(commit=False) models.py: class Article(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description = models.TextField(_('Description')) class Image(models.Model): article= models.ForeignKey(Article, on_delete=models.CASCADE) image = models.FileField(_('Image'), upload_to='images/%Y/%m/%d/') forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('description', ) image = MultiFileField() def save(self, commit=True): instance = super(ArticleForm, self).save(commit) for each in self.cleaned_data['image']: Image.objects.create(image=each, article=instance) return instance views.py: def article_add(request, project_id): data = dict() project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': article_form = ArticleForm(request.POST, request.FILES) if article_form.is_valid(): article = article_form.save(commit=False) article.project = project article.save() data['form_is_valid'] = True articles = Article.objects.all context = {'articles': articles} context.update(csrf(request)) data['html_article'] = render_to_string('project/article_list.html', context) else: data['form_is_valid'] = False else: article_form = ArticleForm() context = {'article_form': article_form} data['html_article_form'] = render_to_string('project/article_add.html', context, request=request) return JsonResponse(data) JS: $(function () { var loadForm = function () { … -
Django with Celery and RabbitMQ
I am working an application where I have to send emails asynchronously using Celery and RabbitMQ. What I want know, if there is a possibility to get back a result from the celery worker to check if the email has been sent successfully. -
Django : Raw query fetching values from table
job = jobs.objects.raw('select j.*, v.ip, v.id , v.name from jobs_jobs as j,clientadmin_virtualmachine as v where (j.ip_id)::int = v.id order by j.date desc') While executing this query in pgAdminIII it returns result from both tables as per the query but when I use the same in django view it fetches result from first table only, ignoring the v.ip, v.id , v.name field values. -
django model attribute field empty list
I'm trying to build an online forum. Right now, my forum model has several attributes and one of it is "owner", which is a ForeignKey to the user that created this forum. It also has another attribute "passcode" which makes sure that whenever an owner creates a forum, he/she has to type a passcode so that only others with the right passcode can join the forum. Now, I am trying to implement a new function such that users can choose to join existing forums; however, I am stuck. 1) My first issue is that in order to create a custom permission, I first need another model attribute that contains a list of the permissioned users. I was thinking of having a model attribute as an empty list, permissioned_users = [], so that whenever a user requests to join a forum and has the right passcode, his/her username will be appended to the list and then in my views.py I can use @user_passes_test to check if the request.user.username is in the list. However, i'm not sure if "students = []" will work such that i can do "anyparticularinstance".students.append("his name") will work. 2) How do i create a join forum function? I … -
Using pk argument with Django crispy forms form_action
Is there anyway to pass an argument in to a model FormView using django crispy forms? I'm setting the url like: self.helper.form_action = reverse(my_url, args={'pk': self.instance.pk}) I even tried overriding get_form() by doing: form = super().get_form(form_class) form.helper.form_action = reverse(my_url, args={'pk': self.kwargs.get('pk')}) and neither of those worked I keep getting an error thrown saying there is no reverse match where the pk argument is blank. I realize I could just set this in the template, but I'm using an abstract template which also works for loading the form (and just the form) dynamically into modals so that would require me to restructure all of this. -
django-What happens on deploying?
My project is to establish connection between master (pc1) and client (pc2).socket creation code is a part of views.py in pc1 and I have a clientsocket.py batch file in pc2.On executing the socket creation code remotely in other pc (pc2) ,What I found was the socket is still being created in pc1 not in pc2 . So now will deployment help me in creating socket in pc2? or any other possibilities?? -
POST Request in Django
i have been trying to make a post request using postman as my client application. I get the error student_id cannot be null. Besides, i am submitting my request to the url for user, how come it is requesting me to fill student_id which is in the Teachers table? models class User(models.Model): first_name = models.CharField(max_length=200,blank=False) last_name = models.CharField(max_length=200, blank=False) class Students(models.Model): first_name = models.CharField(max_length=200,blank=False) last_name = models.CharField(max_length=200, blank=False) class Teachers(models.Model): first_name = models.CharField(max_length=200,blank=False) last_name = models.CharField(max_length=200, blank=False) students = models.ForeignKey(Student, on_delete=models.CASCADE) serializers class CollegeSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name','last_name') class Meta: model = Students fields = ('id','first_name','last_name') class Meta: model = Teachers fields = ('id','first_name','last_name','student_id') views def user_list(request): if request.method == 'GET': tutorial = User.objects.all() serializer = PeaceSerializer(tutorial, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = PeaceSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.error, status=400) -
Django Naturaltime is not working in .annotate
Here I just wants to annotate a field on a model that gives human readable format saying how much time elapsed since it's created My Model is created 30 seconds ago What I did is here from django.contrib.humanize.templatetags.humanize import naturaltime from django.db.models import F from .models import MyModel m = MyModel.objects.annotate(timesincecreated=naturaltime(F('created_at')) print m.values('timesincecreated') on this print call I am getting the DateTimeField that I used in the model. Any help? TIA. -
(Django/HTML/Javascript) Switching from using an BooleanField to ManytoManyFields in a onClick button function
I've created a Add to function in my project and it work perfectly, but its not very efficient to be use in a huge database. My Question is : How can I change from using BooleanField True or False state to ManytoManyField Here is my code : model.py class ProjectProfile(models.Model): project_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def __str__(self): return self.project_name views.py def index_view(request): context = { "table_list": ProjectProfile.objects.all(), "title": "Table_List" } return render(request, 'index.html', context) def favorite_project(request, projectprofile_id): projectprofile = get_object_or_404(ProjectProfile, pk=projectprofile_id) try: if projectprofile.is_favorite: projectprofile.is_favorite = False else: projectprofile.is_favorite = True projectprofile.save() except (KeyError, ProjectProfile.DoesNotExist): return JsonResponse({'success': False}) else: return JsonResponse({'success': True}) url.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index_view, name='index_view'), url(r'^(?P<projectprofile_id>[0-9]+)/favorite_album/$', favorite_project, name='favorite_project'), ] index.html <head> <meta charset="UTF-8"> <title>Favorite function</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <h1>Favorite Function</h1> <table> <thead> <tr> <th>Name</th> <th>Artist</th> <th>Favorite</th> </tr> </thead> <tbody> {% for data in table_list %}{% csrf_token %} <tr > <td>{{data.project_name}}</td> <td>{{data.artist}}</td> <!-- Favorite Album --> <td><a href="{% url 'favorite_project' data.id %}" class="btn btn-default btn-sm btn-favorite" role="button"><span class=" glyphicon glyphicon-star {% if data.is_favorite %}active{% endif %}" action=""></span></a></td> </tr> {% endfor %} </tbody> </table> </body> javascript var ProjectListPage = { init: function() … -
How to traverse a list which contains many dicts in Django template?
Now,I have a dict in view and want to present in HTML in the form of table: and I pass it into context: context['cities']=cities then,render it: render(request,'index.html',context=context) In 'index.html': <table> <tr> <th>name</th> <th>population</th> <th>country</th> </tr> {% for city in cities%} <tr> <td>{{city.name}}</td> <td>{{city.population}}</td> <td>{{city.country}}</td> </tr> {% endfor %} </table> Unfortunately,it seems that Django template can't support this kind of traverse,so the result can't show successfully as I expected. "td" tags are empty. -
How do I handle %20 into spaces for a django filter for queries?
class SomeFilter(filters.FilterSet): class Meta: model = SomeModel fields = { 'column1': '__all__', 'column2': '__all__' } So basically lets say I have a GET request using this filter like www.someAPI.com/?column2=something%20or%20Another When I apply the filter above, it doesn't work because it's querying column 2 with %20 instead of spaces (which is what is in the sql database) how can I handle this so it queries correctly? -
Django: Can I prevent logged in users from accessing login.html?
I have two general questions: As per the title, is there a way to make users who have an active session running that try to access /login.html be routed to /home.html instead? I'm using Django's default PasswordChangeForm and when a user changes their password, it lets them use their old password. So this works: Old Password: 123456 New Password: 123456 Repeat New Password: 123456 Thanks! -
Django Channels error : failed: WebSocket is closed before the connection is established
I am using Django with django channels I am going off of Andrew Godwins django channels examples the "MultiChat" example I am using Webfaction and Putty to try and get it going here is the code I got: settings.py redis_host = os.environ.get('REDIS_HOST', 'localhost') CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 27411)], }, "ROUTING": "myproject.routing.channel_routing", }, } I do have a question here would I change were it says localhost to my Ip address for my website or would i leave it as localhost when using redis? as for my index.html I have this Not sure if this code needs to be tweaked or updated any help is appreciated thanks. {% extends "base.html" %} {% block title %}MultiChat Example{% endblock %} {% block header_text %}MultiChat Example{% endblock %} {% block content %} <ul class="rooms"> {% for room in rooms %} <li class="room-link" data-room-id="{{ room.id }}">{{ room }}</li> {% empty %} <p class="empty">No chat rooms defined. Maybe make some in the <a href="{% url 'admin:index' %}">admin</a>?</p> {% endfor %} </ul> <div id="chats"> </div> {% endblock %} {% block extra_body %} <script> $(function () { // Correctly decide … -
How to return a queryset from unrelated models that share fields with methods
I have users submit a form with information about their Household to view the total Household Rates on various Plans. Each Plan has a different Rate for each Person based on 'age' and the Household 'area'. Person is a ForeignKey to Household, but they are not related to Rate or Plan. However, the Rate model shares the 'age' and 'area' fields with methods in the Person and Household models. I have a working python solution (see that view here), but I'm trying to use Django querysets so I have access to all of the fields with dot notation in my template. I've read the queryset docs extensively, but I can't figure out how to use them with my models because the Rate and Plan models are not related to Person or Household. Any advice is greatly appreciated. Before trying to Sum, it would look like this: Example Household has 3 Persons: Plan A: Rates: Person 1: $1 Person 2: $2 Person 3: $3 Plan B: Rates: Person 1: $2 Person 2: $4 Person 3: $6 But I need template to return a Household Sum like this: Total for Household: Plan A: $6 Plan B: $12 models.py class Plan(models.Model): name = …