Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: '>=' not supported between instances of 'datetime.datetime' and ' float'
import datetime from django.utils import timezone class Allcourses (models.Model): started_from=models.DateTimeField('Started from') def was_published_recently(self): return self.started_from >=(timezone.now()-datetime.timedelta(days=1)).timestamp() -
why am I getting network error for my Django website?
My django website was integrated with default SQLite DB. Yesterday, I tried migrating it to Postgres, however, due to some password issue, the migration failed. Then I tried to fall back to SQLite just by uncommenting the SQLite portion in settings.py. But it failed too. I guess I broke my Database. To fix the issue I used the below CLI command to delete everything in the SQLite: python manage.py migrate my-app-name zero Then I used makemigratons and then migrate. So, here everything seem to go smoothly. However, now I faced the connectivity issue with my website. Its not launching from web browser. I don't know if I have messed my entire environment itself. My website is hosted on AWS on Ubuntu server, it has gunicorn and nginx up and running. Initially I was receiving some below error: A communication error occurred: The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests I checked the journalctl logs, and I found something like below: nginx.service: Failed to read PID from file /run/nginx.pid: Invalid argument To try to fix the issue I followed the web link. But, it is not working. I am not sure … -
Creating a duration field using startdate and lastdate of DateField type in Django
All I need to do is calculating difference between two dates and store it as another field in database. class Experience(models.Model): startdate = models.DateField(default=date.today) lastdate = models.DateField(default=date.today) duration = models.DurationField((startdate-lastdate).days) Kindly let know what am I doing wrong here, and what should be done to correct. -
DJANGO - dynamic form fields creation using ajax
I'm new to django, and i'm having trouble adding form fields dynamically with a click of a button using ajax. This is what I tried so far using modelformset_factory. In my views.py I have a code like this which is called to add a new field of author from ajax: if request.is_ajax: AuthorFormset = modelformset_factory(Author, form=AuthorForm) author_form = AuthorFormset(request.POST) if author_form.is_valid: return JsonResponse({'data': str(author_form)}) basically, what I want to do with that code is return a new formset with an initial value of the POST request sent from ajax with one extra field. But this code only returns the fields from the POST request without the extra field. How can I make it do that? I appreciate any help, thanks in advance! -
how to solve bad request in django rest-frame-workd
I have created an api which accepts user email and password to login. When ever i tried accessing the api, i get bad request. I have been searching the need, looking at my code. but yet i cannot figure out what i am doing wrong. Please help Below my html form <form id="loginform"action="userlogin/" method="post" enctype="multipart/form-data"> <div class="errors-field"> </div> <div class="input-field"> <label > Email </label> <input placeholder="Email"type="email" name="email" value=""required> </div> <div class="input-field"> <label> Password </label> <input placeholder="Password"type="password" name="password" value=""required> </div> <button type="submit">Login</button> </form> My java script below const lgform = document.querySelector('#loginform') lgform.addEventListener('submit',loginForm) function loginForm(event){ event.preventDefault() const myform = event.target const myFormData = new FormData(myform) const url = myform.getAttribute("action") const method = myform.getAttribute("method") const csrftoken = getCookie('csrftoken') const xhr = new XMLHttpRequest() xhr.open(method,url) xhr.setRequestHeader("Content-Type","application/json") xhr.setRequestHeader("HTTP_X_REQUEST_WITH","XMLHttpRequest") xhr.setRequestHeader("X-Requested-with","XMLHttpRequest") xhr.setRequestHeader("X-CSRFToken",csrftoken) xhr.onload=function(){ const serverResponse = xhr.response const serverData = JSON.parse(serverResponse) console.log(serverData.email) if(xhr.status==200){ if(serverData.token){ cname = "user" cvalue = serverData.token exdays = 1 setCookie(cname, cvalue, exdays) } } } xhr.onerror=function(){ console.log('error') } xhr.send(myFormData) } my serilialozer class loginUserSerializer(serializers.Serializer): password = serializers.CharField(style={'input_type':'password'},write_only=True,required=True) email = serializers.EmailField(required=True) def validate_email(self,value): data = self.get_initial() pw = data.get('password') email= value user=authenticate(email=email,password=pw) if not user or not user.is_active: raise serializers.ValidationError('email or password not correct') return value My api view class loginUser(ObtainAuthToken): def post(self,request,*args,**kwargs): data … -
Foreign Key in Model causing IntegrityError NOT NULL constraint failed:
I have a model where a user posts a job vacancy, then other users can submit applications. The submit application model is called CandidatesSubmission & pulls the 'title' from a different app/model. I not sure what I'm doing wrong in this line: title = models.ForeignKey('jobs.JobsPost', on_delete=models.CASCADE) but it causes "IntegrityError NOT NULL constraint failed: candidates_candidatessubmission.title_id." I have tried adding null=True, blank=False but which stops the error but the title isn't saved to the database. Any suggestions on what I'm doing wrong would be great. Thank you class CandidatesSubmission(models.Model): title = models.ForeignKey('jobs.JobsPost', on_delete=models.CASCADE) Fee = models.CharField(max_length=50, null=False, blank=False) CandidateFirstName = models.CharField(max_length=50, null=True, blank=False) CandidateSecondName = models.CharField(max_length=50, null=True, blank=False) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How track track field type in change log of a database Row
I have been working on Django and I wanted to track the changes of a table and I am thinking of a table to keep track of the changes on a field-based tracking system like audit_field (table_name, id, field_name, field_value, status, datetime) with the status column ready to track if this change has been approved or not and is visible on the model. but I wanted to keep track of the field types too to use database validation against it. FYI I am working on Django and Mysql database -
How to access media through URL after uploading
I am trying to make a blog application, where every post has a featured image. When I upload the image from admin dashboard, I can see the image in my folder. But, when i try to access the url of the image or show the image from source, it's showing nothing. Here is my code: models.py class Post(models.Model): PRIVACY=( ('0', 'Public'), ('1', 'Private') ) title = models.CharField(max_length=250) image = models.ImageField(upload_to="gallery/") description = models.TextField() status = models.CharField(max_length=8, choices=PRIVACY, default='0') tags = TaggableManager() published = models.DateField(auto_now_add=True) slug = models.SlugField(max_length=58,blank=True,) def save(self, *args, **kwargs): slug_save(self) # call slug_save, listed below super(Post, self).save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('src:post_detail',args=[self.slug]) def get_image(self): return self.image.url views.py def home(request): posts = Post.objects.order_by('-published') template = 'home.html' context = {'posts': posts} return render(request, template, context) def post_detail(request,post): post = get_object_or_404(Post, slug=post) return render(request,'detail.html',{'post': post}) urls.py app_name = 'src' urlpatterns = [ path('', views.home, name='home'), path('<slug:post>/',views.post_detail,name='post_detail'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += staticfiles_urlpatterns() **home.html {% extends 'base.html' %} {% block content %} {% for post in posts %} <section class="post"> <h3><a class="post-title" href="{{post.get_absolute_url}}"> {{ post.title }} </a></h3> <span class="post-meta"> {{ post.published }} <a href="{{post.get_image}}"> <img src="{{ post.image.url }}" /></a> </span> <p class="post-excerpt"> {{ … -
Django Rest - Show Item base on User login
I want implement simple role Admin and User. Admin can see every user's item and user can see their only item. My Viewset class IncidentViewset(viewsets.ModelViewSet): queryset = Incident.objects.all() serializer_class = IncidentSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = IncidentFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In laravel this can be done by auth()->user()->id = user_id, but dont know in Django. Thanks in advance... -
Django Custom User Model Optional Field and Integer Field with Specific Format
fellow devs! I am writing a custom user model in Django but I can't figure out how can I make a user input middle name for those who have it or won't force it for those who don't. This code works but I have to type a space to bypass the middle name field, which isn't the ideal behavior I want. Also, I want to know if it's possible to set a custom primary key to the field id_number. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, firstname, lastname, middlename, id_number, password=None, active=True, staff=False, admin=False): if not email: raise ValueError('User must have a valid Email Address!') if not username: raise ValueError('User must have Username!') if not password: raise ValueError('User must set Password!') if not firstname: raise ValueError('User must have First Name!') if not lastname: raise ValueError('User must have Last Name!') if not id_number: raise ValueError('User must have a valid ID number!') user = self.model( email=self.normalize_email(email), username=username.lower(), firstname=firstname.capitalize(), lastname=lastname.capitalize(), middlename=middlename.capitalize(), id_number=id_number ) user.set_password(password) user.staff = staff user.admin = admin user.active = active user.save(using=self.db) return user def create_staffuser(self, email, username, firstname, lastname, middlename, id_number, password=None): user = self.create_user( email, username=username, lastname=lastname, firstname=firstname, middlename=middlename, id_number=id_number, password=password, staff=True ) return user … -
How do I return to the comments section after deleting an individual comment in django?
I am trying to delete an individual comment from my comments page and then simply remain on the same page. My delete view is fired from a modal within a for loop like this: {% for comment in comments %} {% if comment.author == user %} <button type="button" data-toggle="modal" data-target="#comment-delete{{comment.id}}" class="btn btn-danger">Delete</button> <div class="modal fade" id="comment-delete{{comment.id}}" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times</button> <h3 class="modal-title">Do you really want to delete?</h3> <div class="modal-body"><p>{{ comment.content }}</p></div> <div class="modal-footer"> <form action="{% url 'comment_delete' comment.id %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-outline-danger">Yes, Delete</button> <button type="button" data-dismiss="modal" class="btn btn-secondary btn-outline">Cancel</button> </form> </div> </div> </div> </div> </div> </div> {% endif %} {% endfor %} Here is my Comment model: class Comment(models.Model): content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.content[:5] My relevant urls: urlpatterns = [ path('post/<int:pk>/comments/', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/', CommentDeleteView.as_view(), name='comment_delete'), And this is my deleteview: class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment # success_url = '/' # def get_success_url(self): # return reverse('post_detail', kwargs={'pk': Post.pk}) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False As you can see I have tried to use the get_success_url method … -
Django projects with Postgres stopped working after brew install
I was trying to get Selenium to work, and so followed the suggestion here to brew install geckodriver in the relevant virtual environment (pipenv). After having done that, my other virtual environments stopped working. I was able to get most of them to work again by re-installing pipenv outside of any virtual environment (using pip3 install pipenv). But all of my Django projects that rely on Postgres still don't work: I'm able to start their virtual environment (with pipenv shell), but python manage.py runserver gives me the following traceback: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/my_last_name/.local/share/virtualenvs/pred_market_pg_copy-ZXHemaJW/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", … -
AttributeError: 'tuple' object has no attribute 'encode' (django contact form)
I am creating a Contact page for my django project. forms.py has name, subject, sender and message. Here's the view: def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] sender_email = form.cleaned_data['sender_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] send_mail(subject, message, sender_email, ['***@gmail.com']) return render(request, 'contact_us.html', {'form': form}) The template: <h1>Contact Us</h1> <form method="POST"> {%csrf_token%} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> After I click Send I get this error: AttributeError: 'tuple' object has no attribute 'encode' and I can't seem to figure out what's wrong despite checking other questions of the same type the last couple of days. I have followed instructions from link 1 and link 2 to set up the SMTP server (2 different cases) and it gives me the same error. How can I fix that? Thank you! -
angular 9 production files fail in django. Error 404
well, I worked in a little project and everything was fine, when I made a build files everything is wrong. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Frontend</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="{% static 'styles.1165db34b7e7158143e4.css' %}"></head> <body> <app-root></app-root> <script src="{% static 'runtime-es2015.40ead21e007fa8741f0a.js' %}" type="module"></script> <script src="{% static 'runtime-es5.40ead21e007fa8741f0a.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es5.86f7ad57e8b901d60e04.js' %}" nomodule defer></script> <script src="{% static 'polyfills-es2015.ae2ff135b6a0a9cb55e7.js' %}" type="module"></script> <script src="{% static 'main-es2015.f1b8c0450fffd3db5039.js' %}" type="module"></script> <script src="{% static 'main-es5.f1b8c0450fffd3db5039.js' %}" nomodule defer></script></body> </html> this is my routes.py urlpatterns = [ path('admin/', admin.site.urls), path('login/', include('apps.index.urls')), path('api/v1.0/', include('apps.abogado.api.urls')), path('api/v1.0/', include('apps.despacho.api.urls')), path('api/v1.0/', include('apps.proceso.api.urls')), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In angular this is my login <div class="login-div"> <div class="image-div"> <img [src]="'/assets/logo.svg'"> </div> <form action="" class="formulario"> <div class="fields"> <div class="username"><input type="text" class="user-input" name="username" placeholder="usuario" [(ngModel)]="user.username"></div> <div class="password"> <input type="password" class="pass-input" name="password" placeholder="contraseña" [(ngModel)]="user.password"></div> </div> <button type="submit" class='signin-button' (click)="login()" >Login</button> </form> with this code the user is redirect to dashboard login(user:object) { return this.http.post('http://127.0.0.1:8000/api/token/', JSON.stringify(user), this.httpOptions).subscribe( res => { this.almacenarCredenciales(res, user); this.router.navigateByUrl('dashboard/proceso/todas-notificaciones') } ); } after make the login, the user is redirect to dashboard, there is where happens … -
Share variables to included templates in django
In views.py the thing object is being passed to index.html. def index(request): return render(request, "myapp/index.html", { 'things': Thing.objects.all() }) index.html is setup like this: {% block body %} {% for thing in things %} {{ thing.attribute }} <button type="button" class="btn" data-toggle="modal" data-target="#exampleModal"></button> {% endfor %} {% endblock %} I would like to separate the html that renders the modal referred to by the button into another html file to keep things organized. I was able to do this by referencing the modal html file with include as shown below: {% block modal_code %} {% include 'myapp/modal_code.html' %} {% endblock %} But I could not figure out how to share the things object with the model code so the modal could dynamically display the object's content. Is there a way to do this? -
Pass values from url to django model?
I want to take a value from my url using POST, pass that variable to my model and save in my database. Can anyone help? -
how to make a database connection PAGE/FORM in django
please help I'm so lost on this. Everything i search on this just tries to explain how to connect django to a database. which is not the goal. The goal is: I'm trying to make a form where users can insert their database credentials and connect. Don't leave yet! I already have it working - but I don't know how to link the users responses to the script that connects to the database. Here's my form and some of the code (it's django so code is everywhere): The db html page: {% extends 'base.html' %} {% block content %} <h1>New DB Connection</h1> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-info ml-2" type="button" value="Cancel" onclick="history.back()"> <button class="btn btn-info ml-2" onclick="location.href='{% url 'output_script' %}'">Connect!</button> <hr> {% if df %} {{ df }} {% endif %} </form> {% endblock content %} The views.py file: Here's where it gets hard - How do i link the inputs in the DBCreateView class and assign them to the variables in the output function?! Sorry if this seems easy, but it's beyond me. class DbCreateView(CreateView): # if request.POST: # form = model = db template_name = 'db_new.html' fields = ('USERNAME','PASSWORD','ACCOUNT','WAREHOUSE','DATABASE', 'SCHEMA', 'ROLE') … -
Django user authentication does not work, how can I fix my login?
I am using the django-email-verification app and I had to change how a User is signed up but I left the login authentication part the same. Every time I try to login it does not allow me to sign in and says that the credentials are wrong. Also I used emails as usernames. I'm thinking its the: user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) that needs to be changed. Please how do I fix the login? from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib.auth import get_user_model from django_email_verification import sendConfirm def signup(request): if request.method == 'POST': if request.POST['pass1'] == request.POST['pass2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error': 'Email is already registered'}) except User.DoesNotExist: '''user = User.objects.create_user(request.POST['username'], password=request.POST['pass1']) auth.login(request, user)''' user = get_user_model().objects.create(username=request.POST['username'], password=request.POST['pass1'], email=request.POST['username']) sendConfirm(user) return redirect('home') else: return render(request, 'accounts/signup.html', {'error': 'Passwords must match'}) else: return render(request, 'accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: auth.login(request, user) return redirect('home') else: return render(request, 'accounts/login.html',{'error':'username or password is incorrect.'}) else: return render(request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('home') -
Syntax Error in django migrate with SQL Server
I have an error in python manage.py migrate in all models with ForeignKey fields. django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Sintaxis incorrecta cerca de '.'. (102) (SQLExecDirectW)") The table is created and the index is created too, but in the add constraint statement for the foreign key the error is shown. The model. class Book(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey('Author', related_name='books', on_delete=models.PROTECT) name = models.CharField(max_length=20) class Meta: db_table = u'Library].[Book' # this line sets the schema for the table in MSSQL DB the sqlmigrate output: python manage.py sqlmigrate catalogos 0018_prueba -- -- Create model Prueba -- CREATE TABLE [Library].[Book] ([id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY, [name] nvarchar(20) NOT NULL, [author_id] int NOT NULL); CREATE INDEX [Library].[Book_author_id_66e91062] ON [Library].[Book] ([author_id]); ALTER TABLE [Library].[Book] ADD CONSTRAINT [Library].[Library_author_id_66e91062_fk_Library].[Author_id] FOREIGN KEY ([author_id]) REFERENCES [Library].[Author] ([id]); # this raises error when is executed in sql server the last line adds the foreign key but it raises the error, the table is created succesfully, the index is created too and in the django_migrations table, the migration is applied but the foreign key does not exists. How can i avoid this error?, This happens in all my models with foreign … -
Django cron vs Django celery vs Django schedule
I am currently looking into implementing this specific task: once a scheduled message reached its supposedly-sent date, the system will then automatically send the message (convert from saved drafts status to sent). After some very light research, seems like there are many ways to do this but which technology is the best for my situation? Django cron, celery, or schedule (https://schedule.readthedocs.io/en/stable/)? What are the pros and cons of each? Thank you! -
HTTP Requests between Pi and existing Full Stack Web Application
I would like to send API data via https requests between Raspberry Pi GPIO and my Existing Django Backend in order to store on my existing database(django/sqlite). It's for a portable IOT device. What is the best method to achieve this? Do I still require the flask server on the Pi? If so, will I be required to deploy my Rasp Pi Flask Server onto the web? I look forward to hearing from someone. This is the missing piece in the puzzle, so your help will be much appreciated! Thank you! -
Access kwargs in Django Forms
With reference to the picture above, I am trying to access the kwargs pk in the forms.py. In the views.py kwargs pk is not empty and has a value of 57. My problem is, how to access this pk in forms.py. When poping the 'pk' it returns an error. I have written some code here but cannot retrieve pk kwargs. Here is mi code in the form.py: project_id = kwargs.pop('pk') #THIS RETURNS AN ERROR super(ModelCreateForm, self).__init__(*args, **kwargs) project = Project.objects.get(id=project_id) In my views.p I have: kwargs = super(ModelCreateView, self).get_form_kwargs() pk = self.request.GET['pk'] kwargs['pk']=pk return kwargs -
How to insert multi rows in django
I need your help to insert multi rows in Django I've a form: start from,end to,number of_book,branch,active date,active for example: start from=101 end to=125 start from=126 end to=150 start from=151 end to=175 start from=176 end to=200 and the other inputs is static My Form -
django importing problems but everything is working properly
i'm using django 3.1 and i have python3 and in my file when i import something saying from lorem import ipsum it says no name 'ipsum' in module lorem for example: from django.conf.urls import url from django.contrib import admin from django.urls import path , include there is says: No name 'path' in module 'django.urls' No name 'include'in module 'django.urls' -
How do I make a ForeignKey field use Multiple Dropdowns from the same list, and remove duplicates as they are selected, in Django?
I am trying to set up a Django project that will reference a list of users. In one of my models, I am using ForeignKey fields to point at the table of users. I have several slots setup, linked to the table of users, and I would like to be able to select a user from that table when adding data. But I would also like the users name to be removed from the rest of the dropdowns if they are selected in one of the dropdowns. For Example. I have 3 users in my table. John, Mark, Andy In the entry page, I would like to have 3 dropdown fields. Each of them linked to the users table. In the first field when I click it, all three users should pop up as options, John, Mark and Andy. After selecting John, the second field should only give me the option to select Mark or Andy. After selecting Mark for the second field, the third field should give the option to select Andy, or stay blank. My models.py is setup like this: class Users(models.Model): name = models.CharField(max_length=15) class Session(models.Model): Slot1 = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='Slot1') Slot2 = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='Slot2') Slot3 …