Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detect duplicate inserts when adding many-to-many relation
Let's assume there are two models, A and B: class A(models.Model): name = models.CharField(max_length=100) class B(models.Model): children = models.ManyToManyField(A) I'm using b.children.add() method to add instance of A to b: a = A.objects.get(pk=SOMETHING) b.children.add(a) As far as I know, Django by default doesn't allow duplicate many-to-many relationship. So I cannot add same instance of A more than once. But the problem is here, I fetch instances of A with another query, then loop around them and add them one by one. How can I detect a duplicate relation? Does add() method return something useful? -
Django on_delete CASCADE won't delete related objects
I'm trying to make Content object deleted right after I delete Post object. I've setted up my testing database like that: def setUp(self): Post.objects.all().delete() Content.objects.all().delete() date1 = datetime.now() date2 = datetime.now() date3 = datetime.now() date1 = date1.replace(year=2017, month=12) date2 = date2.replace(year=2017, month=11) date3 = date3.replace(year=2017, month=10) content1 = Content.objects.create(polish_content='Jakiś tam polski kontent dla posta 1', english_content='Some english content for post 1', polish_link='polski-link-1', english_link='english-link-1') self.deleted_content = content2 = Content.objects.create(polish_content='Jakiś tam polski kontent dla posta 2', english_content='Some english content for post 2', polish_link='polski-link-2', english_link='english-link-2') content3 = Content.objects.create(polish_content='Jakiś tam polski kontent dla posta 3', english_content='Some english content for post 3', polish_link='polski-link-3', english_link='english-link-3') Post.objects.create(content=content1, author='durpal', category='cats', date=date1) self.post = Post.objects.create(content=content2, author='bartek', category='cats', date=date2) Post.objects.create(content=content3, author='piotr', category='snakes', date=date3) User.objects.all().delete() User.objects.create_user('bunny', 'some@mail.pl', 'p455w0rd') And I have my test like that: def test_can_delete_post(self): c = Client() c.login(username='bunny', password='p455w0rd'), response = c.post('/delete_post/', {'id': '2'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response = c.post('/delete_post/', {'id': '1'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response_content = json.loads(response.content) self.assertEqual(1, Post.objects.count()) self.assertEqual(1, Content.objects.count()) with self.assertRaises(Post.DoesNotExist): Post.objects.get(author='bartek') self.assertTrue(Content.objects.get(english_link='english-link-2') == None) self.assertEquals('OK', response_content['status']) But line: self.assertEqual(1, Content.objects.count()) shows, that there is 3 Contents instead of one, Posts are being deleted successfully. In my model, it looks like: class Post(models.Model): content = models.ForeignKey(Content, on_delete=models.CASCADE) -
Django admin display custom list below change form
My question has two parts. How do I call a separate queryset (aside from the default one) such as Appointments.objects.all() in the template extending change_form.html? I've hoped to pass context variables just I would with a normal view. But I don't know how to pass them specifically for the admin views. I pursued redefining the default query set with something like this In admin.py def get_queryset(self, request): qs = super(PatientAdmin, self).get_queryset(request) return qs.filter(first_name = 'Luke') Functionality aside the above code only changes the default queryset rather creating a new one. And secondly how would I make that unique to that selected object? For example, underneath the usual editing options I would like a list of all appointments for that specific client so I'd like to show something like this And maybe something like this for listing the appointments. {% for client_obj in this_client.objects%} {{client_obj.appointment_date}} {% endfor %} I thought this would be an intuitive and/or very easy since the admin is already interacting with the database. But maybe this isn't the intended use of the admin site. Thanks -
Django: Machine learning model in server side?
I have a Word2Vec model(One of Machine learning model) and could get this pre-trained model by filename : model = Word2Vec.load(fname) So, I can get some prediction by using this model: prediction = model.predict(X) What I'm trying to do is to get request(including query word) from user and query this data to my pre-trained model and get prediction so that server could send response with this prediction data. This process should occur every time user send queries, so this pre-trained model should always be in memory. To implement this, I think I have to use Redis, Celery kinda thing, but as I know of, Celery is working asynchronously with Django web application, so it would not be suitable for what I want to do... How can I implement this function in my Django application? Thanks. -
Django - how to add data using conditional statement in a separate python script
Purpose/Intension I have created Django Model with the result being an sqlite3 database. I now want to use a separate python script to add to that database based on some conditional logic. Problem I am new to Django and Python so I am not sure how to interrogate the database and then add some values based on the return result from that interrogation using a separate python script. This is my Models.py: from django.db import models from django.utils import timezone from django.core.urlresolvers import reverse from django.contrib.auth.models import User # Create your models here. class Author(models.Model): ''' Model representing the Author of the stocknote. ''' user_id = models.ForeignKey('auth.User') name = models.CharField(max_length=100) def __str__(self): return self.name class Stock(models.Model): ''' Model representing the stock info. ''' author = models.ForeignKey(Author) ticker_code = models.CharField(max_length=10, null=True, blank=True) latest_stock_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True) datetime_of_last_quote = models.DateTimeField(default=timezone.now) def __str__(self): return self.ticker_code class Note(models.Model): ''' Model representing the Authors note. ''' author = models.ForeignKey(Author) note = models.TextField() ticker_code = models.ForeignKey(Stock) date_note_created = models.DateTimeField(default=timezone.now) alert_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True) def __str__(self): return self.note Now imagine I have added data into the database so it contains data in all the fields except for the field 'latest_stock_price' which is empty. … -
How to retrieve all objects in model database and send it through ajax?
Hello I've been having trouble passing my data from views.py (objects.all) to my ajax. What I wanted to do is for every object in the query set, I'll append its details in a div in my html. I tried serializing it but I'm having trouble on how to loop through the serialized JSON. Any suggestions? Pls help. jQuery function getOffers(key){ dict = { 'key':key// pk value of post sent to retrieve offers to it }; key = "pk";//I actually dont know what to put here generateCSRFToken(); $.ajax({ url: "/retrieve_offers/", method: "POST", data : JSON.stringify(dict), success: function(data){ data = JSON.parse(data); console.log(data); //HOW TO LOOP THROUGH THE DATA AND GET EACH PK }, error: function(){ } }) } views.py def retrieve_offers(request): dict = json.loads(request.body) post_key = Post.objects.get(pk=dict["key"]) offers = Offer.objects.filter(post_id=post_key) data = serializers.serialize('json',offers) return HttpResponse( json.dumps(data), content_type="application/json" ) models.py class Post(models.Model): date_submitted = models.DateField() description = models.CharField(max_length=1024) author = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.ForeignKey(to=Category,on_delete=models.CASCADE) trade_item = models.FileField(null=True,blank=True) trade_item_name = models.CharField(null=True,max_length=100) receive_item = models.FileField(null=True, blank=True) receive_item_name = models.CharField(null=True,max_length=100) def __str__(self): return str(self.pk) + " by " + (self.author.username) @staticmethod def create(date_submitted, description, author, category): post = Post() post.date_submitted = date_submitted post.description = description post.author = author post.category = category return post class Offer(models.Model): … -
Django packages techniques to be able to sell and manage licence
I am building a business model of selling my app to customers. I plan to sell my app on Heroku however the plan is that customers create they own cloud account on Heroku add me as collaborator and I deploy my code to they Heroku account . I want to charge my customers on monthly license basis for use , update and support. But in case when customer is not paying I want to limit the functionality of the deployed app. I am working on implementation of my solution where I have centralized server where I register every deployment , however I was wondering if there existing solution or package I can reuse. I cant find anything of this nature but the task seems trivial to me (I assume I dont know the right keywords) Is there existing Django package I can use ? Or may be it is not a package or some 3rd party service? -
Form Submission in Django without Page Refresh using AJAX
I'm a newbie in python so this might be fixed easily. I'm trying to do a register form using Jquery with Django. I've been following this tutorial when I click on the button it shows me the success message in the alert but nothing is inserted in the database. Here is my code : register.html <body> <form id="add_user_form"> {% csrf_token %} {# label et input du uti_login de la class Form#} <label for="UTI_LOGIN">Insérer un surnom d'utilisateur</label> <input id="UTI_LOGIN" type="text" name="UTI_LOGIN"> <br> {# label et input du UTI_NOM de la class LoginForm#} <label for="UTI_NOM">Insérer un nom d'utilisateur</label> <input id="UTI_NOM" type="text" name="UTI_NOM"> <br> {# label et input du UTI_PRENOM de la class LoginForm#} <label for="UTI_PRENOM">Insérer un prenom d'utilisateur</label> <input id="UTI_PRENOM" type="text" name="UTI_PRENOM"> <br> {# label et input du UTI_CIVILITE de la class LoginForm#} <label for="UTI_CIVILITE">Insérer un civilite d'utilisateur</label> <input id="UTI_CIVILITE" type="text" name="UTI_CIVILITE"> <br> {# label et input du UTI_EMAIL de la class LoginForm#} <label for="UTI_EMAIL">Insérer un email d'utilisateur</label> <input id="UTI_EMAIL" type="text" name="UTI_EMAIL"> <br> {# label et input du uti_mdp de la class LoginForm#} <label for="UTI_MDP">Insérer mot de passe</label> <input id="UTI_MDP" type="password" name="UTI_MDP"> <br> <label for="UTI_SUPPRIME">Hidden label checked</label> <input id="UTI_SUPPRIME" type="checkbox" hidden checked> <br> <br> <input value="S'inscrire ! ☺" type="submit"> </form> </body> <script … -
How can I show a formset in Django with a AJAX success function?
For example if I have the following Ajax request: $.ajax({ type: "POST", url: url, traditional : true, data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), data: data, }, success: function(data){ var html_text =` <div> {% for form in formset %} {{form.as_p}} {% endfor %} </div> ` $("#formset-div").append(html_text); } }); I always get just text in the div after execute Ajax success function How can I show form set with the created data that created by the python function that executed with the Ajax request? -
Validating a Django field dependently on context
I write the code to edit the list of users which belong to a team. For this I create a form, as below: class Organization(models.Model): name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Organization Name'), max_length=256) class Team(models.Model): organization = models.ForeignKey('Organization') name = models.CharField(blank=False, verbose_name=_("Name"), help_text=_('Team Name'), max_length=256) users = models.ManyToManyField('User', related_name='teams') def __str__(self): return self.name class TeamUsersForm(forms.ModelForm): class Meta: model = Team fields = ['users'] users = forms.ModelMultipleChoiceField(queryset=User.objects.filter(request.user.organization), required=False) def clean_users(self): users = self.cleaned_data['users'] if users.exclude(organization=request.user.organization): raise ValidationError(_("Cannot add user from another organization")) return users The code above should look into request value to determine the current organization and restring display and model store only to users from the same organization. But the above code cannot work, because the value of request is not known at class loading time. What you suggest to do? I thought of two variants: create a local (to a function) class like the above class TeamUsersForm dismiss using Django forms for this altogether and use more low-level API -
Django - add summary table in admin-site
What I want to achieve is to have a list of associations on one column and total members on the other column, like so: I have tried to look for other solutions here with no luck, is there something i'm missing? Still a newbie so appreciate all your help and guidance, folks! models.py class Member(models.Model): member_no = models.AutoField(primary_key=True) association = models.ForeignKey('Association') ... class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' def __str__(self): return self.asoc_name def __unicode__(self): return self.asoc_name class AssociationSummary(Association): class Meta: proxy = True verbose_name = 'Association Summary' verbose_name_plural = 'Association Summary' admin.py @admin.register(AssociationSummary) class ChartAssociationAdmin(admin.ModelAdmin): change_list_template = 'admin/chart_association.html' def get_total(self): total = Member.objects.all().aggregate(association=Sum('member_no')) return total def changelist_view(self, request, extra_context=None): my_context = { 'member_no': self.get_total(), } return super(ChartAssociationAdmin, self).changelist_view(request, extra_context=my_context) chart_association.html {% extends 'admin/change_list.html' %} {% block content_title %} <h1> Association Summary </h1> {% endblock %} {% block result_list %} <div class=”results”> <table> <thead> <tr> <th> <div class=”text”> <span>Association</span> </div> </th> <th> <div class=”text”> <span>Total Members</span> </div> </th> </tr> </thead> <tbody> {% for row in member %} <tr class="{% cycle 'row1' 'row2' %}"> <td> {{ row.asoc_name }} </td> <td> {{ row.total }} </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} {% block … -
Associate comments with an already authorized user?
My task is to create comment system in django project. I am tring to use django-comments-xtd app. I successfully added this app to my project and use {% render_comment_form for object %} in template. Is shows me fields like "Name", "Email", "Url" and "Comment". Maybe someone who worked with this app could answer me. Is it possible to show only "Сomment" field and associate comments with an already authorized user. Right now all unregistered users can comment. What I need to customize? I am little bit comfused with this app. -
User email account verification and activation django
views.py def registration(request): template = "main/registration.html" params = dict() if request.method == "POST": email = request.POST.get("email", "").lower() password = request.POST.get("password", "") password2 = request.POST.get("password2", "") try: validate_email(email) except Exception as error: return render(request, template, params) try: len(password) >= 5 except Exception as error: messages.add_message(request, messages.ERROR, PASSWORD_ERROR) return render(request, template, params) if password != password2: messages.add_message(request, messages.ERROR, DIFFERENT_PASSWORD) if User.objects.filter(username=email, is_active=True).exists(): messages.add_message(request, messages.ERROR, EXIST_USER) return render(request, template, params) new_user = User.objects.create_user(username=email, password=password) activation_key = Activation.objects.generate(user=new_user) messages.add_message(request, messages.ERROR, SUCCESS) send_mail('activation JustSolve.kz', "hello world", settings.EMAIL_HOST_USER, ['knursultana@gmail.com']) # TODO: add celery # TODO: send verification email return render(request, template, params) settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True models.py class ActivationManager(models.Manager): def generate(self, user): activation = Activation() activation.user = user activation.key = uuid.uuid4() activation.save() return activation.key class Activation(models.Model): user = models.ForeignKey('MainUser') key = models.CharField(max_length=100, blank=False) create_time = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) objects = ActivationManager() def __unicode__(self): return u"user={0} key={1}".format(self.user, self.key) class Meta: verbose_name=u"" How to do activation via email? I just want to do active "Is active" field. I can not to implement it in code. I think it works like this: after registration I should generate activation code. Then send email to user with url … -
saving image from Django view in ImageField
hello I have find this code on site where take url images and save that images in database. But for my problem I don't have url image but I have simple image path like this image1='C:/my/path/image.png that image have create from my personal simple image processing where I have in views.py. my question is how to add(update? ) this image in person model ? models.py from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Person(models.Model): avatar = models.ImageField(upload_to='avatars', default='') avatar_thumbnail = ImageSpecField(source='avatar', processors=[ResizeToFill(300, 200)], format='JPEG', options={'quality': 80}) views.py from django.core.files.base import ContentFile from io import BytesIO from urllib.request import urlopen input_file = BytesIO(urlopen(img_url).read()) # img_url is simply the image URL person = Person.objects.create() person.avatar.save("image.jpg", ContentFile(input_file.getvalue()), save=False) person.save() -
Django .filter() for imagefields
I have 6 or more images saved in a model in Django. I want to iterate over these to create a carousel in Bootstrap. So far I have everything working as expected however I cannot seem to create the for loop to return more than one picture. My views.py looks like this def slideshow(request, pk): retdict = {'cars': Sales.objects.filter(id=pk)} return render(request, "website/slideshow.html", retdict) and the slideshow.html (without all the bootstrap carousel code) looks like <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> {% for pic in cars %} {% if forloop.counter == 1 %} <div class="item active"> {% else %} <div class="item"> {% endif %} <img src="{{ pic.photo1.url }}" alt="Image"> </div> </div> {% endfor %} </div> I realise that the photo1.url is the incorrect code to type as this references the name of the file in the database. I want to be able to call many images but I am unsure how to get the correct .url for each iteration of the for loop. -
Having form fields be able to duplicate by clicking the add icons or plus icon
Let's say I want to create a form that will take in the info about someone. Let's say I have a school field and I want to know the schools the person has attended. In the case the person has more than one school, how do I make the form duplicate the school field in order to add all the schools the person has been to. -
Making view only available to registered users with registration redux?
I'm making a simple Django application, I've implemented django registration redux with two step email verification, using the standard default templates. I know want to add a simple HTML page that is only accessible to registered users: my_project /settings.py /urls.py templates /only_accessible_to_users.html /registration manage.py my_application /models.py /admin.py /views.py /urls.py In /my_project/urls.py I have the following: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^finance/', include('my_application.urls')) ] In my_application/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.testing, name='testing')] Finally in my_application/view.py: def testing(request): return HttpResponse("<h2>Hey!</h2>") How can I render a HTML page here after validating that it's being requested by a registered user? -
How do display CommentForm in IndexView ? Django
I have comments for each post and I want that users can just type their comments and submit them on the same page 'IndexView' here is my views.py def IndexView(request): if request.user.is_authenticated(): base_template_name = 'blog/base.html' else: base_template_name = 'blog/visitor.html' form = CommentForm() posts = Post.objects.all() return render(request, 'blog/index.html', {'form':form,'posts':posts,'base_template_name':base_template_name}) def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() context = {'form':form} return render(request,'blog/index.html', context) else: form = CommentForm() return render(request, 'blog/index.html', {'form': form}) In Index.html I put this (it displays the field put cannot submit it): <form enctype="multipart/form-data" method="post" class="post-form"> {% csrf_token %} {{ form.textc }} <button type="submit" class="save btn btn-default">Send</button> </form> Here my CommentForm in forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('textc',) And Urls.py for Index and comment url(r'^post/(?P\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'), url(r'^$', views.IndexView, name = 'index'), Thanks alot guys ! -
Delete a password reset instance for a user if they have not reset there password withn a day
I am making an application using django I am wondering what is the best solution for automatically deleting password reset instances from my PasswordReset model if a user hasn't reset their password within a day. ResetPassword Model class ResetPassword(models.Model): user = models.ForeignKey('auth.User') password_reset_token = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) password_reset_submission_date = models.DateField(auto_now_add=True,null=True,blank=True) def __str__(self): return self.user.username -
Django x-www-form-urlencoded request
I'm trying to do the following request with django : I tried the following code but it doesn't work : data = {'username': admin, 'password': 123, 'grant_type': 'password', 'client_id': 'xxxx', 'client_secret': 'xxxx'} headers = {'content-type': 'application/x-www-form-urlencoded'} r = requests.post(url, data=data, headers=headers) Thanks for your help ! -
Django convert current page to PDF on button click
I am using Django 1.10 and python 3.4 on windows. I set up pdfkit and it works perfectly from command line. I want to use it in the site on a button to return the current page as a pdf attachment without redirecting anywhere(if possible). The page to convert is a report which uses a user specified date as url. Currently the button redirects by appending the current url with "?mybtn=Generate+PDF#" I have seen some solutions using jQuery or javascript, but I only really know python well. I will learn those eventually, but for now I would like a quicker solution where I understand what's going on. views.py class FlashReport(generic.View): template_name = "reports_flash_report.html" def get(self, request, year, month, day): report_data = get_flash_report_data(int(year),int(month),int(day)) return render(request, 'reports_flash_report.html', report_data) def generate_PDF(request): path = request.get_full_path() pdf = pdfkit.from_url(path, False) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="flash_report.pdf"' return response reports_flash_report.html <div> <form action="" method="get"> <input type="submit" class="btn" value="Generate PDF" name="mybtn" /> </form> </div> urls.py url(r'^flash_report/(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})/$', views.FlashReport.as_view(), name="flash_report"), -
CloudFlare redirect to certain port
I've got a VPS running on Debian 8 where I have a few of Django apps that runs on http://[IPv6]:8000 and http://[IPv6]:8080 and I want to make CloudFlare DNS system to redirect from http://www.example.com to one of these addresses on different port than 80. Redirect to http://[IPv6] is ok, but when I try to redirect to different port, it throws an error. Thank you ! -
Django or flask, which is better in case the developped application makes a lot of data loading to the client?
The app am developping uses cron jobs to retrieve and update data from facebook ads api, adwords api and google analytics, metrics on campaigns are displayed in a dashboard developped with angular2, reports on campaigns perormance on the different channels can also be displayed. -
Django - DRF setting fields with non string
lest say we have a code like this. class UserProfileDetailSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('userThumbnail', 'point') what i want to do is not using ('userThumbnail', 'point') but something like this (nameof(UserProfile.userThumbnail), nameof(UserProfile.point)) so i dont have to rewrite those fields everytime i rename those. how can i do something like that? -
Django Rest - "<ClientProfile: mike@tyson.com>" needs to have a value for field "clientprofile" before this many-to-many relationship can be used
I'm trying to implement an API where I can: Return all ClientProfile objects, with a nested ManytoMany field containing a list of Location objects (I don't really care if it's PK or actual object, actual object would be nice.) Be able to POST a ClientProfile object, and specify which Location objects should be associated with it using the PK of the Location object, like so: { "user": { "email": "mike@tyson.com" }, "first_name": "Mike", "last_name": "Tyson", "locations": [ 1,5,21 ] } I have seen people saying "You need to implement a save method" for normal Django. I'm new to Django and Django REST, so not sure where or how to implement a solution for this.. Please save me from this nightmare! Error: Traceback (most recent call last): File "/venv/project/userauth/tests/User.py", line 28, in setUp self.response = self.client.post(path="/client-profile/", format="json", data=self.data) File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 290, in post path, data=data, format=format, content_type=content_type, **extra) File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post return self.generic('POST', path, data, content_type, **extra) File "/venv/lib/python3.5/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 279, in request return super(APIClient, self).request(**kwargs) File "/venv/lib/python3.5/site-packages/rest_framework/test.py", line 231, in request request = super(APIRequestFactory, self).request(**kwargs) File "/venv/lib/python3.5/site-packages/django/test/client.py", line 494, in request six.reraise(*exc_info) File "/venv/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise …