Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django token authentication test
I'm working on very simple API for creation and authentication user with a token. If I run a server and user is created manually then I can get a token, so it probably works as expected. But my unittest for creating token for user actually do not pass. My question is - why it actually do not pass? Probably I have missed something what is done by django underhood. Appreciate any feedback. Below you can see my serializer, view, model and a failing test. models class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user.""" if not email: raise ValueError('User must an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """Creates and saves a new superuser.""" user = self.create_user(email, password) user.is_admin = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model with email instead of username.""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' @property def is_staff(self): """Is the user a member staff?""" return self.is_admin serializer class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, … -
How to pass parameters from the form input box with action="get"?
I am trying to implement a form that sends a GET request but I want to pass arguments obtained by extracting data from the textfield. Here is an example: urls.py: urlpatterns = [ path('my-awesome-url/<str:foo>', MyAwesomeView.as_view(), name='my_awesome_url'), ] views.py: class ContactTracingView(View): def get(self, request, *args, **kwargs): foo = kwargs['foo'] context = {} # do some logic here return render(request, 'my_awesome_template.html', context) my_awesome_template.html: {% extends 'base.html' %} {% block content %} <form method="get" action="{% url 'my_awesome_url' foo %}"> <input type="text" name="foo"> <button type="submit" value="Submit">Submit</button> </form> {% endblock %} However, this code is not doing the job. I am receiving this error: NoReverseMatch Reverse for 'my_awesome_url' with no arguments not found. 1 pattern(s) tried: ['my\-awesome\-url\/(?P[^/]+)$'] I don't want to use POST, because I want the user to be able to bookmark the page. Also, when I tried to hardcode the url without writing parameters, csrf token was passed into the url, too. I want the url to be: my-awesome-website.tld/my-awesome-url/foo -
SyntaxError: Unexpected token < in JSON at position 0 while getting object
I am writing a SPA using DRF and Vue. I can get the list view class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = "slug" def perform_create(self, serializer): serializer.save(user=self.request.user) and my script export default { name: "Home", data() { return { articles:[] } }, methods: { getArticles() { let endpoint = 'api/articles/'; apiService(endpoint) .then(data=>{ this.articles.push(...data.results) }); } }, created() { this.getArticles(); console.log(this.articles) } }; when I try to route-link my articles : <router-link :to="{ name: 'article', params: { slug: article.slug }}" >{{article.content}} </router-link> I get error although I can see the object in the console. SyntaxError: Unexpected token < in JSON at position 0 vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'content' of undefined" this is my article.vue <template> <div class="single-question mt-2"> <div class="container"> {{article.content}} </div> </div> </template> <script> import { apiService } from "../common/api.service.js"; export default { name: "Article", props: { slug: { type:String, required: true } }, data(){ return { article: {} } }, methods: { getArticleData() { let endpoint = `api/articles/${this.slug}/`; apiService(endpoint) .then(data=> { this.article = data; }) } }, created() { this.getArticleData(); } }; </script> Can you help me to fix the error. Thanks -
Filter Django model on reverse relationship list
I have two Django models as follows: class Event(models.Model): name = models.CharField() class EventPerson(models.Model): event = models.ForeignKey('Event',on_delete='CASCADE',related_name='event_persons') person_name = models.CharField() If an Event exists in the database, it will have exactly two EventPerson objects that are related to it. What I want to do is to determine if there exists an Event with a given name AND that have a given set of two people (EventPersons) in that event. Is this possible to do in a single Django query? I know I could write python code like this to check, but I'm hoping for something more efficient: def event_exists(eventname,person1name,person2name): foundit=False for evt in Event.objects.filter(name=eventname): evtperson_names = [obj.person_name in evt.event_persons.all()] if len(evtperson_names) == 2 and person1name in evtperson_names and person2name in evtperson_names: foundit=True break return foundit Or would it be better to refactor the models so that Event has person1name and person2name as its own fields like this: class Event(models.Model): name = models.CharField() person1name = models.CharField() person2name = models.CharField() The problem with this is that there is no natural ordering for person1 and person2, ie if the persons are "Bob" and "Sally" then we could have person1name="Bob" and person2name="Sally" or we could have person1name="Sally" and person2name="Bob". Suggestions? -
Problems with session set_expiry method
I created a session for a view that some action, but i want to reset this session every week, i found set_expiry for that and tried to add that, but after working it reset all sessions in the website and i am doing logout. How to do that only for my action and not to touch all sessions in the website views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) join_key = f"joined_{room.invite_url}" if request.session.get(join_key, False): join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session[join_key] = True request.session.set_expiry(10000) join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) -
Django CreateView not saving item to model
My Django CreateView is not working. There are no bugs, but a new item is not being created when I submit the form. For example, when I go to the url and submit the form, a new item is not being added. Could you please help? You can also check out my GitHub repo for this project. Code for new_pattern.html {% extends 'patterns/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Perler Pattern</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Pattern</button> </div> </form> </div> {% endblock %} Code for views.py from django.views.generic import (``` ListView, CreateView, ) from django.contrib.auth.mixins import LoginRequiredMixin from .models import Pattern class PatternListView(ListView): model = Pattern template_name = 'patterns/home.html' context_object_name = 'patterns' ordering = ['title'] class PatternCreateView(CreateView): model = Pattern fields = ['title', 'image'] template_name = 'patterns/new_pattern.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Code for settings.py from . import views from django.urls import path urlpatterns = [ path('', views.PatternListView.as_view(), name='beadz-home'), path('new/', views.PatternCreateView.as_view(), name='new-pattern'), ] Code for models.py from django.db import models from django.contrib.auth.models import User class Pattern(models.Model): title = models.CharField(max_length=45) image = models.ImageField() author = models.ForeignKey(User, on_delete=models.CASCADE) def … -
does not appear to have any patterns in it. or circular import
recently i started to studying django but there is a problem into my code and i cant find what exactly could be a decent fix to this problem so i thought i would be good to ask. ... from django.urls import path from . import views ulrpatterns = [ path('' , views.index) ] ... well this is my code for urls.py into the articles directory. ... from django.contrib import admin from django.urls import path , include from home import views as home_views urlpatterns = [ path("" ,home_views.index ), path("about", home_views.about), path("Contact" ,home_views.contact ), path('admin/', admin.site.urls), path('articles/' , include('articles.urls')), ] ... this one is my main urls.py from what im seeing i called articles.urls but when im running my server it keeps givin me this error raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
IBM Cloud db2 django migrations python manage.py migrate
Created my first ibm db2 database on ibm cloud and connected it with django. With following settings: 'default':{ 'ENGINE' : 'ibm_db_django', 'NAME' : 'BLUDB', 'USER' : 'xxxxxxxxxxxxxxxx', 'PASSWORD' : 'xxxxxxxxxxxxxxxx', 'HOST' : 'dashdb-xxxxxxx-sbox-xxxxxxxxxx.services.eu-gb.bluemix.net', 'PORT' : '50000', 'PCONNECT' : True, } Connection works very well because I can run migrations for custom django app which I added. Even for session and content types. Problems arises due while running migrations for auth and admin. I get following error message: Exception('SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0551N The statement failed because the authorization ID does not have the required authorization or privilege to perform the operation. Authorization ID: "XXXXXXXX". Operation: "SELECT". Object: "SYSIBMADM.ADMINTABINFO". SQLSTATE=42501 SQLCODE=-551' I understand that I dont have privileges to perform select operation on SYSIBMADM.ADMINTABINFO. My question is how can I give myself (admin account) privileges so that my python manage.py migrate does'nt throw an error. Or there is something wrong I am doing in django app itself. (INITIAL MIGRATIONS) -
sending email from django app doesnt work from server
I have an app that sends out an email when an object is create, this is the code for sending email: send_mail("New entryis added", "Hi a new entry is added", "myemail@gmail.com", [c.email for c in CustomUser.objects.all()], fail_silently=False) and this is my setting: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True I also made sure that my "Less secure app access" is on in google security setting. So with all thses I am able to send email with no issue in local server. However when I push the code to digital ocean droplet linux server, it throws some errors: SMTPAuthenticationError at /a/b/c/add/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 VVGrAjSoYzu_W9fGpWsq5B3qMs04qWLzeqnxkFdrMaeVJumRRljQzXEyYpA9xt1MSYaii\n5.7.14 iyVCj2qaXbQzY5Tvc3mux9qViJSKE5yOozpCzao_qU0FhjYGX8IZ1xgd9PUep41I>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 g9sm2079574pgj.89 - gsmtp') Exception Type: SMTPAuthenticationError I apreciate if someone can shed some light on what is the issue, Thanks, -
How to create asynchronous result submission based on table data using django-tables2
I am currently using django-tables2 to display some results to users. The results is coming from a RDF graph, so the results and number of columns may vary. I wrote the following code to deal with variable length of table columns: def createData(queryResults): if not queryResults: return (DummyTable,[]) else: myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="secReqViews/radionbuttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) return QueryTable2, mylist Not to dwell on the algorithm, but you can see that I dynamically created the table columns using myTableCol={} and dynamically created class QueryTable2. I added a column call "Actions", which is my focus for this post. I would like to use this column to get information from the users asynchronously. So, for the results in the table, the user can select the "Yes" or "No" radio button to say whether the a row of results is correct or not. By selecting the "Yes" or "No" radio button, the information from the row will be sent and then save the row that is correct or not. Can this be done using Django-tables2? … -
Validation in case of multiple objects serializer
My data input is in the form of list of 'n' number of dicts "contact_person":[ { "contactperson_salutation[0]":"sddd", "contactperson_first_name[0]":"santoorr", "contactperson_last_name[0]":"", "contactperson_email[0]":"gfgh", "contactperson_mobile_number[0]":"", "contactperson_work_phone_number[0]":"jio" }, { "contactperson_salutation[1]":"dfsf", "contactperson_first_name[1]":"lux", "contactperson_last_name[1]":"", "contactperson_email[1]":"", "contactperson_mobile_number[1]":"", "contactperson_work_phone_number[1]":"9048" }, .............] My model is like this: class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) contactperson_salutation = models.CharField(max_length=4, choices=SALUTATIONS) contactperson_first_name = models.CharField(max_length=128) contactperson_last_name = models.CharField(max_length=128, blank=True) contactperson_email = models.EmailField(blank=True, null=True) contactperson_mobile_number = models.CharField(max_length=20, blank=True) contactperson_work_phone_number = models.CharField(max_length=20, blank=True) How to write serializer when the fields names are changing for every dict in the input list.. And if errors occurs the Error Response should be in this format: [ { "contactperson_email[0]":"Invalid Email", "contactperson_mobile_number[0]":"Invalid mobile phone", "contactperson_work_phone_number[0]":"Invalid workphone number" }, { "contactperson_mobile_number[1]":"Invalid mobile phone", "contactperson_work_phone_number[1]":"Invalid workphone number" } ] -
declaring a global timer variable django
Good day, I have a django project up and running which has a users profile feature, users that register complete their profile with their personal information and other people on the site can view their profile. i have a field in my model for each user called profileVisits which counts each time a users profile is visited in the views.py. profileVisits = models.IntegerField(blank=True, null=True, default= 0) I want to use the profileVisits number to display the data in some kind of line graph which creates a average profileVisits graph. What i had in mind to approach this is to use a queue in python which has a max size of 5 integers q = Queue(maxsize = 5) this is because the data in q will be used in the data field for the chart.js. now the problem im facing is the use of a global variable in django. I want to add the data to q once a day with the number of profile visits and remove the oldest element in it, FIFO sequence, does anyone know how to initialize such a global timer variable in django or any better way to accomplish this -
how to do Django extract zip file after uploading
I am trying to upload a zip file and extract it into the static folder, bellow codeshare working file for uploading the zip file, how to extract the zip file to the static folder after uploading class Article(TimeStampModel): article_type = models.CharField( max_length=256, choices=ArticleTypeChoice.choices(), default=ArticleTypeChoice.ARTICLE.name) language = models.CharField(max_length=256, choices=LanguageChoice.choices()) title = models.CharField(max_length=1020) description = models.TextField(null=False, blank=True) article = models.FileField(null=False, blank=True, upload_to='static/') ``` -
DRF Custom Permission is not firing
I wrote a custom permission class for a drf project to protect my view: views.py class Employee(APIView): permission_classes = [BelongsToClient] serializer_class = EmployeeSerializer def get(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) serializer = EmployeeSerializer(employee, many=False) return Response(serializer.data) def delete(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) employee.Employees_deleted = True employee.save() return Response(status=status.HTTP_200_OK) My permission class: permission.py from rest_framework import permissions class BelongsToClient(permissions.BasePermission): message= "You are only authorized to view objects of your client" """ Object-level permission to only see objects of the authenticated users client """ def has_object_permission(self, request, view, obj): if obj.Mandant == request.user.Mandant: return True else: return False Unfortunatly this permission class isn't blocking my view even when it should. I dont know why. Did I miss something? -
how to compress django output with your own script?
I am new to Django and I know that it comes with many libraries that can compress the html, css and js files but i want to do this with my own script I have a python script which can compress these files and it works perfectly i want to use this script to compress my Django project output. I am using python 3.7.3 and django 3.0.5 -
Django: If I start a table, and then have a {% block %}{% endblock %} and close the table after, does it break the table?
I am making an html email template, and the header and footer for various email templates are on a single page that is included on each email. They are set up in tables, and the header and footer are contained in a single table. Because I am providing the body of the email in a separate file, it has to be broken up with a block. Apple mail renders the tfoot wrong, as if the footer is separate from the rest of the table. Is this because it is broken up by the block tags? How can I make it work, if so? This is the barebones setup for reference. <body> <table> <th> ---- </th> {% block body %} {% endblock %} <tfoot> <tr> <td> ----- </td> </tr> </tfoot> </table> </body> -
Operational Error: table "users_userscore" already exists
For my web app, I have two apps, one is morse_logs, the main app; second, is the users app, which mainly handles the users details and authentication, etc. At the moment in my users app, I have a UserProfile model, which only have one variable which is description, and now I am struggling to add one more variable score to user, so that each user will have one score variable to store their score, and the user's score will be updated after certain actions in morse_logs game1.html and morse_logs/views.py (the main app). I am really not familiar with modelling and create table, columns these sort of stuff... And when I do migrations, it gives me error like Operaional Error: table "users_userscore" already exists... I did try deleting the migrations py files... all my code are on github: https://github.com/phl6/morse_log So, my question is how can I update my model so I can have a score variable/field for each user which this variable can be updated in the morse_logs(main app). users/model.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.CharField(max_length=100, … -
Session Authentiction not working with django and vuejs
I am getting the csrf token and i am using axios to send a get request to the rest api. when i set the CSRF token and try to get the data, i get a 403 forbidden error. axios.get("my-api-url",{ header:{ 'X-CSRFTOKEN': csrftoken } }) .then(res -> console.log(res)) .catch(error => console.log(error)) -
KeyError 'OPTIONS' when trying to run Django Heroku project locally
I'm currently trying to run my Django Heroku project locally to develop after making local changes. Upon issuing the command heroku local I get the error seen below. I believe that I'm missing some local environment configuration, as everything works as expected on my production deployment. Below the error message is my settings.py file. 12:05:35 PM web.1 | [2020-04-10 12:05:35 -0500] [3553] [ERROR] Exception in worker process 12:05:35 PM web.1 | Traceback (most recent call last): 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 12:05:35 PM web.1 | worker.init_process() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 12:05:35 PM web.1 | self.load_wsgi() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 12:05:35 PM web.1 | self.wsgi = self.app.wsgi() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 12:05:35 PM web.1 | self.callable = self.load() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 12:05:35 PM web.1 | return self.load_wsgiapp() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 12:05:35 PM web.1 | return util.import_app(self.app_uri) 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/util.py", line 358, in import_app 12:05:35 PM web.1 | mod = importlib.import_module(module) 12:05:35 PM web.1 | File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module 12:05:35 … -
Logical error in Model & View files - Django Rest Framework
I am creating a Blog app backend using Django Rest Framwork. I use Djoser for user management. Authenticated users can do CRUD operation in their blog post and any logged in user can like and comment the posts. I cannot establish relationship between Posts and comments.Please help MODELS.PY from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): # codes here for user creation,removed codes for simplicity of stackoverflow readers class OwnedModel(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True) class Meta: abstract = True class Post(OwnedModel): name = models.CharField(max_length=100,null=True) likes = models.ManyToManyField(User) class Comment(models.Model): body = models.TextField() friend = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.ForeignKey(User, on_delete=models.CASCADE) VIEWS.PY from rest_framework import viewsets,permissions from . import models,serializers from .permissions import IsOwner from rest_framework.permissions import IsAuthenticated class PostViewset(viewsets.ModelViewSet): queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = [IsOwner] class CommentViewset(viewsets.ModelViewSet): queryset = models.Comment.objects.all() serializer_class = serializers.CommentSerializers permission_classes = [IsAuthenticatedOrReadOnly] ** SERIALISERS.PY** from rest_framework import serializers from .models import Post,User,Comment from djoser.serializers import UserCreateSerializer,UserSerializer class PostSerializer(serializers.ModelSerializer): owner = serializers.HiddenField( default=serializers.CurrentUserDefault()) class Meta: model = Post fields = ('id', 'name',"owner",'likes') class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields=('id','email','username','phone','first_name','last_name','password',) class CommentSerializers(serializers.ModelSerializer): class Meta: model = Comment fields=('__all__') ** PERMISSIONS.PY ** from rest_framework import permissions class IsOwner(permissions.BasePermission): message … -
django_tables2: Pagination by Alphabet
I am using django_tables2 to display some data - however. I would like the pagination to occur by letters of the alphabet. I.e. page 1 is all entries that start with A, page 2 is all entries that start with B. etc. I though this would be relatively straightforward to do - but I can't find any examples of this anywhere! Is this not possible? Perhaps I have been using the wrong search terms. Currently my inputs are quite simple - although just pointing me to some materials would be just as helpful as telling me how to change the code. tables.py: import django_tables2 as tables from .models import Person, Languages from django_tables2.utils import A # alias for Accessor class LanguagesTable(tables.Table): name = tables.LinkColumn("language_detail", args=[A("glottocode")]) class Meta: model = Languages template_name = "django_tables2/bootstrap.html" fields = ("name", ) urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$', views.home, name='home'), path('', views.home, name='home'), path('about/', views.about, name='about'), path('languages/', views.LanguagesTable.as_view(), name='languages'), #path('languages/', views.LanguagesTable, name='languages'), path('languages/<str:pk>/', views.language_detail, name='language_detail'), path('phylogeny/', views.phylogeny, name='phylogeny'), #path("people/", views.PersonListView.as_view()), ] models.py class Languages(models.Model): id = models.TextField(db_column='ID', blank=True, null=False, primary_key=True) # Field name made lowercase. name = models.TextField(db_column='Name', blank=True, null=True) # Field name made … -
Video element in HTML5 won't let me change the time?
I'm using Django as a back end for a website I'm making. I want to load the page and the page start on a variable time using the currentTime property. I've done this exact same thing using a static website and it worked, but as soon as I added django it stopped working. At first I though that maybe it was taking longer to load since the video has to be ready to play in order set the currentTime, but when I did that the video stopped being able to played all together. Another thing that is behaving weird is that the video won't let me use the scrubber to change the time if I enable controls (I would guess this is related), but if I open the video in a new tab I can change the time just fine. -
Django3/DRF: Custom Queryset __init__() gets called multiple times. [ Chaining Querysets is applied ]
Greeting there ! i have built a custom queryset and i have noticed that its __init__() method gets called multiple times. let's take into consideration that i am also applyingQueryset Chaining models.py class Todo(...): ... objects = TodoQueryset.as_manager() manager.py from types import MethodType from django.conf import settings from django.db import models from django.utils import timezone from .settings import TODO_PRIORITY, TODO_STATUS, today_start_date class TodoQueryset(models.QuerySet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.priorities = TODO_PRIORITY print('\t weird 0') def starting_from_today(self): return self.filter(start_time__gte=today_start_date) def flag_as_missed(self): """ Flag Todos which end_time is lower than the current datetime as `TODO_MISSED` """ return self.filter(status=settings.TODO_PROGRESS, end_time__lt=timezone.now).update(status=settings.TODO_MISSED) def specific(self, priority=None, status=None): """ Fetch Todos with a specific priority: => {self.}request.user.todos.specific(priority='HIGH') Or call the specific method set for each priority: => {self.}request.user.todos.high() // NOT IMPLEMENTED YET """ assert priority is not None or status is not None, '.specific() must be called with either `status=...` or `priority=...`, got None instead.' return self.filter(priority=priority.upper()) serializers.py class TodoListSerializer(serializers.Serializer): todo_id = serializers.IntegerField(read_only=True) author_id = serializers.IntegerField(read_only=True) content = serializers.CharField(read_only=True) start_time = serializers.DateTimeField(read_only=True) end_time = serializers.DateTimeField(read_only=True) timestamp = serializers.DateTimeField(read_only=True) priority = serializers.CharField(read_only=True) status = serializers.CharField(read_only=True) path = serializers.SerializerMethodField() def get_path(self, instance): reverse_view = reverse(viewname="todo-detail", args=[instance.pk]) request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(reverse_view) return … -
How to save fomrset data
I am trying to display some data from my contact table and update it in the same time, but the data that I should passe to the formset is always empty so the formset is unbound that's mean invalid formset,the form data are displayed but they can't be edited, so any solution ?? views.py def see(request,slug): data = dict() ProductFormSet = modelformset_factory(Contact, fields=('Nom','post','Tel','email','contact_type','client'), extra=0) client = get_object_or_404(Client_Data, slug=slug) attig = request.POST or None formset = ProductFormSet(data=attig, queryset=Contact.objects.filter(client=client)) print(formset.is_bound) if request.method == 'POST' and formset.is_valid(): formset.save() else: for form in formset: form.fields['client'].queryset = Contact.objects.filter(client=client.id) context = {'form': formset} template_name = 'Client_Section/partial_client_contact.html' data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) forms.py class Contact_Form(forms.ModelForm): class Meta: model = Contact fields = ('Nom','post','Tel','email','contact_type','client') def __init__(self,*args, **kwargs): super(Contact_Form, self).__init__(*args, **kwargs) self.fields['client'].queryset = Client_Data.objects.all() parital_client_contact.html <form method="post" class="js-book-create-form"> {% csrf_token %} <div class="modal-body" > {% include 'Client_Section/partial_client_contact_form.html' %} </div> <br><br> <div style="pos"> <button style="float : right" type="submit" class="btn btn-primary ">Update Contacts</button> <button style="float : right" type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> parital_client_contact_form.html : {% block content %} {{form.as_p}} {% endblock %} -
python manage.py shell nothing happening
I'n new to django and I'm practicing through Django's Documentation on setting up my first project. All worked well until it asked to invoke the Python shell with the command python manage.py shell As a result, nothing really happens apart from showing the following text: Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Could someone please help? I tried finding an answer in very different sources but no one has really answered it. Thank you in advance.