Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sort queryset by annotated attr from ManyToMany field
Simplest example: class User(models.Model): name = ... class Group(models.Model): members = models.ManyToManyField(User, through='GroupMembership') class GroupMembership(models.Model): user = ... group = ... I want to get list of Groups ordered by annotated field of members. I'm using trigram search to filter and annotate User queryset. To get annotated users I have something like that: User.objects.annotate(...).annotate(similarity=...) And now I'm trying to sort Groups queryset by Users' "similarity": ann_users = User.objects.annotate(...).annotate(similarity=...) qs = Group.objects.prefetch_related(Prefetch('members', queryset=ann_users)) qs.annotate(similarity=Max('members__similarity')).order_by('similarity') But it doesn't work, because prefetch_related does the ‘joining’ in Python; so I have the error: "FieldError: Cannot resolve keyword 'members' into field." -
TypeError: view must be a callable or a list/tuple in the case of include
First off I apologize for asking this question again as apparently others have. I am having trouble with this and have been receiving the error that you see in the title of the post. I'm following along with the tutorial and have understood it up to this point. I'm not even really sure what the method does. So first off if someone can answer that it would be appreciated. Secondly, how do I fix that error. I realize I must have Django's old syntax. How would I fix that? views.py(I created this file under my root directory) from django.shortcuts import render def index(requests): return render(request, 'index.html', {}) urls.py (also under root directory) urlpatterns = { url(r'^$', 'post.views.index'), url(r'^admin/', admin.site.urls) I have an html file called index is in my template/layout Thanks to anyone who might be able to help. I realize this is probably a total noob question. -
How to parse (Decimal('str'),) with python
in my view i make a call to a stored procedure that return to me the ID of the entry it created. I need to use this id as arguments for another stored procédure. My problem is that the result of the first query is : (Decimal('1046'),) and of course wont fit as argument for the second procedure. How can i parse it to only get the '1046' ? -
I am getting this error Forbidden (csrf token missing or incorrect.)
I am fairly new to python/django. But my code has been running perfectly fine. And now I am suddenly getting this error. My code is about file upload. I have added {% csrf_token %} in the view. The "django.middleware.csrf.CsrfViewMiddleware" is in the settings file. And I am returning the response with the render () function. Is there anything that I need to check on? I have been running/testing this code for a week or so and now suddenly this error is popping up. I am not sure how to debug it. Thanks in advance, Vrunda -
Django Forms - Custom Date Input
I am having an issue clearing a date through the following form: class CreateArtistProfile(forms.ModelForm): focus_str = forms.CharField() birthdate = forms.DateField(input_formats="%d %B, %Y") occupation = forms.CharField(required=False) tagline = forms.CharField(required=False) class Meta: model=ArtistAccount fields = ['artist_name', 'location', 'occupation', "type_label", "map_input", "tagline", "birthdate"] I am using Materialize's datepicker, and trying to submit the date string it gives me. If I select a date, the field value looks like this 30 September, 2004 But Django continues to reject it: ('birthdate', 'Enter a valid date.') I think I've set the correct date formats. Am I doing something else wrong? -
Fetch picklist values through SOQL query in Salesforce
I am using Djnago & Salesforce. I establish connection between them through simple-salesforce I have created a custom picklist on Contact Object of Salesforce. I wont to fetch all the 20 values of my picklist & display in Django. I am looking for SOQL to fetch values from Salesforce. sf = Salesforce(instance_url='https://test.salesforce.com', session_id='') sf1 = Salesforce(connection parameters) sf3 = sf1.query("SELECT Color__c FROM Contact") sf3 will give me values set for respective Contact records. I want to fetch all the 20 values I have entered while creating Color__c on Contact object. In Apex we can do that, something like below public class PicklistUtil { public static List<Schema.PicklistEntry> getContactColor() { return Contact.Color__c.getDescribe().getPicklistValues(); } } I am looking to do the same in Django. Can someone please help? -
using Spring Boot JWT for authentication in DJango
My understanding is that the JWT is composed of a header, payload, and secret and is put together like something below I have a REST server that uses services to access data stored upon it. Some of the data is in an Oracle DB. From what I can see, one would "consume" the REST services from DJango side as seen below by using something like urllib3. def get_books(year, author): url = 'http://api.example.com/books' params = {'year': year, 'author': author} r = requests.get('http://api.example.com/books', params=params) books = r.json() books_list = {'books':books['results']} return books_list Src 1 proper-way-to-consume-data-from-restful-api-in-django Src 2 how-do-you-get-django-to-make-a-restful-call In the same message above ("Src 1"), it is mentioned that perhaps access to REST services can take the place of accessing data from thea database: If the service allowed for CRUD, you might opt for per-verb functions in service.py - get_book, put_book, delete_book etc. In using REST, the idea is that they (REST functions) can be called from Andriod, IOS, etc. The goal was to write the code once and use it in as many places as possible. In the example above, my understanding is that if one wanted to secure the services, one would use JWT. Since the server code was using … -
Django - Return Pdf and JsonResponse using same class instance
I have a view that return a JsonResponse. I want to generate a pdf report using the Building instance (the structure variable). For example, the view that return the JsonResponse is: @login_required def buildings(request): if request.POST and request.is_ajax(): s_form = BuildingForm(request.POST) if s_form.is_valid(): structure = Building(**s_form.cleaned_data) html = render_to_string('wind/results/buildings/buildings_results.html', {'structure': structure}) return JsonResponse({"result": html}) else: return JsonResponse({'building_errors': s_form.errors, status=400) else: s_form = BuildingForm() return render(request, 'wind/buildings.html', {'s_form': s_form}) I have the following code for generate and return the pdf: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Report.pdf"' buffer = BytesIO() report = BuildingsReport(structure) # I want to use the same Building instance pdf = report.generate_pdf() response.write(pdf) return response What I want is use the same building instance for generating the pdf and the html variable. Using a different view to return the pdf implies a new Building instance. Except that there is another solution that solves the problem using another view. In the Frontend I want to show the JsonResponse and have the pdf available for the user to download using a html button. Using Celery is adecuated for this task? Thanks in advance! -
Updating custom user profile
In my web app, I need two users, regular site users and employees. I am using a custom user based on AbstractUser to achieve this. class CustomUser(AbstractUser): pass class Employee(CustomUser): user = models.OneToOneField(settings.AUTH_USER_MODEL) # other fields In settings.py I have: AUTH_USER_MODEL = 'app.CustomUser' I want to provide a profile page for both the regular site user and the Employee user. First, I created a form called UserProfileEditForm for regular site users: class UserProfileEditForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and get_user_model().objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): user = super(UserProfileEditForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user the corresponding view: @login_required def user_profile_edit(request): user = get_user_model() if request.method == 'POST': form = UserProfileEditForm(request.POST, instance=request.user) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() return redirect('user_profile') else: form = UserProfileEditForm(instance=request.user) return render(request, 'user/user_profile_edit.html', { 'form': form }) and the form: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Update Information</button> </form> In the edit user profile page, I see the email rightly … -
Can I make 'get_absolute_url' return a related modal DetailView?
first-time poster, long-time lurker. Hopefully someone can help me figure this one out. So I have a Django project that includes a model named 'Artist'. I've created the detail view showing all the variables associated with this model (yay!) Now I want to include a comment feature for each artist, so I've created a model named 'ArtistComment': class ArtistComment(models.Model): author = models.ForeignKey(User, default=1) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='artistcomment') message = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) def approve(self): self.approved_comment = True self.save() def get_absolute_url(self): return reverse('events:artistdetail', kwargs={'pk': self.pk}) def __str__(self): return self.created_at.strftime('%H: %M - %d %b') My urls.py looks like this: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), My ArtistComment CreateView looks like this: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['artist', 'message',] def form_valid(self, form, **args): form.instance.author = self.request.user self.object = form.save() return super(ArtistCommentCreate, self).form_valid(form) And finally the URL in the ArtistDetail view looks like this: <a data-toggle="modal" data-target="#artistcommentModal" href="{% url 'events:artistcomment-add' %}">Add A New Comment</a></p> (I'm using a modal div to make the form pop-up) My issue is that when I submit a new comment the 'get_absolute_url' returns the Primary Key from the ArtistComment, rather than the Artist the ArtistComment is related to. How would I make the … -
Python Django Wagtail, multiprocessing for search through PDF files
I have encountered a bit of a challenge, with searching through a library of PDF files for a given string. I do understand that going through a PDF file for a string is not an exact science but having used pyPdf and re libraries i have reasonable reusults. This is an example piece of code i found online which works for me def fn_search_pdf(my_dict): # xfile : the PDF file in which to look # xString : the string to look for import pyPdf, re PageFound = -1 print my_dict pdfDoc = pyPdf.PdfFileReader(file(my_dict['xFile'], "rb")) for i in range(0, pdfDoc.getNumPages()): content = "" content += pdfDoc.getPage(i).extractText() + "\n" content1 = content.encode('ascii', 'ignore').lower() ResSearch = re.search(my_dict['xString'], content1) if ResSearch is not None: PageFound = i #q.put(id) my_dict['q'].append(my_dict['id']) #print 'list',my_dict['q'] break def do_pdf_search(object,xString): procs = [] manager = Manager() res = [] temps = manager.list() pool = Pool(processes=1) list_dicts = [] for index, pdf in enumerate(object): for p in pdf.document_en: path = '/var/www/my/path/media/documents/'+os.path.basename(p.value.url) #path = 'E:/my/path/media/documents/'+os.path.basename(p.value.url) list_dicts.append({'xFile': path, 'xString': xString, 'q': temps,'id': pdf.id}) pool.map(fn_search_pdf, list_dicts) pool.close() pool.join() return temps do_pdf_search(Newsletters.objects.all(),'the string i'm looking for') on my windows machine it works just fine when i launch the Django service through python manage.py runserver 0.0.0.0:9988 … -
Django RF Writable Nested Serializers
I am trying to make a writable nested serializer in DRF3. I have a model Concert with a m2m field 'technicians' to my User-model. I have successfully added a list of the Users that is connected to the Concert instance in it's view. Now I want to be able to add technicians/Users to the Concert-model. This is my serializer so far: class ConcertListSerializer(serializers.ModelSerializer): technicians = UserDetailSerializer( many=True, read_only=True ) class Meta: model = models.Concert fields = [ 'name', 'date', 'technicians', 'stage', 'id', ] def create(self, validated_data): # list of pk's technicians_data = validated_data.pop('technicians') concert = Concert.object.create(**validated_data) for tech in technicians_data: tech, created = User.objects.get(id = tech) concert.technicians.add({ "name": str(tech.name), "email": str(tech.email), "is_staff": tech.is_staff, "is_admin": tech.is_admin, "is_superuser": tech.is_superuser, "groups": tech.groups, "id": tech.id }) return concert I want to be able to just add a list of the pk/id of the technicians I want to add. So for example: "technicians": [1,2,3] adds user 1, 2, 3 to Concert's technicians-field. Whenever I do this, I get KeyError that just says 'technicians' and refers to the first line in my create() function... The fields I am adding in a dictionary are all the fields of the User-model. That is the format they are displayed … -
User regist cannot be done
User regist cannot be done.I wrote in index.html <div class="newaccount"> <h2>New Account registration</h2> <form class="form-inline" action="{% url 'accounts:detail' %}" method="POST"> <div class="form-group"> <label for="id_username">Username</label> {{ regist_form.username }} {{ regist_form.username.errors }} </div> <div class="form-group"> <label for="id_email">Email</label> {{ regist_form.email }} {{ regist_form.email.errors }} </div> <div class="form-group"> <label for="id_password">Password</label> {{ regist_form.password1 }} {{ regist_form.password1.errors }} </div> <div class="form-group"> <label for="id_password">Password(conformation)</label> {{ regist_form.password2 }} {{ regist_form.password2.errors }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> <button type="submit" class="btn btn-primary btn-lg">Regist</button> <input name="next" type="hidden"/> {% csrf_token %} </form> in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if login_form.is_valid(): user = login_form.save() print(1111) print(user) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } print(33333) return redirect('profile', context) context = { 'login_form': login_form, 'regist_form': regist_form, } print(2222) return render(request, 'registration/accounts/login.html', context) in urls.py urlpatterns = [ url(r'^login/$', views.login,name='login'), ] in models.py class UserData(models.Model): user = models.ForeignKey("auth.User", verbose_name="imageforegin") When I wrote in all files and put "Regist" button, it sends next page.But when I see admin site, no data is in there.Terminal shows 2222,so I found program does not pass if login_form.is_valid():,it is ok.I really cannot understand what is wrong.How should I fix this? -
How to make a button-click redirect to another URL, in Django?
I made an HTML-button, in the code shown below: <div style="" class="button-box" > <button>Useradministration</button> </div> When I click on it, I want it to redirect the user to the /admin-url. How should I do this? How do I make Django "know" that the button has been clicked? Thank you so much for your time! -
Django 1.11 don't load static image and show error in main page
I have a new problem: I don't know what is the problem, because I check it move the folder media to eventus folder, but it no working, and I change the path in MEDIA_URL, but it no working too. I think the problem will be in that I follow a tutorial of the version 1.6 of Django and some things are deferents in this new version and I don't know how to do it. my schema of the project is the next . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ … -
Group by and filter django model
I have the following data: 1, Red, Audi 2, Black, Audi 3, Black, BMW I want to get all rows that have both Red and Black colors for the same car. In this case I expect 1 and 2 in result, because Audi is both Red and Black, but not 3, since there is no Red BMW. How to achieve it with django orm? -
How to limit the number of choices in Django admin
Supposing I have two models, Group and Person, where Group is a foreignky field of Person. In the admin page, Group is represented as a drowndown/choice fields for the Person admin. Now, I want the number of choices to be limited to, say, five, and that they should be ordered according to their names. Currently, I have the following code: class PersonAdmin(admin.ModelAdmin): ... def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field.name == 'group': kwargs['queryset'] = Group.objects.order_by('name')[:5] return super(PersonAdmin, self).formfield_for_foreignkey( db_field, request, **kwargs) The problem is that when I try to save the record, I get the following error: AssertionError: Cannot filter a query once a slice has been taken.. I've searched for that error and found a lot of SO threads, but none of them seemed to help me with my case. -
Django Backgroundworker
I have a question to the Backgroundworker/ Django Framework. In my example, I have a Backgroundworker which sent a Websocket message to the Website. The question here: Has each Website call-up his own Backgroundworker Process? Or how can I handle that? -
Django working with external HTMLs
I am writing a small Django local project (with no access to internet). Let's say i have offline standalone version of Wikipedia(I believe it's HTML5 format) as that: . I am trying to write a simple Django front page where user would be able to click a button and be redirected to "wikipedia_for_schools/index.html" from where all the url control will be done by that offline wikipedia stand alone page. How is it possible to make? :/ I have tried creating a link in django template as <a href="/Rachel/modules/wikipedia_for_schools/index.htm" target="content">Click to see wikipedia</a> but that doesn't work cause Django complains that "http://172.30.10.67:8000/modules/wikipedia_for_schools/index.htm" Page not found, my urls.py is just urlpatterns = [ url(r'^$', views.IndexView, name='index'), and i think it's impossible to rewrite each file from wikipedia offline project to Django MVT model to provide urls, models and templates for each link. That's how my Django project structure looks like: And that's how offline Wikipedia index page looks Any help would be highly appreciated -
programmatically set columns of a tables when populating from a list
I am going to populate a django-tables2 list from a list and I am following the tutorial example: import django_tables2 as tables data = [ {'name': 'Bradley'}, {'name': 'Stevie'}, ] class NameTable(tables.Table): name = tables.Column() table = NameTable(data) My problem is that I do not know which are the fields needed, so it would be nice for me to be able to specify them at runtime from a list of names. E.g.,: needed_columns = ["name"] class NameTable(tables.Table): for field in needed_columns: ADD_FIELD(field, tables.Column()) Is this possible in some way?? -
Django Rest Framework model relations
I'm creating school project, Gallery app. I have next entities: Profile, Album, Image, Tag, Like, Comment. But i'm a little bit confused with relations. I created all, but i'm not sure everything is good. Please check: Profile: class Profile(models.Model): user = models.OneToOneField(User) albums = models.ManyToManyField("albums.Album", blank=True) commented = models.ManyToManyField("comments.Comment", blank=True, unique=False) liked = models.ManyToManyField("likes.Like", blank=True) profile_picture = models.ImageField( blank=True, null=True, upload_to='profile_pics') timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Album: class Album(models.Model): name = models.CharField(max_length=120, blank=False, null=False) owner = models.ForeignKey("profiles.Profile") description = models.TextField( max_length=500, null=True) images = models.ManyToManyField("images.Image", related_name="album_images", blank=True) is_public = models.BooleanField(default=False) timestamp = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Image class Image(models.Model): name = models.CharField(max_length=120, blank=False, null=True) album = models.ForeignKey("albums.Album", related_name="album_id", null=True, blank=True) image = models.ImageField(verbose_name="Image", blank=True, null=True, upload_to='img') description = models.TextField(max_length=500, null=True, blank=True) comments = models.ManyToManyField("comments.Comment", related_name="all_comments", blank=True, unique=False) likes = models.ManyToManyField("likes.Like", related_name="all_likes", blank=True, unique=False) tags = models.ManyToManyField("tags.Tag", related_name="all_tags", blank=True) is_public = models.BooleanField(default=False) timestamp = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Tags class Tag(models.Model): name = models.CharField(max_length=120, blank=False, null=False) images = models.ManyToManyField("images.Image", blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Likes class Like(models.Model): owner = models.ManyToManyField("profiles.Profile") image = models.ManyToManyField("images.Image") timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Comments class Comment(models.Model): owner = models.ManyToManyField("profiles.Profile", unique=False) image = models.ManyToManyField("images.Image", unique=False) content = models.TextField(max_length=500, blank=False, null=False) timestamp = models.DateTimeField(auto_now_add=True) … -
Where can I learn Django with examples? [on hold]
I want to learn Django (intermediate level). Where can I get some good tutorials/books to learn Django? -
How to bind/trace django cache variable
I would like to save some value in Django cache and bind a trace function to it, so as soon as the value changes I would like to call a function. After the trace function has been called I would like to remove the bind. Django Cache Code. from django.core.cache import cache cache.set("MyVariable", value, None) cache.get("MyVariable") Pseudo Code: def callbackFunction(): print cache.get("MyVariable") cache.unbind("MyVariable", callbackFunction) def runOnce(): cache.bind("MyVariable", callbackFunction) # Bind Cache Variable runOnce() cache.set("MyVariable", 123, None) cache.set("MyVariable", 999, None) Expected printed result: 123 -
How can I inspect a ValidationError exception while testing with django TestCase?
I'm working with Django testing using a django.test.TestCase and I would like to know the pythonic way to inspect a validation error. I've come up with the below, which works, but it feels a little long winded and prone to error over a large number of tests self.valid_account.contact_number = "1234567" # Too short with self.assertRaises(ValidationError): try: self.valid_account.full_clean() self.fail("Did not raise validation error") except ValidationError as e: self.assertTrue('contact_number' in e.message_dict) raise e Is there a better way to inspect and test an exception? -
Heroku not loading procfile
I've tried other peoples solutions to getting there procfile recognised and it's just not working for me. Really confused about how I can get heroku to recognize my Procfile! I've moved it around into different folders and whatnot but it just won't recognise it. web: waitress-serve --port=$PORT alex1.wsgi:application This is my code. It's sitting right next to my requirements.txt file which is getting picked up by heroku fine. using echo to create the file or even echo is not working. https://github.com/Hewlbern/Videography-Website/tree/master/Alex1 <--- the github link that I'm trying to deploy to heroku from. Can see where i've placed it and etc if anyone can help! Such sad, many mad.