Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
if id is given, how do i find the other values of other attributes in this list with dictionaries inside
my_playlists=[ {"id":1,"name":"Bicycle Playlist","numberOfSongs":3}, {"id":2,"name":"Coding Playlist","numberOfSongs":2} ] if the input is 1, which is supposed to be considered as an id. how do I get the name attribute? and its value? -
Django: is_ajax() doesn't work while is_ajax does
So I'm trying to understand ajax in django. I try to make a view (MessageCreate) which will create a message and then display that in ChatView (DetailView) which is constantly reloading (that is already done and works fine). But while trying to make this MassageCreate, there are always problems with "POST not allowed". So while trying to understand what's exactly going on with that ajax, I've done small tests and it turned out that request.is_ajax() returns false while request.is_ajax works fine. How is that possible? Here is my ajax function $(function() { // This function gets cookie with a given name function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); /* The functions below will create a header with csrftoken */ function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // … -
Ubuntu/Nginx/EC2 Instance - Unreadable files (R they malicious??)
I was looking through an EC2 Instance (not created by me) and found a few files. When I tried to nano into it, the files are unreadable and I'm not sure if they are malicious or not. Is there any way to decipher and see if these files are malicious or should I just remove it? example file that I nano into Greatly appreciate your help! -
django application registry into INSTALLED_APPS should not import any models ,how to understand it?
I don't understand what mean follow, and always get error like django.core.exceptions.AppRegistryNotReady:Apps aren't loaded yet.,how can i do, thanks! First Django imports each item in INSTALLED_APPS. If it’s an application configuration class, Django imports the root package of the application, defined by its name attribute. If it’s a Python package, Django creates a default application configuration. At this stage, your code shouldn’t import any models! the doc is here: enter link description here -
Number of Post Views is not showing in template ( Function Based Views )
I am Building a BlogApp and I implement a feature to count the views of Post. BUT views are not showing in post page in Browser. What i am trying to do I am trying to count the number of views which post will got whenever the user visits. The Problem Post views are not showing in post page in browser. What have i tried 1). I also tried models.IntegerField BUT that didn't worked for me , because whenever user refresh the page then it increase one view everytime for single user. 2). I followed some tutorials BUT the all of them were on Class Based Views and I am using Function Based Views. 3). Then i thought of IP address BUT that also didn't worked for me because it wasn't working for my server. Then i think of a ManyToManyField in views variable. BUT it also working for me, I don't know where is the problem. views.py def detail_view(request,pk): data = get_object_or_404(BlogPost,pk=pk) queryset = BlogPost.objects.order_by('viewers') context = {'queryset':queryset,'data':data} return render(request, 'mains/show_more.html', context ) models.py class BloPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) date_added = models viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False) show_more.html 1). This is showing auth.User.None {{ data.viewers }} 2). This is … -
Django admin: every app with different custom base_site.html
Hi I have been trying to customize my admin page and I have some application specific admin pages that require custom javascript and css. I would like to have different base_site.html within the template/admin/ of each app including the required javascript and css. The thing is that only the changes of the base_site.html of the first registered app (inside the settings.py file) are shown. Is my approach of customizing base_site.html for each app correct? if yes, how can I get it to work? How to include css and js only in some admin pages? Thank you. -app1 -templates -admin -base_site.html -app2 -templates -admin -base_site.html -app3 -templates -admin -base_site.html -manage.py -
Error appeared when I want to add a permission to a user or join it to a group in django
In django admin panel... after creating a user I can't give that a permission or specify a group for that actually after setting the intended permission or group clicking on save button will cause this error syntax error at or near "ON" LINE 1: ...ser_groups" ("user_id", "group_id") VALUES (2, 1) ON CONFLIC... -
I got Error while not authenticate users try to see the content
DoesNotExist at / Account matching query does not exist. I got error while the not authenticate user try to see the video I need to let the not authenticate user can to see the content videos but absolutely can't to post any videos The model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to='post-videos') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) allow_comments = models.BooleanField(default=False) is_public = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(null=True, blank=True) The form class Video_form(forms.ModelForm): class Meta: model = Video fields = ('title', 'description', 'video') The views def home_screen_view(request, *args, **kwargs): all_videos = Video.objects.all() V_form = Video_form() video_added = False account = Account.objects.get(username=request.user) if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) instance.author = account instance.save() V_form = Video_form() video_added = True contex = { 'all_videos': all_videos, 'account': account, 'V_form': V_form, 'video_added': video_added } return render(request, "personal/home.html", contex) The Html template {% if request.user.is_authenticated %} <div class="container"> <div class="mt-5"> <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{V_form}} <button class="btn btn-success btn-lg" name="submit_v_form">Upload</button> </form> </div> {% endif %} <hr> {% for x in all_videos %} <h3 class="text-center mt-2 mb-2">{{x.title}}</h3> <video class="embed-responsive embed-responsive-16by9" controls="controls" > <source src="{{x.video.url}}" type="video/mp4" /> </video> {% … -
How to connect the css?
How can I plug css into html by importing css from the main folder? I have a network project with 3 app. network --chat --news --static/style.css ... My code: {% load static %} <link rel="stylesheet" href="{% style.css' %}"> It works if I create a static folder in some app, but I want to put it in the main network folder and then it stops working. -
How to use lookup_field along with FilterSet in Django Rest Framework?
I am working on developing an API for a project and the API must list all the courses offered in a particular college and retrieve a particular course using lookup_field as course_slug. It also must support filtering courses in the list page based on some other parameters which I am implementing it with the help of Django FilterSet along with filterset_class (filterset_class) . The problem is, once I filter the courses based on the requirements, the query params is included in the URL as well. Now, I am not able do the retrieve operation on it, as the URL cannot recognize the lookup_field added and mistakes it to a pattern in query params. ViewSet.py class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = CourseSerializer lookup_field = 'slug' filter_backends = (SearchFilter, DjangoFilterBackend,) search_fields = ['name'] filterset_class = CourseFilter def get_queryset(self): queryset = Course.objects.all() return queryset.filter(college_courses__college__slug=self.kwargs['college_slug']) def get_object(self): obj = super().get_object() if self.action == 'retrieve': obj.additional = CollegeCourse.objects.filter(course=obj, college__slug=self.kwargs['college_slug']).first() return obj def get_serializer_class(self): if self.action == 'retrieve': return CollegeCourseSerializer return super().get_serializer_class() filters.py class CourseFilter(filters.FilterSet): name = filters.MultipleChoiceFilter(field_name='college_courses__stream__name', choices=choices("STREAM_NAME_CHOICES")) category = filters.MultipleChoiceFilter(field_name='college_courses__stream__category', choices=choices("STREAM_CATEGORY_CHOICES")) program = filters.MultipleChoiceFilter(field_name='college_courses__stream__program', choices=choices("STREAM_PROGRAM_CHOICES")) class Meta: model = Course fields = [ 'name', 'category', 'program' ] urls.py router = routers.DefaultRouter() router.register(r'courses', CollegeCourseViewSet, basename='college_course') urlpatterns = … -
I Try to add Next and Previous Button in my Django Project
This is my Url "href="course?lecture={{video.serial_number}}" this should go like this example: www.demo. com/course?lecture=1 www.demo. com/course?lecture=2 www.demo. com/course?lecture=3 www.demo. com/course??lecture=4 ( last video ) I Used Below method (IMAGE) it works with previous button but next button not working in last video lecture, like if i have 4 videos (?lecture=4 ) but it continuous to 5th video ( ?lecture=5 ) when i click next button at the end. I used this code -
How to reference a Form's ModelMutiplechoiceField to a foreignKey in Django?
Consider my model like this: class Major(models.Model): major_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.major_name class Minor(models.Model): major_name = models.ForeignKey(Major, on_delete=models.CASCADE) minor_name = models.CharField(max_length=100, default='', null=False) is_active = models.BooleanField(default=True, null=False) def __str__(self): return self.minor_name Then with this form: class PreferredMinorForm(forms.Form): preferred_minor= forms.ModelMultipleChoiceField( queryset=Minor.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) I can loop through minor to be displayed on template. But how do I loop through minor that is under major? Currently, my code looks like this: view: minor = PreferredMinorForm() context['minor_list'] = minor context['major_list'] = Major.objects.filter(is_active=True).order_by('id') template: {% for major in major_list %} {{major}} {% for minor in minor_list %} # How to if statement here? {% endfor %} {% endfor %} If I test minor, I got this: <li><label for="id_minor_45"><input type="checkbox" name="minor" value="46" id="id_minor_45">DATA</label></li> -
Not making Django project in PyCharm
I have a problem when i try to create a new Django project in PyCharm. enter image description here -
django-channels add user to multiple groups on connect
So I have my models like this. class Box(models.Model): objects = models.Manager() name = models.CharField(max_length=100) owner = models.ForeignKey('users.User', on_delete=models.CASCADE) REQUIRED_FIELDS = [name, owner, icon] class User(AbstractBaseUser): objects = BaseUserManager() email = models.EmailField(unique=True) username = models.CharField(max_length=32, validators=[MinLengthValidator(2)], unique=True) avatar = models.ImageField(upload_to='avatars/', default='avatars/default.jpg') REQUIRED_FIELDS = [username, email] class Member(models.Model): objects = models.Manager() box = models.ForeignKey('uploads.Box', on_delete=models.CASCADE, editable=False) user = models.ForeignKey('users.User', on_delete=models.CASCADE, editable=False) roles = models.ManyToManyField('roles.Role', through='roles.MemberRole') invite = models.ForeignKey('users.Invite', null=True, blank=True, on_delete=models.CASCADE) REQUIRED_FIELDS = [box, user] I have a websockets framework with routing like this. websocket_urlpatterns = [ path('gateway/', GatewayEventsConsumer.as_asgi()), ] class GatewayEventsConsumer(AsyncWebsocketConsumer): """ An ASGI consumer for gateway event sending. Any authenticated user can connect to this consumer. Users receive personalized events based on the permissions they have. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): user = self.scope['user'] if user.is_anonymous: # close the connection if the # user isn't authenticated yet await self.close() for member in user.member_set.all(): # put user into groups according to the boxes # they are a part of. Additional groups would be # added mid-way if the user joins or creates # a box during the lifetime of this connection await self.channel_layer.group_add(member.box.id, self.channel_name) await self.channel_layer.group_add(self.scope['user'].id, self.channel_name) await self.accept() async def disconnect(self, close_code): for member … -
How to embed another html in a division of webpage in python/django?
Suppose one section of a website is all about blogs. The list of blogs are on left division, with titles, posting dates, authors, perhaps a filter as well. The right division is another html page, generated by simple markdown editor, uploaded to a specific folder, perhaps with pictures as well. Clicking on one title on the left would call and display the corresponding html on the right. The left and right has separate scroll bars. Can Django or another Python website framework fulfill the description in these two sentences? Thanks in advance. -
django authenticate Nonetype, admin wrong password
I'm currently building a django application but when I create a superuser and try to login to the admin I keep receiving the Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. warning, aditionally, trying to run authenticate in the shell returns Nonetype checking for is_staff and is_superuser values. This is my user model: class users_user(AbstractUser): pk_iduser = models.AutoField(db_column='PK_IdUsers', primary_key=True) # Field name made lowercase. name = models.CharField(max_length=132, verbose_name='password') surname = models.CharField(max_length=132, verbose_name='password') email = models.CharField(max_length=132, verbose_name='password') password = models.CharField(max_length=132, verbose_name='password') is_active = models.BooleanField(db_column='is_active',default=False) is_reset_password = models.BooleanField(db_column='is_resset_password',default=False) date_reset_password = models.DateTimeField(db_column='date_resset_password',blank=True, null=True) phone = models.CharField(max_length=50,db_column='phone',blank=True, null=True) country = models.IntegerField(db_column='Country',blank=True, null=True) city = models.CharField(max_length=100,db_column='city',blank=True, null=True) address = models.CharField(max_length=255,db_column='address',blank=True, null=True) is_active = models.BooleanField(db_column='is_active',default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) class Meta: db_table = 'users_user' verbose_name_plural = "users" def __str__(self): return '{}'.format(self.pk_iduser) In my UserManager class tried both ways suspecting password was in text format: user.set_password(password) and user.set_password("password") The class: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, … -
Best way to monitor number of views on a blog post in Django
I am working on a blog webapp and I would like to monitor the number of views a post has. I have decided to use the post detail view to count. And to keep the counter from incrementing for a particular user, I am going to allow only logged users to count and a user can count only once. this is my post model class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField(max_length=3000, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) viewers = models.TextField(default="", null=True, blank=True) numViews = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I am basically using a field 'viewers' to track users already counted and 'numviews' as the counter. My views.py function class PostDetailView(DetailView): model = Post def get(self, request, *args, **kwargs): # increment post views whenever request is made postObject = self.get_object() user = request.user if postObject.viewers == None: postObject.viewers = "" postObject.save() if user.is_authenticated and user.username not in postObject.viewers: # increment postObject.numViews += 1 postObject.save() # add username to viewers list postObject.viewers+=user.username postObject.save() return super().get(request, *args, **kwargs) In the views function, I am checking if the username is already appended to the viewers string, else append it and increment the counter. … -
Error while not authenticate users try to see the content
DoesNotExist at / Account matching query does not exist. I got error while the not authenticate user try to see the video I need to let the not authenticate user can to see the content videos but absolutely can't to post any videos The model class Video(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to='post-videos') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) allow_comments = models.BooleanField(default=False) is_public = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(null=True, blank=True) The form class Video_form(forms.ModelForm): class Meta: model = Video fields = ('title', 'description', 'video') The views def home_screen_view(request, *args, **kwargs): all_videos = Video.objects.all() V_form = Video_form() video_added = False account = Account.objects.get(username=request.user) if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) instance.author = account instance.save() V_form = Video_form() video_added = True contex = { 'all_videos': all_videos, 'account': account, 'V_form': V_form, 'video_added': video_added } return render(request, "personal/home.html", contex) The Html template {% if request.user.is_authenticated %} <div class="container"> <div class="mt-5"> <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{V_form}} <button class="btn btn-success btn-lg" name="submit_v_form">Upload</button> </form> </div> {% endif %} <hr> {% for x in all_videos %} <h3 class="text-center mt-2 mb-2">{{x.title}}</h3> <video class="embed-responsive embed-responsive-16by9" controls="controls" > <source src="{{x.video.url}}" type="video/mp4" /> </video> {% … -
Saving to database from a dynamically generated checkbox in django
I have a dynamically generated checkboxes based from a model. I want to save them to a different model. This is a ForeingKey Relationship. The basic code is as follows: class Color(models.Model): color_name = models.CharField(...) class MyFavoriteColor(models.Model): color_name = models.ForeignKey(Color, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) I generated my colors to my template with this view: context['colors'] = Color.objects.all() template: {%for color in colors%} <input type="checkbox" id="id_{{color}} " name="{{color}} " value="{{color}} "> {%endfor%} When I save, I want to create a new data per color for the person. -
Django-Cookie-Consent walkthrough or tutorial
I am looking at launching my very first Django app, and would like to implement cookie consent. I am still fairly new to django and programming and I have read through the docs but as this is my first time with a web app and with really dealing with cookies, I am having trouble understanding exactly what to do. I would just like to find out if anyone knows of a walkthrough or a tutorial implementing django cookie consent? I have it installed but am unsure how exactly to "make it work" how if a user declines a certain cookie I would actually "listen" or implement to their choice? As well as how to set up cookie groups and cookies themselves. While the documentation seems clear for an "advanced beginner" it does seem a little hard to know exactly what to do and how to go about it. Any advice would be great. -
CSRF in local development
I have an app where the frontend is using React and the backend is using django-rest-framework. The backend enforces CSRF which is needed, and I think everything will work fine in production because the backend and the frontend will share the same origin (https://mydomain.awesome). But for local development I have a problem, my frontend is running on localhost:3000 and my backend is running on localhost:8000, and this means they are on different origins and my backend is not sending CSRF token to my frontend. What do people do in this case? How can I have "same origin" in the local development environment? -
Serving a Reportlab generated document working on Windows but not on Ubuntu
I am creating a Django application. Part of the application is that a user provides some inputs for a pdf document to be created, then they can download it. This pdf is created with Reportlab. When I run the Django server on a Windows machine, the pdf is able to be downloaded. When I run it on Ubuntu, it says the following error. UnicodeDecodeError. 'utf-8' codec can't decode byte 0x93 in position 10: invalid start byte Further to the error message, the part the can not be decoded is the part in bold below: %PDF-1.4 %���� ReportLab Generated PDF document http://www.reportlab.com My code for the download function is @login_required def downloadFile(request,filename): # check to see if filename exists theOrder = Orders.objects.filter(baseFilename=filename) if len(theOrder) != 1: print("Does not exists") return render(request, "order_form/order_form_home.html") if not request.user.is_staff: # check if this user created the file print("the order 0 is ",theOrder[0].userCreated) print("request user is ",request.user) if theOrder[0].userCreated != request.user: print("no permission exists") return render(request, "order_form/order_form_home.html") #path absolute pathAbs = os.path.join(settings.MEDIA_PDF,(filename +".pdf")) theFile = filename + ".pdf" with open(pathAbs) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename={0}'.format(theFile) return response Also, it should be noted that I am using Ubuntu 20 desktop on a … -
You cannot .filter() on a DjangoCassandraQuerySet which has been ordered using python
When I want to delete a bulk of data by checked all from Django admin, then go, then this error has happened. My cassandra model: import uuid from cassandra.cqlengine import columns from django.utils import timezone from django_cassandra_engine.models import DjangoCassandraModel class ETrafficPayment(DjangoCassandraModel): id = columns.UUID(primary_key=True, default=uuid.uuid4) requested_data = columns.Text(default="") response = columns.Text(default="") created_at = columns.DateTime(default=timezone.now) updated_at = columns.DateTime(default=timezone.now) -
TypeError: create() got multiple values for keyword argument 'name'
I am currently having trouble executing nesting with Django rest framework, I think the problem is in my loop but cant't get that I have gone through most of the answers but no help. Any help would be appreciated. Thanks in advance!! MODEL class Category(models.Model): name = models.CharField(max_length=36, unique=True) class sub_category(models.Model): parentCategory = models.ForeignKey(Category, blank=True, null=True, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=36, unique=True) class childern(models.Model): parentCategory = models.ForeignKey(sub_category, blank=True, null=True, related_name='subcategories', on_delete=models.CASCADE) name = models.CharField(max_length=36, unique=True) Searlizers class ChildernSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = childern fields = ['name', 'id',] class SubCategorySerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) subcategories = ChildernSerializer(many=True) class Meta: model = sub_category fields = ['name', 'subcategories', 'id',] def create(self, validated_data): sub_cat = validated_data.pop('subcategories') name = Category.objects.create(**validated_data) for cat in sub_cat: sub_category.objects.create(**cat, name=name) return name class CategorySerializer(serializers.ModelSerializer): subcategories = SubCategorySerializer(many=True) class Meta: model = Category fields = [ 'name', 'subcategories', ] def create(self, validated_data): sub_cat = validated_data.pop('subcategories') name = Category.objects.create(**validated_data) for cat in sub_cat: sub_category.objects.create(**cat, name=name) return name -
Django rest framework browsable api root url
I love DRF but I still find its documentation really frustrating, for real, a lot of advanced tips and examples are there but I still always dive into toughness and frustration when I'm looking for the most basic stuff of any topic of the amazing framework. In this case, this resource looks really cool! But they don't even start by how to make it work (or what could not be properly configured if it isn't working as in my case). Could someone tell me what's the holy api root URL or how to include/configure it? Because I don't see it in my URLs and so far I didn't find anything in the official docs. I also followed the quickstart tutorial. This is what I have: My main urls.py: api_urls = [ path('rest_framework/', include('rest_framework.urls', namespace='rest_framework')), path('', include('project.posts.urls')), path('', include('project.users.urls')), ] urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(api_urls)), ] users.urls: router = SimpleRouter() router.register(r'users', UserViewSet, basename='users') urlpatterns = [ path('', include(router.urls)), ] posts.urls: router = SimpleRouter() router.register(r'posts', PostViewSet, basename='posts') urlpatterns = [ path('', include(router.urls)), ] I can log in into the DRF panel but then I get a redirection error. Also I can see the pages if I manually go to a …