Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django setting models.DateField() with a datetime object
I'm debugging some failing test after we recently upgraded from django 1.11 to 2.2, and i've noticed a behaviour that i havent been aware before. consider the following code from datetime import date, datetime, timedelta class User(models.Model): birthday = DateField() user = User.objects.create(birthday=date.today()) # setting the DateField object with datetime yesterday_datetime = datetime.now() - timedelta(days=1) user.birthday = yesterday_datetime user.save() user.refresh_from_db() print(user.birthday) # returns date.today() I've always assumed that when a DateField object has been populated with a datetime object, that the date aspect of the datetime object is taken and saved. It seems like this is not the case, and the field isnt updated / saved to the db. Is this a django 2+ behaviour or has this been the default for quite some time? Can anyone share their experience with this edge case? -
Django name magic in serializers.py file for HyperlinkedModelSerializer?
so I was trying to debug a problem where for a particular view using a HyperlinkedModelSerializer, one level of data was being returned as ints not urls. Ie, I was getting { "id": 4, "title": "asdf", "photos": [ 4 ], }, where I should have been getting { "id": 4, "title": "asdf", "photos": [ "http://localhost:8000/pics/4/" ], }, What was really weird, is the exact same viewset function works when I move it to the serializers.py file, but returns the wrong data when it lives in views.py. The function is as follows: class MemberMenuItemsViewSet(AuthModelViewSet): """ all items available from this maker (from all menus) """ serializer_class = MenuItemSerializer queryset = MenuItem.objects.all() def get_queryset(self): #def get(self, request, *args, **kwargs): member_id = self.kwargs.get('member_id') return MenuItem.objects.filter( menu__owner_id=member_id).order_by('-updated_at') I have solved my problem for now by moving this function to the serializers.py file and adjusting the call to it in urls.py ; but it is baffling why moving the function here instead of in views.py, should make any difference. I've tested it several times with consistent results, and my conclusion is there is some name magic going on? Or somewhere that I have not realized the serializers.py file is being pre-processed? Its no longer a … -
Connection refused while using MongoDB with Django
I'm using 2 databases for my Django project and they're in the settings as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'AppDB', 'USER': 'genericpiratename', 'PASSWORD':'pass', 'HOST': 'mypirateapp-postgres.ja6as4d8ss54.ap-south-1.rds.amazonaws.com', 'PORT': '5432', }, 'mongoDB' : { 'ENGINE': 'djongo', 'NAME': 'pirateapp', 'USER': 'uncommonpiratename', 'PASSWORD': 'dbpass', 'HOST': 'mongodb+srv://uncommonpiratename:dbpass@cluster1-8zu5ge.mongodb.net/test', } } The first database is a hosted PostgreSQL database and the second one is also a hosted MongoDB database. I used the mongodb atlas to host the cluster and compass to create the database pirateapp. I also allowed database access for both the databases from all IPs. I've used the following routers for the databases: class PrimaryRouter: def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True class DirectionsRouter: route_app_labels = {'tressureHunter'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'mongoDB' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'mongoDB' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in … -
Is there any multiple pagination on the same page but in different tabs in django?
I have tabs in django template displaying the tour packages category. For single page I am able to implement pagination in django but I am unknown regarding the pagination based on tabs. will please anyone suggest me any ideas how to filter in django views based on tabbed heading ? In single page I am using like this Models.py enterdef blog(request): blog_list = Blog.objects.filter(blog_verification=True) paginator = Paginator(blog_list, 6) # Show 6 blogs per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'blogs': page_obj, 'packages': Packages.objects.all()} return render(request, 'user/blog.html', context) Templates <div class="pagination"> <span class="step-links"> {% if blogs.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ blogs.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ blogs.number }} of {{ blogs.paginator.num_pages }}. </span> {% if blogs.has_next %} <a href="?page={{ blogs.next_page_number }}">next</a> <a href="?page={{ blogs.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> -
Exit a view function without triggering an error from Twilio, after unsubscribing a phone number? - Django
def sms(request): if request.method == "POST": umessage_body = str(request.POST['Body']).isupper() if umessage_body == STOP or umessage_body == STOPALL or umessage_body == UNSUBSCRIBE or umessage_body == CANCEL or umessage_body == END or umessage_body == QUIT: new_unsubscriber = Unsubscriber(phone_number=request.POST['From']) return elif umessage_body == START or umessage_body == YES or umessage_body == UNSTOP: Unsubscriber.objects.filter(phone_number=request.POST['From']).delete() return If user types one of the unsubscribe words such as STOP, I should add the phone number to my Unsubscriber model as a record, and then exit the sms function. How do I exit the sms function without triggering an error? Currently I get the error 21610 - Attempt to send to unsubscribed recipient from Twilio. -
Django - prefetch_related GenericForeignKey results and sort them
I have the below structure, where content modules, which are subclassed from a common model, are attached to pages via a 'page module' model that references them via a GenericForeignKey: class SitePage(models.Model): title = models.CharField() # [etc..] class PageModule(models.Model): page = models.ForeignKey(SitePage, db_index=True, on_delete=models.CASCADE) module_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) module_id = models.PositiveIntegerField() module_object = GenericForeignKey("module_type", "module_id") class CommonModule(models.Model): published_time = models.DateTimeField() class SingleImage(CommonModule): title = models.CharField() # [etc..] class Article(CommonModule): title = models.CharField() # [etc..] At the moment, populating pages from this results in a LOT of SQL queries. I want to fetch all the module contents (i.e. all the SingleImage and Article instances) for a given page in the most database-efficient manner. I can't just do a straight prefetch_related because it "must be restricted to a homogeneous set of results", and I'm fetching multiple content types. I can get each module type individually: image_modules = PageModule.objects.filter(page=whatever_page, module_type=ContentType.objects.get_for_model(SingleImage)).prefetch_related('module_object_') article_modules = PageModule.objects.filter(page=whatever_page, module_type=ContentType.objects.get_for_model(Article)).prefetch_related('module_object') all_modules = image_modules | article_modules But I need to sort them: all_modules.order_by('module_object__published_time') and I can't because: "Field 'module_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying" ... and I don't think I can add the recommended GenericRelation field to all the content … -
React: How to send a multipart/form-data to a database
I am currently setting up a file upload with React for the frontend and Django for the backend. More specifically, I want to pass a file + some data to my database via an API. But while uploading the file I get the error: "The submitted data was not a file. Check the encoding type on the form." models.py (Django) class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',null=True, validators=[validate_file_extension_audio]) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) serializers.py (Django) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = '__all__' A MultiPartParser is used to pass file + data. api.py (Django) class StoryViewSet(viewsets.ModelViewSet) (Django): serializer_class = StorySerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Story.objects.all() permission_classes = [ permissions.IsAuthenticated ] def perform_create(self, serializer): serializer.save(author=self.request.user) utils.py (Django) class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # find the data field and parse it data = json.loads(result.data["data"]) qdict = QueryDict('', mutable=True) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) In actions story.js (React) import axios from "axios"; import { tokenConfig } from './auth'; import { createMessage, returnErrors } from "./messages"; import {ADD_STORY} from "./types"; const apiBase … -
The If equal not working in Django Template
I am able to fetch these two values in the Django HTML template : {{ user.get_username }} {{post.user}} But when I use them further to compare their values in an IF condition, it doesn't work. {%if user.is_authenticated%} <h3> {{ user.get_username }}</h3> <h3> {{post.user}} </h3> {%ifequal user.get_username post.user%} <form action="{%url 'post_delete' post.id %}" method="POST"> {%csrf_token%} <button type="submit">Delete</button> </form> {%endifequal%} {%endif%} {%endfor%} I've also tried {% if user.get_username == post.user %} as well, but it didn't help either. Please help. I need the delete button only against the posts of logged in user. -
NOT NULL constraint failed: posts_comment.post_id django
I have the basics of a blogs app (I have been following Corey Schafer's tutorial, part 10, if that matters) and I am trying to post and display comments on the post that other users have wrote that only relate to that post. Similar to that of a comment section on Facebook or YouTube. Currently I'm displaying all comments in the database on every post because I don't know how to filter the results to only show comments for the specific post and I also don't know how to post comments to a specific post, that's where I get the error. My code is below: Models.py class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username Views.py class PostDetailView(DetailView): model = Post context_object_name = 'posts' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['comment'] = Comment.objects.all() return context class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) urls.py (This is the urls.py file in … -
How to connect to pymongo with django
my DB connection is DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'taxiapp', 'HOST':'127.0.0.1', 'PORT': xxxx, } } my SSH ADDRESS x.x.x.x SSH USERNAME 'admin' SSH PORT 0000 SSH AUTH method password and USER PASSWORD 0000 currently I am getting pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:xxxx: [Errno 111] Connection refused How to define SSH details in my settings.py file ??? -
how to simply add somthing to manytomany field in django REST with a request
i'm new in django rest. i want to be able to add things to "members" field. how serializers.py and views.py should look like? class Group(models.Model): since = models.DateTimeField(auto_now_add=True) groupid = models.CharField(max_length=20, blank=False, null=False, validators=[alphanumeric], unique=True, default='') #groupid only contains alphanumerical characters title = models.CharField(max_length=100, blank=True, default='No Name') describtion = models.TextField(blank=True) invite_only = models.BooleanField(default=False) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name='Created by', blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.SET_NULL) members = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True) #upper field should be modified. because right now, it's pointing to django's default superuser model class Meta: ordering = ['since'] def __str__(self): return self.title -
Why does this form not save?
the code below is a simple register for an account now when I submit this form it redirects me to the home page and this means that my form is valid and works but when I check my Admin page I see that account is not registered and I get no error. therefor I can understand here that my code is already working but it hasn't been saved. so, how can I save member through FormView? thanks in advance views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, View from django.views.generic.edit import FormView from .forms import UserForm from django.urls import reverse_lazy class IndexView(TemplateView): template_name = "accounts/index.html" class ProfileView(FormView): template_name = "accounts/register.html" form_class = UserForm success_url = reverse_lazy("accounts:index") def form_valid(self, form): print("the user has registered") return super().form_valid(form) forms.py from django import forms from .models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput) class Meta: model = User fields = '__all__' exclude = ('staff', 'active', 'admin', 'last_login') def clean_password2(self): password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password and password2 and password != password2: raise forms.ValidationError("Passwords don't match") return password2 def clean_email(self): email = self.cleaned_data['email'] qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") … -
How can i manage featured option if new article is create then old featured is expired and it show in without featured list?
i have two type of list's one is with featured boolean second is without featured. How can i manage featured option if new article is create then old featured is get expired and it's show in without featured list? example is here.. views.py articles = Article.status_objects.filter(featured=True)[:1] articleslist = Article.status_objects.all().exclude(featured=True)[:2] -
Django adds square brackets and quotes to charfield input
recently I encountered a rather weird problem with my Django forms. I am currently working on my todo list project. Everything works fine, except that whenever I add a new task, its title seems to be saved in database with additional square brackets and quotes around it. It looks like one-element list, but it is a string. I kinda solved it by displaying the silced version of the string from the database, but it still shows for example while editing a task. Hope anyone has some idea what might be going on? models.py: from django.db import models class Task(models.Model): title = models.CharField(max_length=35) completed = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) # added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) author = models.CharField(max_length=50, default='') def __str__(self): return self.title forms.py: from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}), } class TaskEditForm(forms.ModelForm): class Meta: model = Task fields = ['title', 'completed'] widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text'}), } views.py: from django.shortcuts import render, redirect from .forms import * from django.contrib.auth.decorators import login_required @login_required def list_homepage(request): tasks = Task.objects.filter(author=request.user.username) for task in tasks: if "['" and "']" in task.title: task.title … -
Django filter error sub-select returns 2 columns - expected 1
I would like to suggest same post categories on the current page detail So I try the following code: My views : def recipe(request, slug, message=''): post = get_object_or_404(Post, slug=slug) post_category = post.category.all() # get the categories of the post posts_same_category = Post.objects.filter( Q(category__name__icontains= post_category) # filter the same categories of the other posts ).filter(published=True).exclude(slug=slug) # exclude the current post and no publish posts My models : class PostCategory(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=250, null=True, blank=True) category = models.ManyToManyField('PostCategory', blank=True) mealtype = models.ManyToManyField('MealType', blank=True) I have a error on the post detail page : sub-select returns 2 columns - expected 1 I think the problem is with the ManytoManyField but what am I doing wrong ? Thanks in advance for your help ! -
Can I have a field name with spaces in Django Rest Framework?
Is there a way to remap the names of Django Rest Framewok SerializerFields to strings that contain spaces? I have the following sort of code: models.py: class Author(models.Model): author_name = models.CharField() serialisers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["author_name"] This will return JSON like: { "author_name": "William Shakespeare" } But I want it to return JSON like: { "The Author": "William Shakespare" } I know that I can use a different name for a serializer field using the source kwarg, but that still requires a valid python name. I'm specifically wondering if I can use a name with spaces in it. Thanks. -
How to use stored procedure or function created in mysql in django?
As I am learning django and MySql , I am creating a web page and want to use PlSql queries like triggers and procedure in my website using django. I have made connection of MySql and django. Can anyone help me how to proceed further. Thank you in advance! -
What is the most efficient way to insert a value into an integer ranked list?
I have a database that has a list of "Experience Levels", using Django Python. Each level comes with a unique rank attribute, which is a positive integer greater than one. The lower value rank is the first skill on a dropdown, and the highest value rank is the last, so a "Senior" with rank 3 is also everything below. I am creating an endpoint to update and insert values into this ranked list but I am having a lot of issues. In order to insert a new value, I need to change everything above the new rank and then insert it in. What is the most efficient way to do this? -
Bootstrap slider animation issue
I'm working with a bootstrap slider and the images are there, they switch every few seconds, almost everything works fine. But it won't display the animation, it's like suddenly it'll change the image. Here's the code: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{% static 'img/slider1.png' %}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'img/slider2.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'img/slider3.jpg' %}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Note: I'm using Django and I loaded {% static %} previously, so that isn't the issue. I also inserted the scripts from bootstrap. -
How to access a specific Wagtail page slug in a template
I have created a number of Wagtail snippets to represent a link to a page and the text to display. E.g. I might want to have a link to Contact us in many many pages, always with the same text that can be edited by the user. models.py @register_snippet class PageLink(models.Model): link_text = models.CharField(max_length=100) related_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=False, on_delete=models.SET_NULL, related_name='+', ) panels = [ MultiFieldPanel( [ FieldPanel('link_text'), PageChooserPanel('related_page'), ], heading = "Text and page", ) ] def __str__(self): return self.link_text class Meta: verbose_name = "Page link" verbose_name_plural = "Page links" register_snippet(PageLink) templatetags/link_tags.py @register.inclusion_tag("snippets/your_harmony_link.html", takes_context=True) def links(context): return { 'links': PageLink.objects.all(), 'request': context['request'], } your_harmony_link.html {% for link in links %} {{ link.url }} * {{ link.text }} <p> <a href="{{ link.url }}"> {{ link.text }} </a> </p> {% endfor %} I really just want to show one url here but I am looping through them just to sure I have got the model right. When the page is displayed I see all of the links as expected, but I can only see the link.text, not the link.url How can I get the url for a particular link? -
Can I use android studio in place of Pycharm for learning Django .. If No.. why? and if Yes ..how?
I am learning Django and the tutorial requires downloading Pycharm, which looks almost similar to my android studio IDE. So, can I do the same with android studio or I will have to download Pycharm ? -
Django, how to return a file after form submit?
I want to let the user submit a form with some filter criteria and respond with a csv file. This is my code: template: <form action="{% url 'filter_tracks' %}" method="get" id="filter-form"> <various filter params> ... <a class="md-btn" href="javascript:void(0)" onclick="$('#filter-form').submit();" id="csv_btn">Export</a> </form> views.py filename = "TRACKS_EXP{x}_{z}.csv".format(x=int(time.time()), z=lang) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{x}"'.format(x=filename) response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=',', dialect='excel', quotechar = "\"", lineterminator='\r\n',) for track in track_list: writer.writerow([...]) return response Although it works, I get the data inside my HTML page and not in a downloadable file. What am I doing wrong? -
Error while migrating Key (Category_id)=(1) is not present in table (after makemigration i put the default value=1 so problem came)
class Category(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class Destination(models.Model): category = models.ForeignKey(Category,models.CASCADE) name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False) sittayma = models.BooleanField(default= True) vid = models.FileField(upload_to='Video') -
How to assign objects in Foreign Keys in DRF?
My model: class Status(models.Model): COURSE_STATUS = ( ('COMPLETED', 'Completed'), ('ASSIGNED', 'Assigned'), ('PROGRESS', 'In progress'), ) course_status = models.CharField(max_length=9, choices=COURSE_STATUS, default='ASSIGNED' ) course_completion_date = models.DateField(blank=True, null=True, ) course = models.ForeignKey(TrainingCourse, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="students") Serializer: class AssignUserSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__ View: class StatusView(ModelViewSet): serializer_class = AssignUserSerializer queryset = Status.objects.all() permission_classes = [AllUsersProfileOnly, IsAuthenticated] I wanna make POST REQUEST and create and add to some users{id} to specific course such a "id": 35, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 3,** "id": 36, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 4,** now I got error like "Incorrect type. Expected pk value, received str." if try to send more than one id into user field error from Postman -
Problem in displaying 3 columns in my Django Blogapp....Only one column is shown...Its in masonry grid system
I made a blogapp using Django framework. Iam facing problem in displaying the posts.I want posts to be displayed in 3 columns but its showing in just 1 column...Please help me in editing my code... This is the code: **** {{ post.title }} {{ post.category }} {{post.created_date}} {{ post.text | slice:":200"}}