Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix this error when use django-notifications?
Please helpme with these: File "C:\Python36\lib\site-packages\notifications\models.py", line 170, in Notification recipient = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='notifications') TypeError: init() missing 1 required positional argument: 'on_delete' -
How to render PyViz visualizations in Django or Flask apps
I've seen the tutorial of PyViz and it has a lot of interactive visualizations. However, I want these visualization to be part of my web app, the tutorial doesn't show how to render the visualizations properly to the front-end (HTML, CSS, JS) side of the application. Does anyonr have any suggestions? -
Python 2.7 Django 1.9 I can't pass 2 parameters
I got an error message: "submission() takes exactly 2 arguments (1 given)" and I suspect that I didn't pass the 2 parameters successfully. I have struggled it for over 2 days now. Can anyone give me a quick diagnosis of what is going wrong? Here is my submission.html <form method="post" action="{% url 'submission' %}" enctype="multipart/form-data"> {% csrf_token %} <div> <td>{{ form.title.label_tag }}</td> <td>{{ form.title }}</td> </div> <div> <td>{{ form.message.label_tag }}</td> <td>{{ form.message }}</td> </div> <div> <input type="text" name="image_id" /> <input type="hidden" name="next" value="{{ next }}" /> <input type="submit" value="Store Post" /> </div> <a href="/discussion/registration">Register for an account</a><br> <a href="/login">Login</a><br> <a href="/logout/">Logout</a><br> <a href="/discussion/">See All Comments</a><br> <a href="/discussion/submission/">Submit</a> </form> Here is part of my view.py. the purpose is trying to upload image files. def submission(request, image_id): form = PostForm() if request.user.is_authenticated() and request.method == 'POST': form = PostForm(request.POST) if form.is_valid() == True: post_to_submit = Post() post_to_submit.post_title = form.cleaned_data['title'] post_to_submit.post_text = form.cleaned_data['message'] post_to_submit.pub_date = datetime.datetime.now() post_to_submit.user = request.user post_to_submit.save() image = Image.objects.get(id=image_id) image.comments.add(post_to_submit) template = loader.get_template('discussion/index.html') post_list = Post.objects.order_by('-pub_date') context = {'post_list': post_list, 'image_id' : image_id} else: return HttpResponse(form.errors.__str__()) elif request.user.is_authenticated() and request.method != 'POST': form = PostForm() template = loader.get_template('discussion/submission.html') context = {'form' : form, 'image_id' : image_id} elif request.user.is_authenticated() == … -
update_or_create with Django for sum old row
i'm trying to create a row in DATABASE and if exist update the old value to the new + old, with DJANGO. something like PHP above: $sql= "IF EXISTS(SELECT * FROM francais WHERE label='".$label."') THEN BEGIN UPDATE francais SET n=n+'".$n."' WHERE label='".$label."'; END; ELSE BEGIN INSERT INTO francais (n,label) VALUES('".$n."','".$label."'); END; END IF;"; i'm receiving new row ,trying this: query = Francais.objects.get_or_create(label= label, n= new_value, date= timezone.now()) sum_value = query.n+= new_value query = Francais(label=label, n=sum_value , date=timezone.now()) query.save() -
Tech stack advice for Payment Processing app?
I am thinking about building a web app which integrates with a payment processing API like Galileo (https://galileoprocessing.com/) and have a tech stack question. Most of my web app experience is using Node.js (MEAN stack) and building my own REST APIs. For this app, I will mostly be using the payment API and I'm not sure if I want to use Node.js. Would you suggest I stick to using Node.js or switch to something like Django or PHP based? Are there disadvantages to using something like Node for this kind of app? Note that I have not written any code but rather just looking to find out more about the stack for an app like this from people who know more than me:). Thanks! -
Django - How to call localflavor US_STATES in HTML
How do you make a drop down menu that contains all of the options in localflavor's US_STATES? I can see how to create a model that contains a field that uses the localflavor option US_STATES. class State(models.Model): states = models.CharField(max_length=2, choices=US_STATES , null=True, blank=True) The field state is then in a manytomany relationship to a model called Person. How do you take this a put it in a html page? In my view, I can only think of doing this. def get_context_data(self, *args, **kwargs): context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs) context['states'] = State.objects.all() But this only pulls the existing state options. 1) How do I pull all states into the view? 2) How can I render an html template to use the output of 1? I imagine it has something to do with the 'choices' option, but I haven't ever done that before. Thanks -
Uncaught ReferenceError: Comment_Text is Not Defined
I'm working on a blog where a user can add comment to the blog posts. I'm trying to add the comment without refreshing the webpage but it's not working properly. Here's what I did, Comment model, class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) html file, <div class="comm_update"> <form class="comm_form" action="{% url 'comm:create' post.id %}" method="post"> # Comment form </form> {% for comment in post.comment_set.all %} <div>{{ comment }}</div> {% endfor %} </div> ajax request, $(document).on("submit", ".comm_form", function(e) { e.preventDefault(); var abc = $(this), req = $.post(abc.attr("action"), abc.serialize()), url = abc.attr("action"); req.done(function() { $.ajax({ url: url, type: "GET", data: {comment_text: comment_text, timestamp: timestamp, post: post}, success: function(result){ $(".comm_update").html(result); } }); }) }); After typing a comment in comment form when I press submit, it sends a request & saves the comment in database but it's not updating the comments after that request. When I submit the comment it shows an error inside the console saying, Uncaught ReferenceError: comment_text is not defined How can we fix this problem? Thank You! -
Create Django Application Settings Page
I have a Django app and am trying to make some specific model information changeable while the site is loaded. For example, I'd like to be able to change certain images on pages (banners and such) based on changes I make on the admin panel of Django. Additionally, I'd like to create a list of prepopulated migrations for my social media links that can be editable in a django admin page. My specific instance of this is for all of my social media links. I'd like to put my social media link in a model 'Facebook Url" = 'www.facebook.com/mypage. I would then like to put these links throughout the page using dot notation {{ project_settings.facebook.url }} for example. What is the easiest way to do this. I don't think I want to put the context in all of the views because I would have to do that for every page I want this to be available. In the case of my footer it is on every page. The background images are also on several different pages. -
Django forms with Number Formatting
I am using numeral.js and jquery-calx.js to format the form input number values. So when the form is submitting I am getting commas or dollar signs such as 250,000 or $250,000. The form will not get validated. How best to clean these values when the form is submitted? Thank you. -
Django ghost settings.py file when breaking out settings
I am at my wits' end with this problem and I am hoping one of you kind folks have the answer. I have production and development Django apps - so I am trying to utilize the settings argument on manage.py to access the right settings when running manage.py ie python manage.py runserver --settings=athena.settings.development To make this work - I moved my settings.py file with the nasty if/else construct and some print statements just to make sure the the settings would still read it there was following me to settings/base.py. I created a settings directory and moved/renamed the settings.py. athena/ |-- athena/ | |-- __init__.py | |-- settings/ | | |-- __init__.py | | |-- base.py <------ | |-- urls.py | +-- wsgi.py +-- manage.py the new settings/base.py that manage.py can't read - defaults to the old settings.py as you'll see in the traceback: import os from decouple import config # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print ('-----------') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = … -
It is possible change id to group uuid and permission django?
It is possible change id to uuid in group and permission django? -
How to Render Django MPTT TreeNodeMultipleChoiceField as A Tree
I like to use jquery (i.e jquery.fancytree) or bootstrap library to rednder my form as a tree. I do not know how to! I do not want to use mptt_tags recursetree. I need to use the Form and not the Model. Thanks Snapshot of the app with two level is shown. forms.py ========= from django import forms from mptt.forms import TreeNodeMultipleChoiceField class RSMDriveForm(forms.Form): choices = TreeNodeMultipleChoiceField(queryset=RSMDriveModel.objects.all(), required=False, level_indicator=mark_safe("&nbsp;"), label="", widget=forms.widgets.SelectMultiple(), ) def __init__(self, *args, **kwargs): super(RSMDriveForm, self).__init__(*args, **kwargs) views.py ========= def rsmgui_home(request): form = RSMDriveForm() context = {'drive_nodes': form } return render(request, "rsmgui_nav.html", context) rsmgui_nav.html =============== <form class="form-horizontal" role="form" id="drive-form" method="post" action="" > {% csrf_token %} {% for choice in drive_nodes.choices %} {{ choice }} {% endfor %} </form> -
django rss returns 404
my Django rss feed reruns 404 No post found matching the query I am trying to make an rss and atom feed for a blog I am working on this is the error I get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/rss No post found matching the query You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. feeds.py from django.contrib.syndication.views import Feed from blog.models import Post from django.utils.feedgenerator import Atom1Feed class RssSiteNewsFeed(Feed): title = "Police beat site news" link = "/sitenews/" description = "Updates on changes and additions to police beat central." def items(self): return Post.objects.all.order_by('date')[:5] class AtomSiteNewsFeed(RssSiteNewsFeed): feed_type = Atom1Feed subtitle = RssSiteNewsFeed.description urls.py from django.conf.urls import url,include from. import views from blog import views as blog_views from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views from chatroom import views as chatroom_views from django.urls import path from main.feeds import RssSiteNewsFeed, AtomSiteNewsFeed urlpatterns = [ ... path('blog/rss/', RssSiteNewsFeed()), path('blog/atom/', AtomSiteNewsFeed()), ] blog.models from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField (max_length = 160) slug = models.SlugField(max_length = 160,unique=True) date … -
Django , path('', views.IndexView.as_view(), name='index') Error :(
I'm new to Django and web coding. I'm following Bucky tuts: Django Tutorial for Beginners - 29 - Generic Views I'm trying to put my index in the urls , put it gives me an error on running the server : ImportError: cannot import name 'views' and here's my codes : urls.py from . import views from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', views.IndexView.as_view(), name='index'), path('base/', TemplateView.as_view(template_name="music/base.html")), path('music/', include('music.urls')) ] views.py from django.views import generic class IndexView (generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.object.all() need your help :) ,, -
Compressing Files with Cloudfront on Django
So, i'm trying to compress my files to improve the performance of my site at http://www.dealmazing.com I was serving static and media files with AWS and decided to implement Cloudfront in order to help compress files. I now run speed test in Google and it still says that I need to compress my files. I have turned on the Compress Objects Automatically feature in Cloudfront. Is there something additional that I should be doing? I can see in Google speed test that when it notes I need to compress my files that they are being served by Cloudfront. Appreciate any help on this. -
Django - Override manager for specific many-to-many relationship field
Say I have a model like so: class Appointment(models.Model): services = models.ManyToManyField( 'models.Service', through='common.AppointmentService') What I want to do is override the field to return a specific queryset (something like below which doesn't obv work): class Appointment(models.Model): services = models.ManyToManyField( 'models.Service', through='common.AppointmentService') @property def services(self) return super(Appointment, self).services.all_with_deleted() Details on the scenario: I am implementing soft delete. I soft delete the Service model, removing any "deleted" services from the application by setting a deleted_at field. But in regards to appointments that already exist with that service, I need to respect those services and not "delete" them. So, everywhere I use appointment.services I would need to call appointment.services.all_with_deleted(). But I don't want that littered throughout my code. The model should abstract those details away via a custom manager or overridden field. -
Setting up Django login with AngularJS app
I am trying to create a login session for my user but keep getting the following error message: Username and password combination is invalid., even though the username and password combination is correct. Not too sure why this is happening, all I want to do is authenticate the user and send a session cookie of some sort back to the client to process. How do I go about doing it? On the server: Djang application views.py class UserLogin(views.APIView): """ User login HTTP POST """ queryset = User.objects.all() serializer_class = UserSignupSerializer def post(self, request): return self.create(request) @staticmethod def create(request): if User.objects.filter(email=request.data['email']).exists(): account = authenticate(email=request.data['email'], password=request.data['password']) print(account) if account is None: return Response({ 'status': 'Unauthorized', 'message': 'Username and password combination is invalid.' }, status=status.HTTP_401_UNAUTHORIZED) if not account.is_active: return Response({ 'status': 'Unauthorized', 'message': 'This account has been disabled. Please contact us to get it re-enabled.' }, status=status.HTTP_401_UNAUTHORIZED) login(request, account) serialized = UserSignupSerializer(account) return Response(serialized.data) else: response_details = { 'data': "", 'message': "Your email address was not found. Please register as an Agency, Creator or Brand.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status']) class UserLogin(views.APIView): """ User login HTTP POST """ queryset = User.objects.all() serializer_class = UserSignupSerializer def post(self, request): return self.create(request) @staticmethod … -
Django 2.0 WSGI Apache Centos7 gets access dined from MySQL server
This issue has been bothering me for the past 24 hours. I have a Django App deployed to a CentOS7 server with Apache2 and WSGI. When I run python manage.py runserver 0.0.0.0:80, everything works fine. So is python mange.py shell. However when I run it with WSGI and Apache2, I can access the web pages, but anything that needs database access gives me an access denied error. I checked on MySQL server, all the permissions are set properly and I can access this database from anywhere else with this user except for from this CentOS server. Thanks for your help! -
Create extended entry along side user entry django
Hi Thanks for your help I have the code below that is working to create a new user when the "user_profile" part is commented out. I am just trying to add the extended fields to the user. I think im close but im a little lost. Whats the correct way of doing this? right now when i run it uncommented i get this error UNIQUE constraint failed: slug_trade_app_userprofile.user_id to be clear, before clicking submit that user does not exist in the database views.py def signup(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = UserProfileForm(request.POST) if user_form.is_valid(): #user created_user = user_form.save(commit=False) first_name = created_user.first_name last_name = created_user.last_name email = created_user.email password1 = request.POST['password1'] #extended profile created_profile = profile_form.save(commit=False) bio = created_profile.bio on_off_campus = created_profile.on_off_campus user = User.objects.create_user(username=email, first_name=first_name, last_name=last_name, email=email, password=password1) user.save() #####TRYING TO DO SOMETHING LIKE THIS user_profile = UserProfile.objects.create( user=user, bio=bio, on_off_campus=on_off_campus) user_profile.save() user_profile.save() models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True ) bio = models.TextField(max_length=500, blank=True) on_off_campus = models.CharField(max_length=3, default="on", choices=CAMPUS_STATUS) -
Django: Validation of parsed uploaded txt
I have a model C which includes a field 'hash' which requires validation before saving. # model.py class C(BaseModel): hash = models.CharField(max_length=10, blank=True, null=True, validators=[RegexValidator(regex='^.{10}$', message='Length has to be 10', code='nomatch')]) def clean(self): if self.hash is not None: if len(self.hash) != 10: raise ValidationError({'hash': 'OMG'}) Now in signal.py, I call a function to extract information from a txt file and want to save the validated data into the database from the backend. However, the problem arises, when I call the save function from signal.py. If I don't add manual validation in extract_info.py, the clean function from model.py will not be raised, i.e. even if the hash is 'ddd', whose length is not 10, the hash will still be saved to the database from backend. If I add manual validation in extract_info.py as shown in the code below, or I call the clean function manually, something like data.clean(), the validation will be raised but however turn to the debug page, instead of showing error message at the top of the page, as it will happen if I manually put 'ddd' in the hash field from frontend and click save. So, does anyone know if it is possible in django to parse … -
Cannot resolve keyword 'name' into field using get_queryset
Sorry is this is basic but I'm new at this I am attempting to take the captured group from a url in the template, (the primary key of the story model) and then use that to filter the correct posts from the Post datbase, which it has a one(story) to many(Post) relationship with. I based the code of the docs: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/#dynamic-filtering But when I run it, I get the error: FieldError at /story/1/ Cannot resolve keyword 'name' into field. Choices are: body, id, title, work, work_id My code: #views from django.shortcuts import get_object_or_404, render from django.views.generic import ListView, DetailView from . models import Post, Story class StoryListView(ListView): model = Story template_name = 'home.html' class PostListView(ListView): template_name = 'story_overview.html' def get_queryset(self): self.work_id=get_object_or_404(Post, name=self.kwargs['pk']) return Post.objects.filter(work_id=self.work_id) #urls from django.urls import path from . import views urlpatterns = [ path('', views.StoryListView.as_view(), name='home'), path('story/<int:pk>/', views.PostListView.as_view(), name='story_overview'), ] #templates/home.html {% extends 'base.html' %} {% block content %} {% for post in object_list %} <h2><a href="{% url 'story_overview' post.pk %}">{{ post.title }}</a></h2> <p>{{ post.description }}</p> {% endfor %} {% endblock content %} #models from django.db import models class Story(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=1500, default= "Description") def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=200, … -
Uploading multiple images for a model with a single form
I would like to be able to upload multiple images for my model using a single form. I use dropzone.js to handle file upload on the front end. For some reason, I'm getting the error that one of the forms is not valid and the images do not add. I think there is also an issue with my views.py, but I can't get to the bottom of the problem because the forms aren't valid. So in short, one listing can have multiple images and I want to create a form which creates a listing AND images in one go. My template.html form looks like: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input name="title" type="text" value="{{ listing_form.title.value }}"/> <input name="image_file" type="file"> <input name="image_file" type="file"> <button type="submit">Post New</button> </form> Models.py class Listing(models.Model): title = models.CharField(max_length=100, blank=False) posted_by = models.ForeignKey('auth.User', on_delete=models.CASCADE) class ListingImage(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) image = models.ImageField(blank=True) Forms.py class NewListingForm(forms.Form): class Meta: model = Listing fields = ['title',] class ListingImageForm(forms.Form): image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) # I tried to copy https://docs.djangoproject.com/en/2.0/topics/http/file-uploads/#uploading-multiple-files class Meta: model = ListingImage fields = ['image', ] Views.py def add_listing(request): if request.method == 'POST': listing_form = NewListingForm(request.POST) image_form = ListingImageForm(request.FILES) files = request.FILES.getlist('image_field') if listing_form.is_valid() and image_form.is_valid(): listing = … -
rendering the page not updated with new httprequest in django
I have a button on my page that passes an empty request payload which updates a form present on the page, making all the fields blank. How can I make the request not empty- but add the payloads already present on the form or may be render the form with the payloads already present? Below is the views.py code- I think I need to handle when form is not valid but I am not sure how- any suggestions will be very appreciated. def view(request, c_id): c = get_object_or_404(C, pk=c_id) if request.method == 'POST': if request.FILES: if 'filename' in request.FILES: file_form = CFileForm(request.POST, request.FILES) if file_form.is_valid(): new = file_form.save(commit=False) new.user = User.objects.get(username=request.user) new.save() ctract.ctract_file.add(new.id) return redirect('cract_view', ctract_id=ctract.id) else: return render(request,'view.html', {'form': form}) I want to render the page not with the empty payload (form), if the request is empty. -
synonyms and antonyms in a django dictionary app for local language
sorry for this question, but I had a problem with making a dictionary app for a local language, so I wouldn't need English dictionary, my problem is synonyms, I can't figure out how to implement it in my models from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse # Create your models here. class Voca(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("voca:detail", kwargs={"id": self.id, "name": self.name}) class Defination(models.Model): voca = models.ForeignKey(Voca, related_name='definations') defination = models.CharField(max_length=500) example = models.CharField(max_length=500) etymology = models.CharField(max_length=500) author = models.ForeignKey(User, default=1) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('created',) def __str__(self): return 'Defination given by {} on {}'.format(self.author, self.voca) class Synonym(models.Model): words = models.ManyToManyField(Voca, blank=True, related_name='synonyms') I would like for users to add words, synonyms, antonyms definitions to the database themselves since it is a slang language, so if I can get any help especially for antonyms and synonyms I would really appreciate... thanks -
SyntaxError: Unexpected token < in JSON at position 1
I am learning ajax with Django. This is my code but it logs SyntaxError: Unexpected token < in JSON at position 1 in my console.I tried editing the csrf_token part but nothing good could come. What can be the possible glitches in my code? index.html ... <form class="form-inline" action="translate/" method="post"> {% csrf_token %} {{ form }} <div class="form-group"> <input type="textarea" class="form-control email" id="email" placeholder="Enter text" name="string" autofocus=""> </div> <button type="submit" class="btn btn-success pull-right">Convert</button> </form> ... <script> var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $("#email").keyup(function () { var value = $(this).val(); $.ajax({ type:"POST", url: '/translate/', data: { "value": value, }, dataType: 'json', success: function (data) { alert(":)"); console.log(data); {#$("#googletrans").html(data.googletrans);#} }, error: function(xhr, status, error) { alert(error); console.log(error); } }); }); </script> views.py @csrf_exempt def convert(request): value = request.GET.get('value', None) data = { "googletrans": "prateek" } return JsonResponse(data) urls.py urlpatterns = [ url('', views.home, name='home'), url(r'^translate/$', views.convert, name='convert'), ]