Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template not rendered in Vue served by Django
I have a Django app for backend, which renders templates with Vue as frontend. My view code in django has the following parts: # thing/views.py def index(request): template = loader.get_template('thing/index.html') return HttpResponse(template.render({}, request)) # thing/urls.py from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), ] # some other files that complete the project are not included In index.html there is the following code: <div id="app"> <p v-if="quotaRemaining > -1"> Remaining: {{ quotaRemaining }} </p> </div> <script> const app = new Vue({ el: '#app', data: { quotaRemaining: 42, }, }); </script> The only thing that is being rendered when I access this page is: Remaining: While I would expect it to be Remaining: 42 Why is my Vue template not being rendered correctly when served by Django? How do I make it work? -
URL pattern python Django
I am learning python django i am developing one website but i am struggling with URL pattern I am Sharing my code for URL pattern i don't understand where i am getting wrong url.py urlpatterns = [ url(r'^$',views.IndexView.as_view(),name='index'), # /music/id/ url(r'^picture/(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'), #for PictureDetail view url(r'^detail/(?P<pk>[0-9]+)/(?P<alb_title>[\w%20+A-Za-z]+)/(?P<song_title>[\w%20+A-Za-z]+)$', views.PicturedetailView.as_view(), name='picturedetail'), ] My Detail.html:- <ul> {% for picture in album.picture_set.all %} <div class="col-sm-4 col-lg-2"> <div class="thumbnail"> <a href="{% url 'music:picturedetail' pk=picture.pk alb_title=picture.album.album_title song_title=picture.song_title %}"> <img src="{{ picture.file_type.url }}" class="img-responsive"> </a> <div class="caption"> <h6>{{picture.song_title}}</h6> </div> </div> </div> {% endfor %} </ul> {% endblock %} I am passing three Parameters one with id and other two are strings ,i also updated my html href pattern but i am getting below error:- Reverse for 'picturedetail' with keyword arguments '{'pk': 3, 'alb_title': 'Beautiful River', 'song_title': 'River'}' not found. 1 pattern(s) tried: ['music/detail/(?P<pk>[0-9]+)/(?P<alb_title>[\\w%20+A-Za-z]+)/(?P<song_title>[\\w%20+A-Za-z]+)$'] Thank you in Advance -
Django: how to route URL requests to django.contrib.admin functions
I would like Django to return the same response for requests to /myapp/add as /admin/myapp/mymodel/add. myproject/myapp/models.py defines the model and myapp/admin.py registers with django.contrib.admin. myproject/myapp/models.py: from django.db import models class MyModel(models.Model): ... myproject/myapp/admin.py: from django.contrib import admin from .models import MyModel admin.site.register(MyModel) I am stuck on how to route the request to django.contrib.admin in the project's urlpatterns: myproject/myproject/urls.py: urlpatterns = [ url(r'^$', views.home_page, name='home'), url(r'^admin/', admin.site.urls), url(r'^myapp/add', ??????), ] From printing the return from resolve('/admin/myapp/mymodel/add/') this looks like part of the answer: ResolverMatch(func=django.contrib.admin.options.add_view, args=(), kwargs={}, url_name=myapp_mymodel_add, app_names=['admin'], namespaces=['admin']) -
The ssh server is not transferring git pull to the site
I made changes in the locale. I got GitHub with git push. I pulled this request with git push in ssh folder. I restarted nginx with "sudo systemctl restart nginx". But when I renew the site, I do not see any changes. note: I deleted the local folder today. then cloned back from github will this create a problem? -
Django TypeError missing 1 required positional argument when trying to use form input in another function
guys, I'm really a noob. What I'am trying to do is to use an input (a category to display) from a ModelForm and pass it to another function, which would render a table accordingly on the next page. Here is the first function from my views.py def index(request): form1 = PrimarySearchForm(request.POST) if form1.is_valid(): return results(request, form1.cleaned_data['actor']) template = 'main/index.html' context = {'form1': form1} return render(request, template, context) Here is the second function from views.py def results(request, actor): table = FactTable(Sawn_Areas_Fact.objects.get(actors=actor)) RequestConfig(request).configure(table) return render(request, 'main/results.html', {'table': table}) Here is the form class PrimarySearchForm(forms.ModelForm): class Meta: model = Actors_Dim fields = ('actor',) So, when I run the server, select an entry and click submit I get the following error message: TypeError: results() missing 1 required positional argument: 'actor' [29/Jul/2018 17:10:04] "POST /results/ HTTP/1.1" 500 59914 Thanks in advance for any help! -
'ManagementForm data is missing or has been tampered with'
I have been trying to implement a way to upload multiple images but I keep getting a managementform error. My way of uploading multiple images was to have the images their own table. And then just use a foreign key for every posts in the page. The problem occurs whenever I go to my create post page These are my code. Models.py from django.db import models from django.utils import timezone from django.forms import ModelForm from django.utils.text import slugify from django.utils.crypto import get_random_string from django.conf import settings from django.contrib.postgres.fields import ArrayField from PIL import Image import os # Create your models here. class Projects(models.Model): title = models.CharField(max_length=30) description = models.TextField(max_length=150) publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) slug = models.SlugField(unique=True) files = models.FileField(upload_to='files/', blank=True) images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True) img_height = models.PositiveIntegerField(default=600) img_width = models.PositiveIntegerField(default=300) def __str__(self): return self.title def save(self, *args, **kwargs): # Generates a random string unique_string = get_random_string(length=32) # Combines title and unique string to slugify slugtext = self.title + "-" + "unique_id=-" + unique_string self.slug = slugify(slugtext) return super(Projects, self).save(*args, **kwargs) def get_p_image_filename(instance, filename): title = instance.p_post.title slug_title = slugify(title) return "post_images/%s-%s" % (slug_slug, filename) class P_Images(models.Model): p_post = models.ForeignKey(Projects, default=None, on_delete=models.PROTECT) … -
How to work with Choices in Django - How to display specific content?
I try to create a book database in Django. I have to do one more thing. So i have a model with CHOICES: #model Book class Book(models.Model): #book types and placed BIOGRAPHY = 1 FANTASY = 2 HISTORICAL = 3 HORROR = 4 CLASSIC = 5 YOUTH_LITHERATURE = 6 NON_FICTION = 7 MODERN_LITERATURE = 8 POETRY = 9 ADVENTURE = 10 ESSAYS = 11 ROMANCE = 12 SATIRE = 13 THRILLER = 14 DRAMA = 15 NONE = 0 B00K_CHOICES = ( (BIOGRAPHY,'Biography'), (FANTASY, 'Fantasy/Sci-Fi'), (HISTORICAL, 'Historical'), (HORROR, 'Horror'), (CLASSIC, 'Classic'), (YOUTH_LITHERATURE, 'Youth Litherature'), (NON_FICTION, 'Non-Fiction'), (MODERN_LITERATURE, 'Modern Literature'), (POETRY, 'Poetry'), (ADVENTURE, 'Adventure'), (ESSAYS, 'Essays'), (ROMANCE, 'Romance'), (SATIRE, 'Satire'), (THRILLER, 'Thriller'), (DRAMA, 'Drama'), (NONE, 'No Information'), ) book_image = models.ImageField(upload_to='book_image', blank=True, null=True) book_name = models.CharField(max_length=255, unique=True) book_author = models.ForeignKey(Author, on_delete=models.CASCADE) book_types = models.IntegerField(choices=B00K_CHOICES, default= NONE) book_description = models.TextField(null=True, blank=True) book_pages = models.PositiveIntegerField(null=True, blank=True) book_published = models.DateField(null=True, blank=True) book_ratings = GenericRelation(Rating, related_query_name='book', default=NONE) def __str__(self): return '{}'.format(self.book_name) And i create a simple view with display this choices: def book_types_list(request): book = Book.objects.all() context = {'book': book, 'book_types': Book.B00K_CHOICES} return render(request, 'plibrary_core/book_types_list.html', context) I create also a html template with list of this choices: {% extends 'base.html' %} {% load static %} … -
django value of foreign key
Looping over a list of records, Django displays the literal value of each record. But, what if the field is a foreign key? So, here is an example {% for record in records %} {{ record.get_fields|dict_key:field }} {% endfor %} The dict_key is a template filter that imitates a dictionary get function given the field. @register.filter(name = 'dict_key') def dict_key(a_dict, key): the_key = normalize(key) # lowercases the key return the_dict.get(the_key, None) So, if a field is a foreign key in the model, Django will display the foreign key ID. Say, for example, the field is room, Django will show '1' (the foreign key ID for room) for the first record, '2' for the second record, etc. But, I want to know how to generically and programmatically render the value of the foreign key, e.g. 'Kitchen' for the foreign key with ID 1, 'living room' for the foreign key with ID 2, etc. Any help is appreciated -
Django won't make migrations with MySQL Database
I'm trying to make the migrations between my database (MySQL) and Django. I used the same parameters in Linux and didn't have any problems. Now I'm using the command : python manage.py migrate and I get nothing at all on the terminal. However, the command works if I let the default parameters ( for a sqlite database ). Also, I've noticed that it actually reads the 'settings.py' file because it returns an error if I write something that doesn't make any sense. Here are my parameters, I know for sure that they are correct ( I checked with the MySQL commands ). settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'root', 'PASSWORD': '123456789_dont_judge_me', 'HOST': '127.0.0.1', 'PORT': '3306', } } I'm using Windows 10, Python 3.5 and Django 2.0. Do you have any idea where the problem could come from ? Thank you for your responses kind people ! -
Django/Django Rest Framework DELETE not Allowed for Detail View
My view is defined with generics.RetrieveUpdateDestroyAPIView. I put a debugger and it properly enters the view as expected, so I do not think it is a problem with the URL. I am properly providing the resource ID for the resource that is to be deleted. When I view the response headers, I see: {'content-type': ('Content-Type', 'application/json'), 'vary': ('Vary', 'Accept'), 'allow': ('Allow', 'GET, POST, HEAD, OPTIONS')} As you can see, it appears DELETE and even PUT and PATCH are not allowed. Any idea as to why this is happening? Thanks! UPDATE to show View: class ItemDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = ItemSerializer queryset = Item.objects.all() -
Django; How can I connect javascript to db?
I'm doing project using Django and now I am trying to adapt js into the project. I'm not familiar with js and I'm wondering how I can manipulate db using js. For example, I want to use js for creating delete function. Currently, when I push delete button, I jump into the other page and then I have to push delete button again. But what I want to do is push the delete button and then pop up the window to confirm and delete something. How can I adapt js into Django in general? Here is current way first I have to push the button and jump into another page <button style="display: inline;" onclick="window.location='{% url 'blog:delete_entry' entry_id=entry.id %}'" class="btn btn-link">Delete</button> and then I have to push a button on the other page again. <button type="submit" class="btn btn-outline-danger" id="delete-button">Delete</button> Here is views.py def delete_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) if request.method != 'POST': form = EditEntryForm(instance=entry) else: form = EditEntryForm(instance=entry) entry.delete() return HttpResponseRedirect(reverse_lazy ('blog:my_entry')) return render(request, 'blog/delete_entry.html', {'entry': entry, 'form': form}) Anyone who can give me tips? -
django - Accessing server from remote devices
I'm aware this question has been asked before but mine is a problem the answers to those questions cannot solve. Whenever I try to access the site through other devices, it just loads forever and then says "this webpage took too long to respond". I have no idea what I am doing wrong. I've already tried: Running the command as manage.py runserver 0.0.0.0:8000 Running the command as manage.py runserver (mylocaladdress):8000 Setting ALLOWED_HOSTS to ['mylocaladdress'] Setting an inbound & outbound rule on the firewall in advanced security I have no idea what else to do. I am able to access the website from my local computer through the local address, but not from other devices. What am I doing wrong? -
Django form.is_valid() is returning false everytime
I have created a django application. In that, when I click on update button on index.html page, it has to redirect to a webpage showing the form with 3 fields,(title,user, body). Everytime I click on update, the form is not validating. It is always returning false. Actually if we press on the update button, the user field should show the present user's id. But it is showing default value. The body field is becoming empty every time. forms.py: class ImmediateForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}),initial="Immediate",max_length=20) class Meta: model = Immediate fields = ['title','user','body',] widgets = { 'user': TextInput(attrs={'readonly': 'readonly'}) } Models.py: class Immediate(models.Model): title = models.CharField(default="Immediate",max_length=30) user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) body = models.TextField(default="") def __str__(self): return self.title views.py: def update_immediate(request,pk): if not request.user.is_authenticated: return render(request, 'set_goals/index.html') else: print(pk) try: if request.method=='POST' : print('BItch.') immediate = Immediate.objects.get(user_id=pk) form = ImmediateForm(request.POST or None, instance=immediate or None) if form.is_valid(): print("no") immediate = form.save(commit=False) immediate.user = request.user.username immediate.body = form.cleaned_data['body'] immediate.save() return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate}) context = { "form": form, } return render(request, 'set_goals/create_template.html', context) except: if request.method=='POST' : print('BItch.') form = ImmediateForm(request.POST or None) if form.is_valid(): print("yes") immediate = form.save(commit=False) immediate.user = request.user immediate.body = form.cleaned_data['body'] immediate.save() return render(request, 'set_goals/detail_immediate.html', {'immediate': immediate}) context … -
How to split values by comma from object values - django2
I have this output when i print the actual code on my template: item1,item2,item3 with this code: related = Product.objects.filter(topic__icontains=topic).values('related').first() and i try with .split(',') but i get a blank result i need: item1 , item2, item3 I can create one backlink in each one to diferents urls, Is for add related topic links, i can split the data from related variable or i need take other way? -
Heroku - deploy django react app
I have created a django-rest-framework and reactjs webapp using this as reference. Then, I have created a heroku app. Added the heroku/python buildpack and the committed the changes to heroku. The problem that I am facing after deploying to heroku is how I should run react? My file structure is a little different than what everyone has!! -frontend -package.json -app -settings.py -webapp -views -serializers -templates -index.html -requirements.txt -Procfile -runtime.txt I know that I have to include heroku/nodejs but my package.json is not in root folder. So, how do I handle that? Please specify if I need to provide any more details! -
How to look ahead and order a queryset in django?
I'm developing a chat app. The models are: User: name and Message: user = ForeignKeyField(User, related_name="messages"), message, time Now, There are just two users in the database. Lets say the message objects are like: msg1: user1: "hello" msg2: user1: "how are you?" msg3: user2: "I'm fine." msg4: user1: "what's up?" msg5: user2: "nothing much." msg6: user2: "Hmm." Now I need to get the messages in an order as (let's say json): {user1:[msg1, msg2], user2:[msg3], user1:[msg4], user2:[msg5, msg6]} I need it to be filtered in a queryset something like: Message.objects.filter(....).order(....) ***used json here for understanding. How could this be done? Are there any drawbacks? I am to render this in the template afterwards. So, Is it possible to order the same inside a template using for loop? -
Elastic Beanstalk instance not responding with https
I'm trying to setup https on my EB instance, which is runnning a django app, it currently works with http, but with https it times out. I've been through every step I thought I needed to: Created self signed certificate with name being the domain (myapp123.vdfb.eu-central-1.elasticbeanstalk.com) and uploaded it to the Certificate Manager Setup port 443 on the Load Balancer: Add rule on the security group attatched to the ec2 instance: Also add rule on the security group attatched to the Load Balancer: Also added these lines in my settings file in the django app: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True After all of this, it still keeps not resolving when I try to access it with https://.... What am I missing? -
Django gives 'CSRF token missing or incorrect.' error even after passing it in the POST call
I have a django application that is successfully able to signup and login a user.However I am unable to logout a user. In the front end, I have a webpage that contains a power button icon, which on clicking should trigger a logout request. I am using angular js for front end index.html <div class="col-xs-2"> <span style="opacity: 0.5;font-family: FontAwesome;font-size: 14px;color:#838F98;text-align:center;cursor:pointer" ng-click="logout()"> <i class="fa fa-power-off" aria-hidden="true"></i> </span> </div> Here I use ngclick to call the logout() function that is defined in my index.js index.js $scope.logout = function() { var url = '/logout'; var toSend = { csrfmiddlewaretoken: '{{ csrf_token }}' } $http({ method: 'POST', url: url, data: toSend, }).then(function(response) { response.data; }) }; This function calls the /logout url for which I have defined an auth views in urls.py urls.py from django.contrib.auth.views import login, logout url(r'^logout$', logout, {'template_name': 'login.html'}), But when I click the power icon on the webpage, I get a 403 Forbidden error.It says CSRF verification failed. Request aborted.But I am passing the csrf token in the javascript POST call. What am I doing wrong? -
django about filter--I want to filter card, its age is over 30
I want to filter card, its age is over 30. if user.age >= 30: card = models.MtomCard.objects.filter(age>30) it doesn't work.. how do i fix it? -
How to get Filename in DjangoWebApp based on a Model containing FileField?
I making a email delivery WebApp, I have an Email Class with uploadcsvfile to upload the .csv contact file from the user's computer to server at location CONTACT_DIR, what I'm unable to figure out is how to get the saved contacts_some_char.csv name in my views.py, the purpouse of getting it's name is so that I can parse the email list and send email to them. I have my model.py as follows : class Email(models.Model): fromemail = models.EmailField(blank = False, max_length = 254) uploadcsvfile = models.FileField(upload_to = 'Contacts', blank = False) subject = models.CharField(blank=False,max_length = 254) bodyHeading = models.CharField(blank = False,max_length = 254) bodytext = models.TextField(blank = False) name = models.CharField(blank = False,max_length = 254) Here is my views.py : def index(request): if request.method == 'POST': email_form = EmailForm(request.POST, request.FILES) if email_form.is_valid(): email_form.save(commit = True) print(Email.uploadcsvfile) contacts = Contacts() #path = settings.CONTACT_DIR f = open(settings.CONTACT_DIR+"/"+str(uploaded_file_name)) csv_f = csv.reader(f) Emails = [] Names= [] L_Names = [] for x in csv_f: Emails.append(x[0]) Names.append(x[1]) L_Names.append(x[2]) f.close() contacts.ListOfEmails = json.dumps(Emails) contacts.ListOfFirstNames = json.dumps(Names) contacts.ListOfLastNames = json.dumps(L_Names) contacts.save() Here is forms.py for the same : from django import forms from dcsvreader.models import Email class EmailForm(forms.ModelForm): class Meta(): model = Email fields = "__all__" A.K.A How … -
How to make a xml request and receive an xml response using django
How to make a xml http request and get xml response in django python? request <Message> <Header> {Auth:'54873' } </Header> <Body> <Request> <CustID> 12345</ CustID > </Request> </Body> </Message> Response: <Message> <Header> {Auth:'54873'} </Header> <Body> <Response> <ID> 56789</ID > </Response> </Body> </Message> -
Django - How can I set manually DateTimeField value given date and time?
How can I set manually DateTimeField value given date and time ? Here is my model and I am trying to assign date & time value to "created_at" field: class Attendance(models.Model): employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.employee.username Here is something I tried in the console: > o = Attendance.objects.last() > o.updated_at datetime.datetime(2018, 6, 26, 0, 45, 31, 829827, tzinfo=<UTC>) > x = datetime.strptime('17/07/2018 12:20', '%d/%m/%Y %H:%M') > x datetime.datetime(2018, 7, 17, 12, 20) >o.updated_at = x o.save() >z = Attendance.objects.last() >z.updated_at datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=<UTC>) notice that I set "2018, 7, 17" but it appears "2018, 7, 29". is the assignment correct ? probably it needs the timezone as well. -
How to customize django admin using css?
I was trying to apply some styles from http://awesome-django.com/ in order to customize my django-admin page but when i install any of them it seems that they require an old version of django (1.8) while i'm using 2.0.7 . it shows me this error : Successfully built django-admin2 django-extra-views future django-admin-bootstrapped 2.5.7 has requirement Django=1.8, but you'll have django 2.0.7 which is incompatible. So i decided to style it myself using CSS but i don't know which file and folder i should edit or apply a template on it . -
In Django Installed_Apps settings, what is the importance of writing "$APP_NAME.apps.$APP_NAMEConfig"?
I am following some of the Django courses and these courses have different formats for some specific code parts. This is the one of them. For example, in the Installed_Apps part of settings.py, what is the difference between writing; INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_pdb', 'polls.apps.PollsConfig', ] or INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_pdb', 'polls', ] Thank you for your time and your answers. -
How to query a ManyToMany Field to contain exactly with a list?
I have a User model as: User: name and a Room as: Room: users = ManyToManyField(User, related_name="rooms") Now. I also have: user_ids_list = [1,5] and there is a room only with these two users. There is a user instance as: user1 = User.objects.get(pk=1) So, I can get all the rooms of user1 as: user1.rooms.all() But, I need to find the room which has users with ids [1,5]. I have came across: user1.rooms.filter(users__id__in=[1,5]).exists() => True But, user1.rooms.filter(users__id__in=[1,23]).exists() => True also returning True. Ok. it's like if any one in the list exists in the room. It is returning True. But if both of the users have no room, then it is returning False. How am I supposed to deal with it?