Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
flow based visualization - drag and drop elements for workflow with ports and nodes
Can web apps like the below ( Azure ML studio ) be created if using flask/django with Python. -
Using Django "now" template tag to compare dates
I have a template tag that returns a date from a model field. If the date is today, I want to render some other content. Using the "now" builtin-templatetag: https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#now, I used logic similar to the answer in this previously posted answer: https://stackoverflow.com/a/34959070/5616606 {% now "Y-m-d" as todays %} {% if self.date|date:"Y-m-d" == todays %} ...add some content {% endif %} I am trying to do this without creating a custom filter, context processor or edit the view. The problem, I believe, is with the timezone. This works until later in the evening when "now" returns the next day, instead of the current day. I researched Django's date and timezone documentation but am not sure how make the timezone returned from "now" match the timezone of the model field without having to create a context processor or edit the view -
Prevent the Repetition of Data in Database
Here's the code in view, def index(request): data = Model.objects.create(user=request.user, timestamp=timezone.now()) Whenever the view is requested i'm saving the user requesting it & the timestamp at which user has requested the page. But, It's repeating the same data in database with updated timestamp. How can I prevent the repetition by updating the same model when the view in requested? Please helpme! -
Django filter choices in ForeignKey field in a ModelForm
How can I filter the options shown for a ForeignKey field in a Model Form? I tried to follow this thread How do I filter ForeignKey choices in a Django ModelForm? but I'm pretty new to Django and I got very confused. I have an app for Users (with a UserManager/AbstractUser models, not relevant) Another app for: Products, with product_id and product name, Purchases, with product_id and user_id. Another app for Tickets, with a form to open a ticket. In that form I want to show only the products that the user has bought, so the user can only open a ticket for the products he has. Code below, I've removed non relevant fields, etc. Ticket Model class Ticket(models.Model): ... user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tickets') product = models.ForeignKey('products.Product', related_name='tickets') Ticket ModelForm class TicketForm(forms.ModelForm): class Meta: model = Ticket fields = ['subject', 'reason', 'product'] Product & Purchase Models class Product(models.Model): name = models.CharField(max_length=100, default="") ... class Purchase (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='purchases') product = models.ForeignKey(Product) ... New Ticket Form view def new_ticket(request): if request.method=='POST': ticket_form = TicketForm(request.POST) ... if ticket_form.is_valid() and comment_form.is_valid(): ticket = ticket_form.save(False) ticket.user = request.user ticket.save() ... return redirect(reverse('ticket-detail', args={ticket.pk})) else: ticket_form = TicketForm() args={'ticket_form':ticket_form} args.update(csrf(request)) return render(request, 'tickets/ticket_form.html',args) … -
Decorating the class or the dispatch() method?
Yesterday I had a Stackoverflow question about putting a permissioning check on a class-based-view. The solution seem(s) to be incorporating a PermissionDeniedMixin. It also looks like I could try UserPassesTestMixin from Django-braces. This made sense, but I was doing some background reading on the dispatch() method and stumbled onto this part of the documentation: To decorate every instance of a class-based view, you need to decorate the class definition itself. To do this you apply the decorator to the dispatch() method of the class. Why would I need or choose to decorate the instances with the permission mixins rather than the class itself? -
Save User Automatically in Database
Here's my Model, class Extra(models.Model): user = models.ForeignKey(User) timestamp = models.DateTimeField() So, whenever the 'request.user' calls a specific view i.e, def myview(request): .... .... return render(request, 'new.html', context) I wants to save the 'user' (request.user) & 'timestamp' (current time as per their location) automatically in database. How can I do that in view? Please help me with this code. Thanks in Advance! -
AWS elastic beanstalk + Nginx + Gunicorn
I am working on creating a Django web app using resources on AWS. I am new to deployment and in my production setup (Elastic Beanstalk i.e. ELB based) I would like to move away from the Django development web server and instead use Nginx + Gunicorn. I have been reading about them and also about ELB. Is Nginx + Gunicorn needed if I deploy my Django app on ELB? As ELB does come with reverse proxy, auto scaling, load balancing etc. Appreciate the inputs. -
How can i use django or tornado framework in Asp.net MVC project
Hey guys this question actually is simple.I want use django or tornado framework for image proccessing or something like that in my Asp.net MVC project how can i do that? Thank you for your answers. -
Displaying an Image in a Form
I have the following form: class QuizForm(forms.Form): def __init__(self, *args, **kwargs): questions = kwargs.pop('questions') super(QuizForm, self).__init__(*args, **kwargs) for q in questions: answers = [ans.Answer for ans in q['w_answers']] answers += [q['question'].CorrectAnswer] self.fields['question_%d' % q['question'].id] = \ forms.ChoiceField( label=q['question'].QuestionText, required=True, choices=[(ans, ans) for ans in answers], widget=forms.RadioSelect) def answers(self): for name, value in self.cleaned_data.items(): if name.startswith('question_'): yield (name.split('_')[1], value) The result of this form is basically a list of questions with each question having a few wrong answers and one correct answer (HTML: <ul> inside <ul>). One of my models is a Question model: class Question(models.Model): def _image_path(instance, filename): return 'images/%s' % filename Course = ForeignKey(Course, on_delete=models.CASCADE) QuestionText = CharField(max_length=200) CorrectAnswer = CharField(max_length=200) Image = ImageField(max_length=200, blank=True, null=True, upload_to=_image_path) class Meta: unique_together = (('Course', 'QuestionText'),) def __str__(self): return self.QuestionText As you can see, I have an ImageField in my model, I don't know how to display it though. How can I display both the QuestionText and the Image? Thanks in advance. -
Matching websites with subdomain using python
I am creating different kinds of matcher based on websites. I am using django and python 2.7. I have logic for one example: Company Name: ABC, Website: www.abc.com/ Company Name ABC, Website: www.abc.com/home For above example my logic is to extract top level domain and check if they are same or not and it is working fine. But it fails for below example: Company Name: ABC Website: www.abc.pqr.eu.com Company Name: XYZ Website: www.xyz.pqr.eu.com In this case as top level domain matches so it is considered as a match. But actually they are two different websites and companies and its not a match. Any suggestions? -
New Notifications Since Last Seen (django)
Right now I'm using this view in order to inform the user that their question is just answered, def notifications(request): answers = Answer.objects.filter(question__user=request.user).order_by('-id') .... But this is just a plain html text notification. I wants to make it more dynamic by notifying them the number of new notifications they have since their last seen, as we see on social networks. How can I do that? Please help me with this code. Thanks in advance! -
Django / Generig Foreign Key saving content_object with form
Couldn't figure out saving form data to database with generic relations. I try to make a reddit clone with django. I want to make with generic foreign keys. right now I can't post a comment to a specific post. I'm kind of confused. views.py class EntryCreate(CreateView): template_name = 'post_form.html' model = Post fields = [ 'subject', 'entry', ] class EntryDetail(FormMixin, DetailView): template_name = 'post_detail.html' model = Post form_class = CommentForm def get_success_url(self): return reverse_lazy('post-detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(EntryDetail, self).get_context_data(**kwargs) context['post_object'] = Post.objects.filter(pk=self.kwargs.get('pk')) context['comments'] = Post.objects.get(pk=self.kwargs.get('pk')).comments.all() return context def post(self, post_id, *args, **kwargs): form = self.get_form() post_comment = Post.objects.get(pk=self.kwargs.get('pk')) if form.is_valid(): form.save(post_id=post_comment) return reverse_lazy('post-detail', kwargs={'pk': self.object.pk}) else: pass forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('entry_comment',) def save(self, post_id, *args, **kwargs): super(CommentForm, self).save(*args, **kwargs) comment = CommentForm() comment.content_object = post_id models.py class Comment(models.Model): entry_comment = models.TextField(max_length=160) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, default=None) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.entry_comment class Post(models.Model): subject = models.CharField(max_length=20) entry = models.TextField(max_length=160) comments = GenericRelation(Comment) def get_absolute_url(self): return reverse('index') -
Authorize Code error in Django project
I have a django project I am working on and I want to create a way for a user to login to my project through paypals api. I create the required users, accounts, and application within the paypal dashboard. I found samples of the code that will implement the openid connect method from the paypal api. I have all the right credentials, but there is an error that is coming from the authorize code that is required to open the connection. I have looked everywhere in the paypal dashboard to find this authorize code that is required. does anyone know where it is located within the dashboard so I can get a successful connection. I tried the client_id, client_secret, app_signature, account_signature and nothing worked. Here is the sample code: # Generate login url login_url = Tokeninfo.authorize_url({ "scope": "openid profile"}) # Create tokeninfo with Authorize code tokeninfo = Tokeninfo.create("Replace with Authorize code") # Refresh tokeninfo tokeninfo = tokeninfo.refresh() Here is the error: paypalrestsdk.exceptions.BadRequest: Failed. Response status: 400. Response message: Bad Request. Error message: {"error_description":"Invalid authorization code","error":"access_denied","correlation_id":"467725762f562","information_link":"https://developer.paypal.com/docs/api/#errors"} -
how can i send data with my gprs to my hosting site database?
i'm creating my car tracking app i'm trying to send data with my gprs (SARA-G350) to my hosting site database in real time i have already used the AT commandes to send data but nfortunately it wouldn't work i want to know the solution -
Django: Form Handling Errors. Processing a Form associated with another Model
I want to be able to submit reviews for teachers. I have 2 models: models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') class Review(models.Model): teacher = models.ForeignKey(Teacher) #other fields def __str__(self): return self.name forms.py class ReviewForm(forms.ModelForm): class Meta: model = Review #Note no 'teacher' in fields below fields = ('title','star','body') views.py I have the following form handling: def teacher_view(request,**kwargs): teacher = Teacher.objects.get(pk=kwargs['pk']) #if request.method == 'POST': #handle the form review_form = ReviewForm(request.POST, instance=teacher) review_form.teacher=teacher if review_form.is_valid(): review_form.save() return redirect('users:index') else: For some reason, I also seem to get the else loop. E.g. the form is not valid. Urls.py url(r'^(?P<pk>[0-9]+)/$', views.teacher_view, name='detail') -
Cannot include urls from my app in django
My app(lists) was working perfectly before I decided to make a separate urls.py file for my app. Now, all the tests Fail with 404 error. my urls.py is from django.conf.urls import url, include from lists import views as list_views urlpatterns = [ url(r'^$', list_views.home_page, name='home'), url(r'^lists/', include('lists.urls')), ] and my lists/urls.py from django.conf.urls import url from lists import views as list_views app_name = 'lists' urlpatterns = [ url(r'^lists/(\d+)/$', list_views.view_list, name = 'view_list'), url(r'^lists/(\d+)/add_item$', list_views.add_item, name = 'add_item'), url(r'^lists/new$', list_views.new_list, name = 'new_list'), ] any help is appreciated. Thank you! -
Django Images for individual users not showing
I have page with a list of all the users in my system. Each user in the lists displayed with three things: 1. their profile picture, 2. their first name, and 3. their user type. However, while the profile picture does show, it does not show the correct one corresponding to that specific user. Instead, it shows the profile picture of the currently logged in user for every user on the site. user profile_list.html: {% extends "base.html" %} {% block content %} {% for users in userprofile_list %} <a class="user-profile-link user-card" href="{% url 'users:user_profile' users.pk %}"> <img class="profile-pic" src="{%if user.userprofile.profile_pic%}{{user.userprofile.profile_pic.url}}{%endif%}"> <p class="user-card-name">{{ users.first_name }}</p> <p class="user-card-type">{{ users.user_type }}</p> </a> {% endfor %} {% endblock %} A picture of what is happening: Instead of a picture of me for every user, their individual profile pictures should be displayed, even though I am the one logged in. -
Images are not found/loading correctly - 404
I am using the Oscar-Django e-commerce project, and I am following the tutorial Frobshop The website is up and running, however, when I add a product -from the admin dashboard- and upload a picture, the thumbnail isn't loading, and when I view the product on the customer view, the picture is missing. Here is my configuration in the settings.py file: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = location("public/media") STATIC_ROOT = location('public/static') When I view the product from the customer view, the terminal is showing the 404 GET "GET /media/cache/45/ec/45ecfa8787510d3ed6997925b6e26ed7.jpg HTTP/1.1" 404 4880 When I go to the admin section of the site and try to click on the picture from the product table, it shows "Page not found" as well, the URL this time is http://127.0.0.1:8000/media/images/products/2017/09/hoodie1.jpeg When I browse to the specific product (still on the admin site), then the image section of this product, the thumbnail isn't displayed and the terminal shows this "GET /media/cache/cd/8a/cd8af791d513ec91a583b0733070d9a7.jpg HTTP/1.1" 404 4880 Here are the patterns from URLs.py urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), # The Django admin is not officially supported; expect breakage. # Nonetheless, it's often useful for debugging. url(r'^admin/', include(admin.site.urls)), url(r'', include(application.urls)), ] I see the picture under this path … -
Django importerror app_name/wsgi.py can't find django.core.wsgi
I'm trying to deploy my Django application to my Digitalocean Droplet running Ubuntu 16.04.3. I have followed this tutorial closely: https://www.codementor.io/uditagarwal/how-to-deploy-a-django-application-on-digitalocean-du1084ylz where I have setup a virtualenv and then installed Django with pip. I use Nginx and Gunicorn. When I try to run my server with the command gunicorn --bind 0.0.0.0:8000 [project_name].wsgi:application I get the following error: gunicorn --bind 0.0.0.0:8000 gruppegenerator.wsgi:application [2017-09-16 19:32:30 +0000] [16604] [INFO] Starting gunicorn 19.4.5 [2017-09-16 19:32:30 +0000] [16604] [INFO] Listening at: http://0.0.0.0:8000 (16604) [2017-09-16 19:32:30 +0000] [16604] [INFO] Using worker: sync [2017-09-16 19:32:30 +0000] [16609] [INFO] Booting worker with pid: 16609 [2017-09-16 19:32:30 +0000] [16609] [ERROR] Exception in worker process: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) File "/home/rasmus/gruppegenerator/gruppegenerator/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File … -
How to detect if the requests to your server are coming from trustworthy service ? (in Django)
I have a service that i've configured a webhook that triggers posting data on my url address. Now i want to restrict incoming requests to be allowed only for this service. How can i do this in Django ? Is there any trick on applying some security measures? i'd be glad if you can provide some code snippets, please -
django multi level select related
I'm working in Django 1.11 I have three apps, country, state and address state model is associated with country by foreign key and address is associated with state with a foreign key. country/models.py class Country(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=50) class Meta: db_table = 'countries' def __str__(self): return self.name state/models.py class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=100) code = models.CharField(max_length=50) class Meta: db_table = 'states' def __str__(self): return self.name address/models.py class Address(models.Model): line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.ForeignKey(State, on_delete=models.PROTECT) postal_code = models.CharField(max_length=15) class Meta: db_table = 'addresses' def __str__(self): return '%s, %s, %s, %s' % (self.line_1, self.line_2, self.city, self.state) Since one country can have multiple states, I want user to be able to select state after selecting country, which will list related/associated states while adding/editing address. I also want this feature in /admin as app is registered to admin too. Is there any simple and better way to do this? -
Django, handling multiple forms. Forms referenced before assignment
I have two forms in my view: BookingForm and ReviewForm. I want to submit and process these forms independently in my template.html. I added the 'booking' and 'review' in the name tag of my forms in template.html For the booking form, I simply want to redirect, but for the ReviewForm I would like to create a record in my DB. Here's my views.py if request.method == "POST": if 'booking' in request.POST: form = BookingForm(request.POST) if form.is_valid(): #process the form return redirect() elif 'review' in request.POST: review_form = BookingForm(request.POST) if review_form.is_valid(): review_form.save() return redirect() else: form = BookingForm() review_form = ReviewForm() return render(request, "template.html", context={"form": form,"review_form":review_form}) However, for some reason, I get the error that form and review_form are referenced before assignment. Another thing, since Review Model has to be associated with another Model (call it Item). I would like to automatically get the item data and associate my review with the item when I call review_form.save(). I'm thinking something along the lines of review_form['item']=kwargs['pk'] (Not sure if this will work). I'm using a DetailView structure and the page has parameter from urls.py, associated with the item, stored as item_id=kwargs['pk'] in my view. class Review(models.Model): #other fields item = models.ForeignKey(Item) class … -
playing audio when a button is clicked in html django template
i have the following html code snippet: <audio controls><source src="{{sound.sound.url}}" type="audio/mpeg" id="yourAudioTag">Your browser does not support the audio element.</audio> <button id="play">Play</button> <script> $(document).ready(function() { var audioElement = document.createElement('audio'); $('#play').click(function() { audioElement.play(); }); }); </script> but it doesn't seem to play the audio when i click on the button PLAY. how can i do it? -
Django - Design choices, Override the model save() so it palys nice with contrib.admin?
I'm with some design issues in Django and getting all to play nice with contrib.admin. My main problem is with Admin Inlines and the save_formset() method. I created a create() classmethod for the model but this do not play nice with save_formset(). I think Django admin have a way of doing this, not with a create() method. In the create() method in the AdPrice I basicaly want to update the field 'tags' in the model Ad. My question: Instead of creating a create() classmethod it would be nice to override the model save() method so I don't have problems with contrib.admin? My code: Models: class Ad(models.Model): title = models.CharField(max_length=250) name = models.CharField(max_length=100) description = models.TextField() tags = TaggableManager() comment = models.TextField(null=True, blank=True) user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad') date_inserted = models.DateTimeField(auto_now_add=True) user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad') date_updated = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name class AdPrice(models.Model): ad = models.ForeignKey(Ad) name = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad_price') date_inserted = models.DateTimeField(auto_now_add=True) user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad_price') date_updated = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name @classmethod def create(cls, ad_id, name, price, date_inserted, user_inserted_id): # Save price new_register = AdPrice(ad_id=ad_id, name=name, price=price, date_inserted=date_inserted, user_inserted=User.objects.get(id=user_inserted_id)) new_register.save() # … -
Unable to import a model into views.py file from models.py file in Django
I recently started with Django. While writing a basic web app, I am unable to import Album model into views.py file. I am using PyCharm IDE. While using objects.all() and DoesNotExit I couldn't see any suggestions from IDE after using dot operator. Album.ojects.all() is working in python shell. I am posting the error message and code spinets. Here is my views.py file. from django.shortcuts import render from django.http import Http404 from .models import Album def index(request): all_albums = Album.ojects.all() return render(request, 'music/index.html', {'all_albums':all_albums}) def detail(request, album_id): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exit") return render(request, 'music/detail.html', {'album':album}) here is my models.py file: from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) def __str__(self): return self.song_title index.html {% if all_albums %} <h3>Here are your albums</h3> <ul> {% for album in all_albums %} <li><a href="/music/{{ album..id }}">{{ album.album_title }}</a> </li> {% endfor %} </ul> {% else %} <h3>You dont have any albums </h3> {% endif %} detail.html {{ album }} Error msg