Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to restrict access to django webpages unless accessed through a specific link?
I'm trying to build a multiple choice web application using django web framework. Is there any way to make a webpage accessible only through a specific link? -
Multiple (same) Many-To-One raltions in same model
I got a model Device. Each Device has 3 sensors which have there own color, status etc.. So I created a class Sensor where I need to store all the sensor data. Now I want in my Device model an attribute for each sensor that is connected with the Sensor model so I can retrieve the data. What's the best way to do this? Doing it like this?: in Device model for each sensor: light_sensor = models.ForeignKey( Sensor, on_delete=SET_NULL, blank=True, null=True, ) or in Sensor model: class Sensor(models.Model): device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="devicesensor" ) status = models.CharField(max_length=25, blank=False) color = models.CharField(max_length=25, blank=False) -
Django Token and Session auth
I was creating a Login For Custom User model is work fine with django , now i try to convert into Rest . It is creating the token but it doesnot return the token and Session is also blank (generation token but serializer.data is blank) enter image description here (Session db is empty) enter image description here django Serializer.py class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=False, allow_blank=True, write_only=True, label="Email " ) password = serializers.CharField( required=True, write_only=True, style={'input_type': 'password'} ) class Meta(object): model = User fields = ['email', 'password'] def validate(self, data): email = data.get('email', None) password = data.get('password', None) if not email: raise serializers.ValidationError("Please enter email to login.") user = User.objects.filter(Q(email=email)).exclude(email__iexact="").exclude(email__isnull=True).distinct() if user.exists(): user1 = authenticate(email=email, password=password) if user1 is not None: if user1.is_active: token, created = Token.objects.get_or_create(user=user1) data['token'] = token else: raise serializers.ValidationError("Account not active.") else: raise serializers.ValidationError("Invalid credentials.") else: raise serializers.ValidationError("This email is not valid.") return data Django view.py class UserLogin(views.APIView): permission_classes = (permissions.AllowAny, ) serializer_class = UserLoginSerializer def post(self, request): serializers = self.serializer_class(data=request.data) print(serializers) if serializers.is_valid(raise_exception=True): print("data", serializers.data) return Response(serializers.data, status=status.HTTP_200_OK) return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) -
(Django) Enviar formulário para outra tabela
Sou iniciante no Django e estou apanhando muito em uma coisa. Quero enviar um formulário que já foi preenchido para outra tabela. Preciso de alguma forma para selecionar qual tabela o formulário será enviado, e que ele "vá" com todos os dados que já foram inseridos posteriormente. Toda vez que um formulário novo é criado, ele vai pra página inicial:Formulários_Criados Percebam que a informação já foi inserida. Eu quero pegar a mesma informação, selecionar a Class do Model e enviar. pretendo fazer uma espécie de sistema de pendencias para enviar pra outras pessoas/setores. Meu Models.py from django.db import models from django.contrib.auth.models import User class Solicitacao(models.Model): nome = models.CharField(max_length=100) carteira = models.CharField(max_length=17) atendimento = models.CharField(max_length=100) descricao = models.TextField() data_da_solicitacao = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField(null=True, blank=True) telefone = models.CharField(max_length=100, null=True, blank=True) arquivo = models.FileField(upload_to='documentos/%y/%m/%d/', null=True, blank=True) def __str__(self): return str(self.id) class Sala1(models.Model): nome = models.CharField(max_length=100) carteira = models.CharField(max_length=17) atendimento = models.CharField(max_length=100) descricao = models.TextField() data_da_solicitacao = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) documentos = models.FileField(null=True, blank=True) email = models.EmailField(null=True, blank=True) telefone = models.CharField(max_length=100, null=True, blank=True) arquivo = models.FileField(upload_to='documentos/%y/%m/%d/', null=True, blank=True) def __str__(self): return str(self.id) class Sala2(models.Model): nome = models.CharField(max_length=100) carteira = models.CharField(max_length=17) atendimento … -
html download attribute not working in django
I want to download an image file from HTML inside my Django app this is my code in the template. {% for pic in pics %} <a href="{{ pic.image.url }}" download> <img src="{{ pic.image.url }}"> </a> {% endfor %} The images are rendered and everything else is working fine. When I click on the image, it opens in fullscreen instead of downloading. I am using chrome. What am I doing Wrong? -
How to use foreign key value to pre-populate another form field in Django
I have two models in for, one has member details and the other is the user model, what i want is to use the foreign key of member model in User model when creating a member account. In a form, when a member name with foreign key is selected, the email field should be pre-populated with value from the members table. I know ajax can do this asynchronous call to the database but how do i achieve this? thank you. User Model class User(AbstractBaseUser , PermissionsMixin): email = models.EmailField(max_length=255, unique=True, blank=True, null=True) username = models.CharField(max_length=30, unique=True) Role = models.CharField(max_length=250, choices=roles, blank=True, null=True) full_name = models.ForeignKey('Members', on_delete=models.SET_NULL, max_length=100, null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) Is_View_on_Web = models.CharField(max_length=20, default='Yes', choices=OPTIONS,null=True,blank=True) USERNAME_FIELD = 'username' REQUIRED_FILEDS = [] objects = UserManager() published = PublishedStatusManager() def __str__(self): return str(self.full_name) and Members Model class Members(models.Model): First_Name=models.CharField(max_length=100,null=True) Second_Name=models.CharField(max_length=100,null=True) Home_Cell=models.CharField(max_length=100, choices=cell,null=True) Residence=models.CharField(max_length=100,null=True) Telephone=models.CharField(max_length=100,null=True) Email=models.CharField(max_length=100,null=True, blank=True) def __str__(self): return str(self.First_Name )+ ' ' + str(self.Second_Name) here is my register.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom">Add New User to the System</legend> <div class="separator"></div> <div class="form-group"> {{ form|crispy}} </div> </fieldset> <div class="form-group"> <button class="btn btn-primary" type="submit"> Submit</button> </div> </form> -
WebSocket connection to 'wss://myurl/' failed: Error during WebSocket handshake: Unexpected response code: 200
WebSocket connection to 'wss://goldenxchangedjango.herokuapp.com/messages/omonbude/' failed: Error during WebSocket handshake: Unexpected response code: 200 Hi, I'm facing this error using vanilla js for web socket. It works locally, but on production, it gives this error. I've searched for answers, yet I can't fine any. I am hosting on heroku server Please help -
How to stream mp4 videos from Django 3 to Vue.js
I followed the solution here and got a byte string via my axios API and then concatenated it with data:video/mp4;base64,, and binded it to the video tag's :src property, but the video is not displaying. Is this the correct way to stream videos from Django 3 to Vue.js? What am I doing wrong? -
Uploading profile pic from user side . Any update methods in views.py to do so using HTML?
models.py I have created a model of ImageField and migrated on my database from django.db import models from django.contrib.auth.models import User class userprofile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) profilepic = models.ImageField(default='default.jpg',upload_to='profile_pic',blank = True) admin.py from django.contrib import admin from .models import userprofile admin.site.register(userprofile) urls.py This is my URL of the app urlpatterns = [ path('',views.home,name="home"), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django ModelForm Dynamic Lookup based on another field in the same form
So I have these models: class Employee(models.Model): ACTIVE = 'A' INACTIVE = 'I' TERMINATED = 'T' STATUS_OPTIONS = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (TERMINATED, 'Terminated'), ) number = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) status = models.CharField(max_length=1, choices=STATUS_OPTIONS, default=ACTIVE) is_supervisor = models.BooleanField(default=False) supervisor = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='employee_supervisor') class Receipt(models.Model): Supervisor = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_supervisor') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_employee') amount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False) reimbursed_on = models.DateField(blank=True, null=True) receipt_copy = models.FileField(upload_to='receipt_uploads/', null=False, blank=False) You will notice that the Receipt class dual foreignkeys the Employee class. As an Employee can also be a supervisor. Form: class ReceiptForm(forms.ModelForm): class Meta: model = Receipt fields = [ 'Supervisor', 'Employee', 'amount', 'receipt_copy' ] widgets = {} def __init__(self, *args, **kwargs): super(ReceiptForm, self).__init__(*args, **kwargs) self.fields['Supervisor'].queryset = Employee.objects.filter(status='A', is_supervisor=True) self.fields['Employee'].queryset = Employee.objects.filter(status='A') # Dynamic Filter Me... So in my Employees table data there are a bunch of employees some of which are supervisors. Most employees have a relationship to another employee called Supervisor. View: def add_receipt(request): form = ReceiptForm(request.POST or None) if form.is_valid(): form.save() form = ReceiptForm() title = 'Add Receipt' context = { 'title': title, 'form': form } return render(request, "receipts/add.html", context) I am looking for a way that when … -
Error in Django execution,AttributeError: 'NoneType' object has no attribute 'split'
I have a Django project which uses Django+Django Rest Framework+Djoser (token based auth). The project runs perfectly and I am able to GET and POST desired data's with backend. But a strange error hits the running terminal randomly after certain interval and during some GET /POST operation, it never cause work interruption as terminal do not stop running. I have attached the minified error screenshot for the reference. I am unable to identify the place of error/cause of error to debug. complete error code as mention below: [10/Jun/2020 00:01:19] "GET /media/tracks/Kalimba_FXkucKr.mp3 HTTP/1.1" 200 5382144 Traceback (most recent call last): File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 279, in write self._write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\socketserver.py", line 796, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [10/Jun/2020 00:01:19] "GET /media/tracks/Kalimba_FXkucKr.mp3 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 55650) Traceback (most recent call last): File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 279, in write self._write(data) File "c:\users\dell\desktop\pythonfiles\Lib\wsgiref\handlers.py", line 453, in _write … -
Can you do Azimuthal Equidistant projections natively in GeoDjango?
I am working on converting a small project I wrote to find overlapping boundaries of a shape file within a radius of a certain point. This original project was a mock up project I wrote using Shapely and GeoPandas, to make this more suitable for production, I am converting it all to GeoDjango. There is one thing that is vital to this program, which is to create an equidistant projection of a circle on a map. I was able to do this with shapely objects using pyproj and functools. Let it be known that this solution was found on stackoverflow and is not my original solution. from shapely import geometry from functools import partial def createGeoCircle(lat, lng, mi): proj_wgs84 = pyproj.Proj(init='epsg:4326') aeqd_proj = '+proj=aeqd +lat_0={lat} +lon_0={lng} +x_0=0 +y_0=0' project = partial( pyproj.transform, pyproj.Proj(aeqd_proj.format(lat=lat, lng=lng)), proj_wgs84) buf = geometry.Point(0, 0).buffer(mi * 1.60934 * 1000) circle = transform(project, buf) return circle I attempted to again use this solution and create a geoDjango MultiPolygon object from the shapely object, but it results in incorrect placement and shapes. Here is the code I use to cast the shapely object coming from the above function. shape_model(geometry=geos.MultiPolygon(geos.GEOSGeometry(createGeoCircle(41.378397, -81.2446768, 1).wkt)), state="CircleTest").save() Here is the output in Django … -
How order_by with JsonField
I use from jsonfield import JSONField for my model (docs: https://github.com/rpkilby/jsonfield): class FinancialInstrument(models.Model): name = models.CharField(max_length=300) isin = models.CharField(max_length=300, blank=True) price = JSONField(null=True) price has data like that: { "2000-01-01": "31.799999", "2001-01-01": "34.375000", "2002-01-01": "39.400002" } In a method I filter my queryset and I want to order by queryset by value of a date: # Filter my queryset by date date = "2000-01-01" queryset = FinancialInstrument.objects.filter(Q(price__icontains=date)) # And here I want to order by queryset by value of the key data, I tried this but it doesn't work queryset = queryset.order_by(RawSQL("price#>%s", ("2000-01-01",))) But queryset.order_by(RawSQL("price#>%s", ("2000-01-01",))) doesn't work. I don't know how to do! Anyone can help me ? -
Materialize CSS (with django) dropdown form not working
I'm trying to create a form in which the user choices an instance of model object (Invoice) already saved in the database and submits. I've tried to initialize the JS, but have little experience working with JS in html so I'm not totally sure I'm doing it right. Right now the below code does not render anything besides the submit button in the form. I have tried adding a random input field (worked) and tried unpacking and rendering the "invoices" context as raw text on the same page (also worked) so I think I've narrowed the issue down to it being the form choices. header.html <head> {% load static %} <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <!-- Compiled and minified CSS --> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <script type = "text/javascript" src = "https://code.jquery.com/jquery-2.1.1.min.js"></script> <script> $(document).ready(function(){ $('select').formSelect(); }); </script> </head> <body> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo">Elb</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="/bulk_invoice_upload/">Invoice Upload</a></li> <li><a href="/bulk_inventory_upload/">Inventory Upload</a></li> </ul> </div> </nav> {% block content %} {% endblock %} </body> form.html {% extends 'main/header.html' %} <body> {% block content %} <br> <br> <form … -
Django annotate by foreign key's date field but exclude past dates
I want to have my queryset of Card model annotated with new field called available_on, which should be calculated as closest date in future of relative Booking model's field removal_date. It should consider only dates in future, how can I filter out removal_date dates that are in the past? What I have now is this. def with_available_on(self): qs = self.annotate(available_on=Case( When(bookings_count__gt=0, slots_available__lt=1, then=Min('bookings__removal_date')), default=None) ) return qs Also I want it to be calculated on database side if possible for performance purposes. Thanks -
I removed date field, but still i am getting datetime_re.match(value) TypeError in django
Model(added 'date_uploaded' field): from django.contrib.auth.models import User from django.db import models from django.utils import timezone class VideoUploads(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(null=True) date_uploaded = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Videos' I got the following Errors: : : : File "C:\Users\adars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1414, in get_prep_value value = super().get_prep_value(value) File "C:\Users\adars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1274, in get_prep_value return self.to_python(value) File "C:\Users\adars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 1375, in to_python parsed = parse_datetime(value) File "C:\Users\adars\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object Model (removed 'date_uploaded' field): but still getting the same error even after i removed 'date_uploaded' field class VideoUploads(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(null=True) def __str__(self): return f'{self.user.username} Videos' How this migration works? -
Unespected @media behaviour when reloading page
I've added media queries for tablet, Ipad pro and every touch screen devices. However, one of the images from one of the retreat4 media query is appearing when I refresh the page. I thought it might be an hierarch problem but it is not changing. base.html <div class="overlay"> <video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop"> <source src="{% static 'videos/yoga.mp4' %}" type="video/mp4"> </video> <div class="container3 h-100"> style.css @media (min-width: 2000px) { .image2 { position: absolute; top: 45vh; left: 110vh; } } /* Change navbar styling on small viewports */ @media (max-width: 991.98px) { .navbar { background: #fff; } .navbar .navbar-brand, .navbar .nav-link { color: #555; } } /* iPads (portrait) ----------- */ @media only screen and (max-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { header { background: url("https://..path..here../static/images/retreat4.jpg") white no-repeat center scroll; position: relative; } .carousel-caption.d-none.d-md-block h1 { padding-bottom: 300px; } } @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) { header { background: url("https://..path..here../static/images/retreat5.png") white no-repeat center scroll; position: relative; } .carousel-caption.d-none.d-md-block h1 { padding-bottom: 250px; } } /* Ipad Pro */ @media only screen and (min-width: 1024px) and (max-height: 1366px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 1.5) … -
Django-rest-auth (dj-rest-auth) custom user registration
I'm using dj-rest-auth (https://dj-rest-auth.readthedocs.io/en/latest/) and trying to implement a custom registration form. When I'm trying to register a new user I have the base form. I've seen with the older version (https://django-rest-auth.readthedocs.io/en/latest/) that if you use password1 and password2, you don't have to retype all the code. serializers.py from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField() last_name = serializers.CharField() def get_cleaned_data(self): super(CustomRegisterSerializer, self).get_cleaned_data() return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), 'email': self.validated_data.get('email', ''), 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', '') } settings.py REST_AUTH_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer', } -
How do i tag users to a post
i am creating a website where a user can upload post and also tag other users, just like facebook. I have successfully implemented a postform and also added a tag field to manytomany field in model. I do not have an idea on this particular topic. So how do i tag a user to a post, when postform is submitted then the users tagged will be selected automatically when the post is saved in admin, so that when i check on the post in admin i will be able to see tagged users selected in manytomany field. I have a form field where the username who you want to tag will be entered before the form is submitted in autocomplete. Model.py: class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) image_caption = models.TextField(blank=True, null=True) tag_someone = models.ManyToManyField(User, related_name='tagged_users', blank=True) Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'image_caption', 'tag_someone', ) Views.py: @login_required def upload_view(request): ImageFormset = modelformset_factory(File, fields=('files',), extra=20) if request.method == "POST": form = PostForm(request.POST) formset = ImageFormset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): post = form.save(commit=False) post.poster_profile = request.user post.save() for f in formset: try: photo = File(post=post, files=f.cleaned_data['files']) photo.save() except Exception as e: break return redirect('/') else: form = … -
Should I integrate React JS in django?
I have to build a really big project that requires scalability and I am having some doubts as to whether I should integrate React inside Django. The project is social network-like and consists of the following: -Backend ran by Django Rest Framework that communicates with database. Frontends will be the following: -Discord bot -Web application (will be built using React JS), which some users will be able to access from the main website and does not require SEO. -Mobile applicaiton (built with React Native) -The website itself, which in theory could be built with Django serving plain HTML, CSS, and some React compiled Javscript. However, I would prefer to use Django only as the backend serving JSON data, and build this website with React, which will be hosted in a server independent from Django. I obviously need good SEO, so plain React won't work. I've read about Gatsby and NextJS and in this case I think NextJS is the way to go. My main concern is to be able to successfully integrate the authentication system in this NextJS server (I need users to register, log into the site, store session data, etc). I know Django does this very easily, but … -
Django user to user live chat (no chat rooms)
Can anyone recommend me a tutorial on how to make a Django user to user live chat. I know that I need channels in order to do this but I am not familiar with channels and in the Django documentation they are using chatrooms instead of user to user chat which makes it hard for me to learn channels and implement the chat in my own app. Any suggestions? -
TypeError: Object of type bytes is not JSON serializable in Django
I am using Django FormWizard and I currently have 3 steps. Each step contains extra data with Pandas DataFrame type stored in sessions as json type which can be accessed anywhere in the form. This works just fine until I stored a dict type data in the 3rd step. Here's a peek of my code: class MyWizard(SessionWizardView): # some code ... def get_context_data(self, form, **kwargs): # some code ... if self.steps.current == 'step_3': my_data = calculate(param1.to_numpy(), param2, ['param3']) self.request.session['mdata'] = my_data print(self.request.session['mdata']) context['p3'] = my_data['param3']['plot'].decode('ascii') # some code ... return context The calculate method returns a JSON Object with a format: { 'param3': { 'result':-1, 'plot':<base64 encoding of param3 plot> }, } type(mydata) outputs a <class 'dict'>. I believe that storing this in Django sessions should work. However, when I proceed to step 3, I got the following error after the output of print(self.request.session['mdata']): Internal Server Error: /step_3/ Traceback (most recent call last): File "C:\Users\Envs\i\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Envs\i\lib\site-packages\django\utils\deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "C:\Users\Envs\i\lib\site-packages\django\contrib\sessions\middleware.py", line 58, in process_response request.session.save() File "C:\Users\Envs\i\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save obj = self.create_model_instance(data) File "C:\Users\Envs\i\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance session_data=self.encode(data), File "C:\Users\Envs\i\lib\site-packages\django\contrib\sessions\backends\base.py", line 95, in … -
my dhango server's import_export module don't work especialy in importing
'''class institutionResource(resources.ModelResource): class Meta: model = institution exclude = ('id',) import_id_fields = ('institution_number',)''' '''class institutionAdmin(ImportExportActionModelAdmin): list_display = ['institution_number', 'quiz1','quiz2','quiz3'] resource_class=institutionResource pass''' this is my code but when i import my xlsx file, look like this picture enter image description here this is my model code enter code here '''class institution(models.Model): institution_number = models.CharField(max_length=13, primary_key=True) quiz1 = models.CharField(max_length=400,blank=True, default=False) quiz2= models.CharField(max_length=400,blank=True, default=False) quiz3 = models.CharField(max_length=400, blank=True, default=False) qrcode=models.CharField(max_length=50, default=False) latitude = models.CharField(max_length=20) longitude = models.CharField(max_length=20) class Meta: ordering = ['institution_number'] ''' -
Display key/value pair in template from Django model
Sorry if the question itself is confusing. I have a model with two lists that are used as dropdown lists for the user to choose from. Everything works fine except when viewing the data it will just show the key when I want it to show the value. models.py class RestroomReview(models.Model): MEN = 'M' WOMEN = 'W' UNISEX = 'U' FAMILY = 'F' RESTROOM_TYPE_CHOICES = [ ('M', 'Men'), ('W', 'Women'), ('U', 'Unisex'), ('F', 'Family') ] RATING_CHOICES = [ (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ] venue = models.ForeignKey(Venue, blank=False, on_delete=models.CASCADE) user = models.ForeignKey('auth.User', blank=False, on_delete=models.CASCADE) public = models.BooleanField(blank=False) rest_type = models.CharField( max_length=1, choices=RESTROOM_TYPE_CHOICES, default=MEN ) baby = models.BooleanField('Changing Table') needle = models.BooleanField('Sharps Container') handicap = models.BooleanField('Handicap Accessible') rating = models.IntegerField(choices=RATING_CHOICES, default=1) title = models.CharField(max_length=200, blank=False) comment = models.TextField(max_length=1000, blank=False) posted_date = models.DateTimeField(blank=False) review_detail.html {% extends 'restroom_rater/base.html' %} {% block content %} <div> <h3>{{ review.venue.name }}</h3> <p>Title: {{ review.title}}</p> <p>by {{ review.user }}</p> <p>Public: {{ review.public }}</p> <p>Type: {{ review.rest_type }}</p> <p>Changing Table: {{ review.baby }}</p> <p>Sharps Container: {{ review.needle }}</p> <p>Handicap Accessible: {{ review.handicap }}</p> <p>Rating: {{ review.rating }}</p> <p>Comment: {{ review.comment }}</p> <p>Date Posted: {{ review.posted_date }}</p> </div> {% endblock %} so in my … -
Replace text entry for datetime to calendar date picker icon in Django form
I've this template in my Django application for adding a training session: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>New session</h1> <form action="" method="post">{% csrf_token %} {{ form|crispy }} <input class="btn btn-success" type="submit" value="Save" /> </form> <p /> {% endblock content %} The form contains a datetime field which appears as follows: Is it possible to change this so instead of entering the datetime as text it can be selected from a calendar type icon? If so, how is this done? This is my view: class SessionCreateView(CreateView): model = ClubSession template_name = 'session_new.html' fields = ['location', 'coach', 'date', 'details'] This is my model: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.location def get_absolute_url(self): return reverse('session_detail', args=[str(self.id)])