Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms:Post request is got but data is not saved
So I'm trying to build a Django site that collects Mod Applications to learn Django Forms. Except that I'm an idiot and I don't know what am I doing. The thing that I'm trying to do is collect and save the Form data the current part and later try to show that data in the Django Admin the part I still haven't done and don't know how. When I fill out the form I get [06/May/2017 19:38:29] "POST /modapp HTTP/1.1" 200 2354 This is my forms.py: class Application(forms.ModelForm): class Meta: model = ModApplication fields = ('discord', 'reddit', 'serverrank','finds','serverstay','active','timezone','reason','helped','help') def __init__(self, *args, **kwargs): super(Application, self).__init__(*args, **kwargs) self.fields['discord'].widget.attrs['placeholder'] = 'UnknownDeveloper#2068' self.fields['reddit'].widget.attrs['placeholder'] = '/u/UnknownDeveloper' self.fields['serverrank'].widget.attrs['placeholder'] = 'GEOCACHING + RANK' self.fields['serverstay'].label = "How long have you been on the server" self.fields['active'].label = "How active have you been on the server" self.fields['timezone'].widget.attrs['placeholder'] = 'CET' self.fields['reason'].label = "Why do you want to become a mod?" self.fields['helped'].label = "How have you helped the server so far?" self.fields['help'].label = "How will you help the server if you'll become a mod" models.py class ModApplication(models.Model): def __unicode__(self): return "Discord User: " + self.discord + " aka " + self.reddit reddit = models.CharField("Reddit Username", max_length=30) discord = models.CharField("Discord Username", max_length=30) serverrank … -
Edit profile in Django
What I need is an edit profile form to edit username,password and avatar.But these fields are in 2 models.User and allusers(OneToOne).How can I create a edit profile form by combining the fields of both. Models.py class allusers(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='retest/static/images/') def __str__(self): return str(self.user) -
Django-tables2 KeyError when field has {curly brackets}
I have a model with Artist and Track class and when the title field of a Track has curly brackets, I get a KeyError Exception. (E.g. Track Title "Beat It {Freestyle}"). Looks like django_tables2 is passing my Track title field value to string.format(). How do I prevent that in django_tables2? models.py class Artist (models.Model): name = models.CharField(max_length=100) slug = AutoSlugField(populate_from='name', unique=True, editable=True, slugify=custom_slugify) class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Submitted by", default=1) title = models.CharField(max_length=100, verbose_name="Title") timestamp = models.DateTimeField(default=timezone.now) tables.py class TrackTable(tables.Table): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) self.artistlink = kwargs.pop('artistlink', None) super(TrackTable, self).__init__(*args, **kwargs) def render_artist(self, value): if self.artistlink == True: return format_html('<a href="/music/by/{}">{}</a>', value.slug, value) else: return value def render_user(self, value): return format_html('<a href="/users/{}">{}</a>', value, value) download = DownloadColumn(empty_values=(), orderable=False) track_id = tables.CheckBoxColumn(accessor="pk", attrs = {"th__input": {"id": "checkAll"}}, orderable=False) class Meta: model = Track attrs = {"class": "table table-bordered table-condensed table-striped", "id": "track-table",} fields = ('track_id', 'artist', 'title', 'user', 'download') views.py def profile_detail(request, slug=None): alpha_list = ['0-9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] playlist_list = Playlist.objects.filter(user=request.user.id) … -
Need to a function or any way of making 1 image a featured from the image set
So I have these 2 models (Product and ProductImages models) and I want the user to be able to select from the images, a featured image of his/her choice from the many uploaded images (ProductImages model) and this will be reflected in the template as a featured image for that product. Product model class Product(models.Model): name = models.CharField(max_length=70) slug = models.SlugField() description = models.TextField("About", max_length=400) category = models.ManyToManyField(Category, verbose_name="Categories", blank=True) order = models.IntegerField("Order", default=0) featured = models.BooleanField("Featured", default=False) def __str__(self): return self.name ProductImage class ProductImages(models.Model): business = models.ForeignKey(Business) image = models.ImageField(upload_to="images/product") title = models.CharField(max_length=120) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.title This can be a function that will help to enable the user select the profile image of their choice. What do you think? will be grateful for your response -
My custom django login view won't work
I was trying to make my own custom login page to test my django skills but it would never work. My View: def login_view(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user: login(request, user) redirect('/account/') else: print(str(password)+" "+str(email)) else: form = LoginForm() return render(request, 'users/login.html',{'form': form}) My Forms class LoginForm(forms.Form): email = forms.CharField( widget=forms.TextInput(attrs={'class': 'registerforms', 'placeholder': 'Email'}), label='', ) password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'registerforms', 'placeholder': 'Password'}), label='', ) My urls url(r'^login/$', views.login_view, name='login_view'), My Template <form action="" method="post" role="form"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> -
deploying webpack + vuejs + django to Heroku, procfile configurations
I'm trying to deploy my VueJS Django app to Heroku but running into issues with running webpack on Heroku. I'm able to collect the static files but it doesn't seem like it's running the npm commands so the website isn't running webpack, which means not only will VueJs files not be transpiled to ES5, but my index.html page will not even call the bundled up code that webpack outputs. Any ideas why this is happening and how to fix it? On somewhat related notes: I'm using Gunicorn as web server and whitenoise to serve my static files. Here's what I have (mostly everything is based off of VueJS Element starter kit) Package.json: { "name": "element-starter", "description": "A Vue.js project", "author": "yi.shyang@ele.me", "private": true, "scripts": { "dev": "webpack-dev-server -d --inline --hot --env.dev", "heroku-postbuild": "rimraf static && webpack -p --config ./webpack.config.js --progress" }, "dependencies": { "element-ui": "^1.1.2", "vue": "^2.1.8" }, "engines": { "node": ">=6" }, "devDependencies": { "autoprefixer": "^6.6.0", "babel-core": "^6.21.0", "babel-eslint": "^7.1.1", "babel-loader": "^6.4.0", "babel-plugin-transform-es2015-modules-commonjs": "^6.24.1", "babel-preset-es2015": "^6.13.2", "css-loader": "^0.27.0", "eslint": "^3.12.2", "eslint-config-enough": "^0.2.2", "eslint-loader": "^1.6.3", "file-loader": "^0.10.1", "html-loader": "^0.4.5", "html-webpack-plugin": "^2.24.1", "postcss-loader": "^1.3.3", "rimraf": "^2.5.4", "style-loader": "^0.13.2", "url-loader": "^0.5.8", "vue-loader": "^11.1.4", "vue-template-compiler": "^2.1.8", "webpack": "^2.4.1", "webpack-dev-server": "^2.4.2" } } Procfile: … -
ValueError: Cannot use Queryset for "": Use a Queryset for ""
I'm working on a little project using these models here and I'm trying to figure out a way to get a set of all the posts associated with users the currently authenticated user is following. But I keep getting: Cannot use QuerySet for "profile": Use a QuerySet for "User". class Profile(models.Model): user = models.OneToOneField(User) isInstructor = models.BooleanField(default=False) isTutor = models.BooleanField(default=False) isStudent = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) following = models.ManyToManyField('self', related_name = "followers", blank=True, symmetrical=False) profile_image = ImageField(upload_to=get_image_path, blank=True, null=True) class Post(models.Model): title = models.CharField(max_length=100) topic = models.CharField(max_length=50) description = models.CharField(max_length=1200) poster = models.ForeignKey(User, related_name="posts") likes = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, blank=True, related_name="posts") def __str__(self): return self.title This is what keeps giving me the error. current_user = Profile.objects.get(user = self.request.user) Post.objects.filter(poster__in = current_user.following.all()) I searched around an found out that I had to use the __in operator whenever you want to filter by a list of things. But I keep getting the same error. Any help with explaining what the error means and what I can do to get around it would be much appreciated. -
Django Folders Permissions Setup?
Since I am having a Django PermissionError at / I need to change permissions on my folders. My question is what is the right level of permission for those folders which still secures my server? I use Apache on Ubuntu. -
What python web framework should i use with google app engine?
Hi I am planning on making a social media app in google app engine. I am going to use python and cloud bigtable for my database. Should I use either django or flask for my web framework or do I not need to use a web framework with google app engine? I did some research and saw that it is not easy to use django with a nosql database like cloud bigtable. -
Keycode authentication to access webapp
I'm trying to build a surprise website for my friend and I wanted it to be fun -- in the homepage, I wanted to build a simple keycode access (very similar to iphone's enter-your-keycode homescreen) page such that access to the rest of the webapp is only possible if the keycode entered in the homepage is right. How do i go about doing this? I'm new to django, and i only know how to do username-password authentication. How do i create a key-code access and that only by having the right keycode can anyone see the rest of the website? Thank you so much! -
Django shopify auth app has no attribute 'Session'
I have installed django-shopify-auth app. When i am trying to migrate then the bellow errors are showing: (shopify) D:\CROSS PLATFORM\shopify>python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "C:\Users\tapor\Envs\shopify\lib\site-packages\django\core\management__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Users\tapor\Envs\shopify\lib\site-packages\django\core\management__init__.py", line 324, in execute django.setup() File "C:\Users\tapor\Envs\shopify\lib\site-packages\django__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\tapor\Envs\shopify\lib\site-packages\django\apps\registry.py", line 115, in populate app_config.ready() File "C:\Users\tapor\Envs\shopify\lib\site-packages\shopify_auth\apps.py", line 20, in ready initialise_shopify_session() File "C:\Users\tapor\Envs\shopify\lib\site-packages\shopify_auth\apps.py", line 29, in initialise_shopify_session shopify.Session.setup(api_key=settings.SHOPIFY_APP_API_KEY, secret=settings.SHOPIFY_APP_API_SECRET) AttributeError: module 'shopify' has no attribute 'Session' ====== Looking forward for help, Thanks ======== I am using windows 10 OS -
Django Contact Form Inputs Won't Show Up - Only See Submit Button
I am running into some trouble here as I attempt setting up a contact form on my personal webpage. For whatever reason I can only see the submit button, the rest of the input fields are not populating. Can someone please help? Thanks! email.html {% load static %} {% block content %} <div id='paddingtop'> <div class="row" id="title"> <div class="col"><img src='{% static 'personal/img/contactme.png' %}' style="height: 100%; width: 100%; max-width: 530px; max-height: 1000px; min-height:500; min-width: 300px;"> </div> </div> </div> <div class="col" style='margin-top: -40px; max-height: 100%; max-width: 100%;'><hr class='underline'></div> <div class='email' style='background-color: blue; width: 100%; height: 100%;'> <form method="post" role="form" action=""> {% csrf_token %} {{ form.as_p }} <div class="form-actions"> <button type="submit" style='background-color: red;'>Send</button> </div> </form> </div> {% endblock %} forms.py from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) urls.py from django.conf.urls import include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^home/$', views.index, name='home'), url(r'^header/$', views.header, name='header'), url(r'^email/$', views.email, name='email'), url(r'^success/$', views.success, name='success'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py from django import template from django.conf import settings from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, … -
How does Django Rest Framework deserialize foreign key relationships?
In the tutorial, there's this loose one-to-one mapping between serializer fields and model fields. I can expect that if a serializer field and a model field are both CharFields it will save a string of characters when deserializing into a model instance: models.py: class Deck(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, unique=True, blank=False, null=False) serializers.py: class DeckSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Deck fields = ('url', 'id', 'created', 'name') extra_kwargs = { 'url': { 'view_name': 'goals:deck-detail', } } But when I try a relationship, the serializer field is a ReadOnlyField, which from what I understand is essentially a Charfield, but the model field is a ForeignKeyField, and to add to the confusion, it seems like I'm saving an object in the views when I override perform_create: models.py: class Deck(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, unique=True, blank=False, null=False) user = models.ForeignKey('users.User', related_name='decks', on_delete=models.CASCADE, null=False) serializers.py: class DeckSerializer(serializers.HyperlinkedModelSerializer): user = serializers.ReadOnlyField(source='user.username') class Meta: model = Deck fields = ('url', 'id', 'created', 'name', 'user') extra_kwargs = { 'url': { 'view_name': 'goals:deck-detail', } } views.py: class DeckList(generics.ListCreateAPIView): serializer_class = DeckSerializer def get_queryset(self): return Deck.objects.all().filter(user__username=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) What's going on here? When dealing with relationships, why is it that I am saving an … -
django-registration returning only submit button
I've installed, registered, and migrated after installing django-registration. The problem is, it's returning a page with just a submit button. Is that the expected behavior? The base.html it extends from is loaded (I can tell by the tab's title, which is set by it), but the form itself isn't getting loaded as it should (or at least that's what I'm suspecting). Inside my project, I have a register app. I've downloaded these templates and placed them in this path: project/register/templates/registration Below are my register app files and their contents: project/register/urls.py: from django.conf.urls import include, url from . import views urlpatterns = [ # Other URL patterns ... url(r'^', views.index), # More URL patterns ... ] project/register/views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import loader def index(request): context = {} return render(request, 'registration/registration_form.html', context) Contents of registration_form.html: {% extends "base.html" %} {% load i18n %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% endblock %} Specifically with the index view, which I suspect to be the culprit, I've tried several ways of returning several objects. After a few hours of searching here and … -
Why am I getting the error message ImportError: No module named <app>.urls?
I was recently building a django project. I have been looking through the files for a couple of hours now and can't find the problem that would result in this kind of error message. Below, I will show you all of the relevant files within the project. base url.py: from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^display/', include('diplay.urls')), ] app url.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] app views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h2>HEY!</h2>") I'm not sure why this is not working because I found a similar format online, and it seemed that every line was similar to the other one. When I try running the server, it gives me the error statement "ImportError: No module named diplay.urls". Any ideas? Thanks in advanced. -
Create object from its foreign key's object
I have two objects: Restaurant and Review, a Review has a foreign key Restaurant (one-to-many relationship). In my views.py, these two classes make me concern the most: RestaurantDetailView(show detail view of a Restaurant), and ReviewCreate(create a review). My point is I want to create a button "Write a Review" my Restaurant Detail page that send a request to create a Review, but that Review has to contain the foreign key of the Restaurant where I sent request from. Any suggestion of how I should do this? For reference: class RestaurantDetailView(generic.DetailView): model = Restaurant template_name = 'service/detail-restaurant.html' class ReviewCreate(CreateView): model = Review fields = ['title', 'description'] def form_valid(self, form): review = form.save(commit=False) review.restaurant = self.request.user return super(ReviewCreate, self).form_valid(form) -
Django Development Server doesn't let me start on Homepage
I've tried to resolve my problem but didn't succeed. When I start the Development Server from Django, I try to access http://127.0.0.1:8000/, but when entered in the Browser it always adds the part /catalog at the end of the URL. I then get an Error (http://i.imgur.com/4eMEqkc.png). I know that it should show the site "It worked!". I have tried to delete all projects and reset all settignd I have changed but it still redirects me every time. Has someone an answer to this problem? -
Django dynamic urls / Sitemap builder
I am trying to create a site map builder in django. This would consist of a model that looks something like this: class SiteMap(models.Model): title = models.CharField(max_length=256) # The title of the page url = models.CharField(max_length=256) # url fragement, .../url/... page_type = models.CharField(max_length=256) # Like forum, livechat, etc... under_page = models.ForeignKey(SiteMap, blank=True) # page this exists under All of the views would be preexisting so my question is how do I direct the url created from the models into the views. If this method is completely wrong don't be afraid to suggest a completely new way of doing this. -
Webapplication created with django refusing connection after importing reverse in views
I want to redirect from one page to another in my web application and want to use the reverse function. Everything works perfectly (except the redirect), but when I import from django.core.urlresolvers import reverse in my view.py file, suddenly my access is denied and the following error pops up: 127.0.0.1 has refused the connection ERR_CONNECTION_REFUSED This happens after the import. No other code is added -
Why does nginx take so long to take effect?
I'm trying to deploy nginx on an Ubuntu Server machine on AWS. However, upon installation of nginx with default settings, it sometimes takes 15-20 minutes for the default nginx page to show up when I visit the site: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. Also, when I change the nginx config, the server takes the same amount of time to update with the new settings. (1) Is this behavior normal? I didn't change anything in the default nginx setup. Just did a simple sudo apt-get install nginx. I'm a beginner to Linux and nginx, so I don't understand a lot of the underlying mechanisms behind nginx. Perhaps it's these mechanisms that cause nginx to serve files to the outside world? (2) Should any changes to nginx configs take effect immediately after restarting nginx? -
Django check if user is in OneToManyField
I want to make something similar to facebook likes, but it is called marks.Im trying to display "Marked" in html if user has marked the exam, or "not marked" if user hasnt marked the exam. So i have this in models.py: class Exam(models.Model): exam_number = models.PositiveIntegerField(validators=[MaxValueValidator(6),MinValueValidator(1)]) exam_user = models.ForeignKey(User, null=True) exam_mark = models.ManyToManyField(User, blank=True, related_name='post_mark') In views, I add marks with this view: def mark_exam(request, letnik_id, classes_id, subject_id): exam_id = request.GET.get('exam') exam = get_object_or_404(Exam, id=exam_id) user = request.user if user in exam.exam_mark.all(): exam.exam_mark.remove(user) return JsonResponse({"mark": "unmarked"}) else: exam.exam_mark.add(user) return JsonResponse({"mark": "marked"}) How would i check if user has alredy marked an exam in template? I was trying something like: {% if user in exam.exam_mark.all %} <h1>Makred</h1> {% else %} <h1>Not marked</h1> {% endblock %} , but is there any more elegant solution? -
Django, schema of database - User table. Why the fields are grey or italics?
I generated schema database and in my User table I see : id - normal but <b> date_joined - italics email ... ... ... last_name - italics and grey password - italics username - italics What does it mean? -
Django REST Serializer, show an exact value
Really I did an almost 5-hours research and could not find something that will work the way I want. The question is just a simple one, I suppose. I wanna build a REST Django framework for Game, with serializers etc. When I try to ask for "Genres"(Game Genres), the JSON return this: Genre Serializer Ideally, I just want to return only the values of the game genres without the annoying "GenreTitle", everywhere. My model: class Genre(models.Model): GenreTitle = models.CharField(max_length=30,verbose_name = 'Title') GenreDescription = models.TextField(max_length=500,verbose_name = 'Description') GenreImage = models.ImageField(null=True, verbose_name='Image') def __str__(self): return self.GenreTitle My serializer: class GenreSerializer(serializers.ModelSerializer): class Meta: model= Genre fields=('GenreTitle',) I know that is a pice of cake for Django developers, but i struggle much because I am beginner at this. Thanks in advance! -
Searching objects in django
Please help, because I'm confused. I'm using Django 1.11 and python 3.5. Trying to get values, and when getting via "contains" everything is working, but when i trying iexact function use, have all the time wrong response. Why? Examples : >>> print(Blog.objects.filter(title__contains='Django')) <QuerySet [<Blog: 1>, <Blog: 4>]> >>> print(Blog.objects.filter(title__iexact='Django')) <QuerySet []> or >>> print(Blog.objects.get(title__contains='Django')) 1 >>> print(Blog.objects.get(title__iexact='Django')) ... blog.models.DoesNotExist: Blog matching query does not exist. Thanks -
Django redirect to template passing model
The think I'm trying to do is to redirect to the same page where user was when deleted an item. After delete using "django.views.generic.edit" (DeleteView) I can collect all needed information into model and get the specific category that I need. The question is how can I create this request url to go? This way I get to http://127.0.0.1:8000/productlist/floor/ <a class="dropdown-item" href="{% url 'productlist' 'floor' %}" > views.py class LampDelete(DeleteView): model = Lamp #success_url = reverse_lazy('index') def get_success_url(self): categ = self.object.category lamps = Lamp.objects.filter(category=categ) return redirect('productlist', {'lamps': lamps}) urls.py urlpatterns =[ url(r'^$', views.index, name='index'), url(r'^productlist/([a-z0-9]+)/$', views.productlist, name='productlist'), url(r'^accounts/', include('allauth.urls')), url(r'productlist/(?P<pk>[0-9]+)/delete/$', views.LampDelete.as_view(), name='lamp-delete'),] So what method should I use and how to redirect to my template with selected category model. If somebody could provide an example would be very thankful.