Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change <input> type- text to type- date in django form
I want to apply bootstrap for forms, but in the input "date" tag the "type" is defined as "text". model: class AdmissionForm(forms.Form): date = forms.DateTimeField(widget=forms.DateTimeInput( attrs={ 'class': 'form-control' } )) def save(self): new_admission = Admission.objects.create( date = self.cleaned_data['date'],) -
Django ' One To Many ' Relationship (Comment on a joke)
thought I'd make a website, where people can upload jokes and comment on different ones, basic functions so far. The only issue I am facing is once I create a comment, I cannot automatically assign it to a joke, I have to select the joke manually that I want to comment on, how do I do that using the current many to one relationship that I have now. Current thoughts... Use this from the jokes model that I'm passing around in the urls to select the joke and assign to the comment this way (Not sure how to do this) Here are my models: from django.db import models from django.utils import timezone from django.urls import reverse class JokeListItem(models.Model): title = models.CharField(max_length=100, null=True) content = models.TextField(null=True) date_posted = models.DateTimeField(null=True, default=timezone.now) comment = models.CharField(max_length=100,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('joke-home') class Comment(models.Model): content = models.CharField(max_length=100,null=True, blank=True) joke = models.ForeignKey(JokeListItem, blank=True, null=True, on_delete=models.CASCADE,related_name='comments') def __str__(self): return self.content def get_absolute_url(self): return reverse('joke-home') Here are my views: from django.shortcuts import render from .models import JokeListItem, Comment from django.views.generic import CreateView, DeleteView, DetailView, UpdateView from django.shortcuts import get_object_or_404 # Create your views here. def home(request): all_joke_items = JokeListItem.objects.all() return render(request, 'website/home.html', {'jokes': all_joke_items}) class … -
Handling html special chracter in django url
This is my django rest framework view: class NewsArticleViewSet(viewsets.ReadOnlyModelViewSet): queryset = [] serializer_class = NewsArticleSerializer pagination_class = None def get_queryset(self): slug = self.request.query_params.get('news', None) if slug: news = News.objects.filter(slug=slug) return news return [] which is working perfectly except when I pass html special chracter in url like this one: ?news=example/2020/4/4/&apos;53-lorem-ipsum&apos; its returning nothing; because self.request.query_params.get('news', None) parsing as example/2020/4/4/ not full string example/2020/4/4/&apos;53-lorem-ipsum&apos; Here is value of self.request.query_params for debugging: <QueryDict: {'news': ['example/2020/4/4/'], 'apos': ['', ''], '53-lorem-ipsum': ['']}> How to fix this problem ? -
How to run a Django Query to filter from a list of values?
I have a list that looks like this - Let's call this list "links" ['https://crucible05.cerner.com/viewer/cru/CCS-28483', 'https://crucible05.cerner.com/viewer/cru/CCS-28520', 'https://crucible05.cerner.com/viewer/cru/CCS-28779'] My Python model, reviewComments looks like this - class reviewComments(models.Model): reviewID = models.CharField(max_length=20, blank=True) commentID = models.CharField(max_length=20, primary_key=True) solution = models.CharField(max_length=50) comment = models.TextField() dateCreated = models.DateField() type = models.CharField(max_length=20, blank=True) crucibleLink = models.URLField(blank=True) authorID = models.CharField(max_length=20) reviewerID = models.CharField(max_length=20) def __str__(self): # pragma: no cover return self.commentID In reviewComments, the field crucibleLink field contains several elements in the database like this - ['https://crucible05.cerner.com/viewer/cru/CCS-24654#CFR-2484153', https://crucible05.cerner.com/viewer/cru/CCS-26041#CFR-2549576 ] Notice the extra #CFR part in each of these.. I need to run a Django query to filter out the "links" elements from the ones present in the database. I tried doing this - crucible_db = reviewComments.objects.values_list('crucibleLink', flat=True) for link in links: crucible_db = crucible_db.filter(crucibleLink__icontains = link) print(crucible_db) But this returns only one queryset and then several empty querysets like this - How do I go about doing this? Thanks -
Django - How can i use "def create()" in an article serializer?
I am trying to make a serializer that can create an article. I have done registration and login part successfully,but i don't know how to write a def create serializer so the data can be saved on Article. Can somebody help? class ArticleCreateSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','author','caption','details') def create(self, validated_data): //???? return article -
How can I display images with the same height with CSS?
I have a dating website and I display lists of users with profile pictures. If the user doesn't have a profile picture, I display a specific image. Here is the code: @register.inclusion_tag(filename='accounts/profile_picture.html', takes_context=True) def profile_picture(context, user, geometry, with_link=True, html_class=''): context = copy.copy(context) geometry_splitted = geometry.split('x') width = geometry_splitted[0] if (len(geometry_splitted) == 2): height = geometry_splitted[1] else: height = geometry_splitted[0] context.update({ 'user': user, 'geometry': geometry, 'width': width, 'height': height, 'with_link': with_link, 'html_class': html_class, }) return context profile_picture.html: {% thumbnail user.photo.file geometry crop='center 20%' as image %} <img src="{{ image.url }}" alt="{{ user.name }}" width="{{ image.width }}" height="{{ image.height }}" class="img-fluid {{ html_class }}" /> {% empty %} <img src="{% static 'speedy-core/images/user.svg' %}" alt="" width="{{ width }}" height="{{ height }}" class="img-fluid {{ html_class }}" /> {% endthumbnail %} CSS: .img-fluid { max-width: 100%; height: auto; } But the problem is, because of this height: auto; thing, users without a profile picture have profile pictures higher than users with profile pictures. I want to display all users with the same height, and if necessary, display a smaller width for users without a profile picture (which displays speedy-core/images/user.svg as their profile picture). If possible, without changing the file user.svg itself. How do I do … -
Django, how to sum queryset value in dictionary values
I have the following queryset dictionary: {'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]} In which I have as Key the category of my products and as items 12 values, that rappresent the sum of each month. I want to calculate the cross sum of all keys of each items, as the following example: {'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]'} How could I obtain it? -
How do I get data stored in localStorage by Django
I made web with Django. And web is created by Javascript. The problem is how to get localStorage Value. If I choose the button then it stored number 1 or 2 at localstorage. function setNumber(num) { localStorage.setItem(FST_NUM_LS, num); } like this. And web is changing for another button, and choose and choose, etc.. Finally, local storage have number that sum of all before number. And I want show result at next page. The result is if sum of number is 1 then show "num 1 result", else "num 2 result" like this.. Result is append to sum of value in localStorage. But I coudn't get localStorage value with Django. How can I get localStorage value?? Or use another method? Plz give me a hint... -
Optionally link a model to another model via a foreign key
I have a Django application where registered users can add, through an input form, details of performances of their music ensemble. This application also has a a section for composers, where they add their own composition. I'm using a custom user model, with profiles linked to user accounts: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) [...] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) [...] This is my 'composition' model: class Composition(models.Model): title = models.CharField(max_length=120) # max_length = required composer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) [...] And this is my 'performance' model. The performance information links to the piece performed (performed): class Performance(models.Model): performed = models.ManyToManyField(Composition, blank=True) [...] So far, so good. Now, I'd like the performers to be able to add pieces by composers who are not (yet) registered to the website. Let's say that the performer performed a piece by John Lennon and is adding information about that performance. So, the performer will need to be able to add both John Lennon, his composition, and link the two. The most important bit is: if the ghost of John Lennon tomorrow wants to register to the website, the administrator of the website will need to be … -
Pytest Not Deselecting Certain Tests (but should be in pytest.ini)
I've got a test suite setup and have been using pytest (which I find so fantastically helpful for testing Django projects, which this is). I also am using pytest-django on this project. To give some background: I am trying to do some integration testing with a Headless Browser and have pytest ignore certain tests that are used where I am using a standard browser (not-headless); I'd like to deselect those tests using a real, visual browser so that they don't trigger in my CI/CD pipeline. Given the example pytest.ini below if I run: pytest launcher it shows as I would expect that there is 1 test being deselected (the StandardBrowserTestCases class only has 1 test in it). However, if I run: pytest other_app (which also has a StandardBrowserTestCases class) it does not show anything being deselected and StandardBrowserTestCases is ran with the other tests and not deselected. [pytest] addopts = --nomigrations --cov-config=.coveragerc --cov=my_project --cov=other_app --cov=launcher --cov=people ; # Ignore the StandardBrowserTestCases - these are only used for local ; # development / visual debug and contain no real valuable tests --deselect=other_app/tests/test_integrations.py::StandardBrowserTestCases --deselect=launcher/tests/test_integrations.py::StandardBrowserTestCases --deselect=people/tests/test_integrations.py::StandardBrowserTestCases --junitxml=./test-results/junit.xml --cov-report html:./test-results/htmlcov --html=./test-results/test_results.html --self-contained-html DJANGO_SETTINGS_MODULE = my_project.unit-test-settings python_files = tests.py test_*.py *_tests.py Question(s): Am I using … -
Django child model with OneToOne parent does not inherit parent's fields?
I have a parent classs Dish and a child Pizza that inherits from Dish. They have a 1to1 relationship and I wrote them as follows: class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' PASTASALAD = 'PASTASALAD' PLATTER = 'PLATTER' TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') ) name = models.CharField(max_length=64, blank=True) type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True) size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=None) def __str__(self): return f"{self.name} {self.size} - Price: ${self.price}" class Pizza(Dish): dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pizza", parent_link=True) REGULAR = 'REGULAR' SICILIAN = 'SICILIAN' STYLE_CHOICES = ( (REGULAR, 'Regular'), (SICILIAN, 'Sicilian'),) style = models.CharField(max_length=7, choices=STYLE_CHOICES, default=REGULAR) topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)]) def __str__(self): return f"{self.size} {self.style} pizza with {self.topping_count} toppings: ${self.price}" Now I have a Dish object with ID=17 and a price of 21.95, type=Pizza, size=Small, type=Regular. I now try to create the corresponding Pizza object as follows: >>> parent=Dish.objects.get(pk=17) >>> new_17_pizza = Pizza(dish=parent, topping_count=2, style="Regular") >>> new_17_pizza.save() I would assume that all Dish fields and values are inherited, i.e. I don't have to repeat them, but I get: sqlite3.IntegrityError: NOT NULL constraint failed: orders_dish.price Why is that? I know I am not allowing blank=True for the price in Dish, but … -
Receiving "'hmset' with mapping of length 0" error
I want to store my session data on redis dataset. I have set SESSION_ENGINE = 'redis' in settings.py. Code for redis.py #redis.py from django.contrib.sessions.backends.base import SessionBase from django.utils.functional import cached_property from redis import Redis class SessionStore(SessionBase): @cached_property def _connection(self): return Redis( host='127.0.0.1', port='6379', db=0, decode_responses=True ) def load(self): return self._connection.hgetall(self.session_key) def exists(self, session_key): return self._connection.exists(session_key) def create(self): # Creates a new session in the database. self._session_key = self._get_new_session_key() self.save(must_create=True) self.modified = True def save(self, must_create=False): # Saves the session data. If `must_create` is True, # creates a new session object. Otherwise, only updates # an existing object and doesn't create one. if self.session_key is None: return self.create() data = self._get_session(no_load=must_create) session_key = self._get_or_create_session_key() self._connection.hmset(session_key, data) self._connection.expire(session_key, self.get_expiry_age()) def delete(self, session_key=None): # Deletes the session data under the session key. if session_key is None: if self.session_key is None: return session_key = self.session_key self._connection.delete(session_key) @classmethod def clear_expired(cls): # There is no need to remove expired sessions by hand # because Redis can do it automatically when # the session has expired. # We set expiration time in `save` method. pass I am receiving 'hmset' with mapping of length 0 error on accessing http://localhost:8000/admin in django. After removing SESSION_ENGINE='redis' I am not receiving … -
Is there a calendar module for Django in Bootstrap?
So I'm newbie in programming world. I've been looking for a calendar in my webpage, so that users can dynamically input their schedules on it. However I'm having hard time finding a fine module. There isn't much in pypi.org, lots of modules are quite outdated. Do you have any recommendations? Thanks a lot :) -
Customizing default auth form in Django for html template
I'm trying to use the CSS from an HTML template I downloaded online to work in my default Django login form, and I gather that to imbue {{ form.username }} with any styles, you must create a custom LoginView in forms.py and modify that as if it were any other form using attrs={}. I have already done what was suggested in this question before anyone says this is a duplicate. class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'input100', } )) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'input100', } )) The name of the CSS style I'm trying to apply to the username (and password) text fields is "input100" but the username and password don't seem to be affected by anything I'm putting in forms.py. In fact, even if I take out the username and password fields in the above file, it still works the same, so clearly changes to forms.py aren't reaching the template (but the template is using UserLoginForm fine as if I take the whole thing out it crashes). change to urls.py: urlpatterns = [ path('', subsmems, name='subsmems'), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path( 'login/', views.LoginView.as_view( authentication_form=UserLoginForm, ), name='login' ) ] html … -
Django payment gateway clone
I want to create payment gateway clone like paypal ,razorpay in django but there is no reference about this in internet.How should i create models?.Any clone for payment gateway but not integration in django?.Please help Sir/Mam. -
Using the attribute value from IntegerField in another object attribute
So I am trying to learn django, and I am trying to enable image resizing from an image uploaded which is then assigned to an object via admin. I am using the django-stdimage lib. The idea is an instance as follows can be summoned: class Website_Post(models.Model): title = models.TextField(default='Enter title') intro = models.TextField(default='Enter post') image_width = models.IntegerField(validators=[MaxValueValidator(1000), MinValueValidator(0)], default=300) image_height = models.IntegerField(validators=[MaxValueValidator(1000), MinValueValidator(0)], default=300) cover = StdImageField(upload_to='images/', variations={'full': {'width': image_width, 'height': image_height}},null=True) def __str__(self): return self.title And then in /admin the image proportions can be defined, with a max value and a min value, which is then applied to the selected image. My reasoning for this is that the StdImageField variations are not easily accessible once the object has been created, so this way they can adjusted, at least from the backend. However when running this code, the object cannot be created, as the following error is given: TypeError: '>' not supported between instances of 'int' and 'IntegerField' with the error at this point: @staticmethod def is_smaller(img, variation): return img.size[0] > variation['width'] \ # <--- error in this line or img.size[1] > variation['height'] which to me indicates that the IntegerField value does not appear as an integer when used in … -
Bitbucket pipeline mssql database set port
I have a bitbucket pipeline that must execute django unittests. Therefore, I need a test database which should be a SQL SERVER datbase. The pipeline looks like this: # This is a sample build configuration for Python. # Check our guides at https://confluence.atlassian.com/x/x4UWN for more examples. # Only use spaces to indent your .yml configuration. # ----- # You can specify a custom docker image from Docker Hub as your build environment. image: python:3.7.3 pipelines: branches: master: - step: name: Setup sql image: fabiang/sqlcmd script: - sqlcmd -S localhost -U sa -P $DB_PASSWORD services: - sqlserver - step: name: Run tests caches: - pip script: # Modify the commands below to build your repository. - python3 -m venv my_env - source my_env/bin/activate - apt-get update && apt-get install - pip3 install -r req-dev.txt - python3 manage.py test - step: name: Linter script: # Modify the commands below to build your repository. - pip3 install flake8 - flake8 --exclude=__init__.py migrations/ definitions: services: sqlserver: image: mcr.microsoft.com/mssql/server:2017-latest variables: ACCEPT_EULA: Y SA_PASSWORD: $DB_PASSWORD And everytime when I run the pipeline I get: Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired. Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server … -
correct sending emails with django
Hi i have a smal question i've got user register form that sets new users to inactive and send me(admin) mail that they are awaiting for approval everything works fine but email i recieve looks like it comes from me to me it doesn't show me email i provide in the form i can fix it by movig "form.email" to a mail body place and then it works but i want this to be displayed how it should be. i'. sending those emails from my localhost to my gmail account: Function def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() user.is_active = False user.save() form.username = form.cleaned_data['username'] form.email = form.cleaned_data['email'] try: send_mail(f'New User requests for approval to log in', f'You have a new user and he is awaiting for approve'+'\n\n'+'User name: '+ form.username, form.email, [EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You will be able to log in after Admin approval') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form, 'register': "active" }) -
django Multiple newtwork request to api cause unique violation error
So i have an API that takes a keyword and runs some logic, then inserts the data into Keyword table. The keyword model is: class Keyword(BaseModel): text = models.CharField(max_length=500, unique=True) key_id = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return my_unicode(self.text) Now due to some bug in my frontend js code a api request was getting sent two times on a button click(not a major issue). But in the backend during the processing of the keyword following code runs which was creating UniqueViolation error: def get_data_for_keyword(key, region_id, language_id): # key is the keyword text that we need to save into db which is coming from network request # Some code keyword = Keyword.objects.filter(text__iexact=key) if keyword.exists(): keyword = keyword[0] # some code else: keyword = Keyword(text=key) keyword.save() # some code Scenrio: Two request come with the same keyword(due to the js bug). Expected behaviour: Both request check the existence of that keyword in DB, the one that runs first doesn't find it in DB creates it and the other one finds it in DB and further processing happens. But whats happening is somehow both request are getting executed simultaneously and both when filtering are not finding that keyword and both are trying to … -
Reformat request data DRF to create multiple model instances
I want to create three model instances using only one serializer, from one POST request. I need to update order, order_info, order_contact The data I receive looks like this: { "longitude": "67.929655", "latitude": "34.263974", "amount_from_client": "2600.00", "address": "New York", "datetime_client": "2019-08-01 16:31:00", "city": "New York", "partner_name": "Partner", "text": "", "client_name": "Qwerty", "client_order_code": 2174206, "datetime_partner": "2019-08-01 16:31:00", "amount_to_partner": "2000.00", "delivery_address_comment": "", "created": "2019-08-01 16:31:00", "client_phone": "74789", "partner_phone": "9988", "client_id": 6, } and here is my serializers: class OrderDetailsCreateSerializer(serializers.ModelSerializer): order_info = OrderInfoSerializer(many=False) order_contact = OrderContactSerializer(many=False) client_id = serializers.IntegerField(write_only=True) class Meta: model = Order fields: Tuple = ( 'address', 'amount_from_client', 'amount_to_partner', 'client_order_code', 'text', 'order_info', 'order_contact', 'client_id', ) def create(self, validated_data): client = Client.objects.get(id=validated_data.pop('client_id')) order_info = validated_data.pop('order_info', None) order_contact = validated_data.pop('order_contact', None) order = Order.objects.create(**validated_data) OrderInfo.objects.create(**order_info, order=order, client=client) OrderContact.objects.create(**order_contact, order=order) return order class OrderInfoSerializer(serializers.ModelSerializer): class Meta: model = OrderInfo fields: Tuple = ( 'datetime_client', 'datetime_partner', 'created', 'client', ) class OrderContactSerializer(serializers.ModelSerializer): class Meta: model = OrderContact fields: Tuple = ( 'client_name', 'client_phone', 'partner_name', 'partner_phone', ) In order to send data to OrderDetailsCreateSerializer my data format should be like this: { "longitude": "67.929655", "latitude": "34.263974", "amount_from_client": "2600.00", "address": "New York", "city": "New York", "text": "", "client_order_code": 2174206, "amount_to_partner": "2000.00", "delivery_address_comment": "", "client_id": 6, "order_info": { "datetime_client": … -
How to access a models attributes in Django
I'm trying to show users the product variations that they have selected. While the code is working and saving the variation in the database, I am not being able to show them on my html page. This is what I've tried: My models.py: class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True) variation_type = models.CharField(max_length=120, choices=VAR_TYPES, default='Size') title = models.CharField(max_length=120, null=True, blank=True) price = models.FloatField(null=True, blank=True) is_available = models.BooleanField(default=True) objects = VariationManager() class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) My cart.html: {% for order_item in object.items.all %} <tbody> <tr> <th scope="row" class="border-0"> <div class="p-2"> <img src="{{ order_item.item.image_url }}" alt="" width="70" class="img-fluid rounded shadow-sm"> <div class="ml-3 d-inline-block align-middle"> <h5 class="mb-0"> <a href="{{ order_item.item.get_absolute_url }}" class="text-dark d-inline-block align-middle">{{ order_item.item.title }}</a> {% if order_item.variation.all %} <ul> {% for subitem in order_item.variation.all %} <li>{{ subitem.variation_type }} : {{ subitem.title }}</li> {% endfor %} </ul> {% endif %} </div> </div> </th> -
A problem with my ubuntu Linux text editor on the key word True and False
when i copy this default config of tinymce4 to text editor it shows no color change for the keyword True.TINYMCE_DEFAULT_CONFIG this is in black and rest all in rose color(default texteditor theme) but in sublime text of windows it shows a color different from all other parameters.for example in the below code ''' 'cleanup_on_startup': True, ''' i'm having True and clean_up_on_startup as same rose color..even reviewing the question in stackoverflow i'm getting a different color for true and false but not getting in my ubuntu linux text editor. ''' TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } ''' -
How does Django knows which template to render when?
I am on 4th chapter the book Django 3 by example and I noticed one thing that we are only creating views from Django's authentication framework but we are not telling those views which template to render when. For example, how does my application would know that it needs to only render the logged_out.html template when we try to access the logout view? If I try to change the name of the file from logged_out.html to loggedout.html then it takes me to the Django's admin logout page. Why? -
Drop down list of images from model django ModelForm
I have a form where a user can update their profile. I want the user to choose from a dropdown list of all the available profile pictures (a gallery of profile pictures from the ProfilePictures Model) which they want to be their profile picture. At the moment the form returns the string of the image url. How can i make the actual image be in the drop down so that a user can see all the images before choosing the one they want? Models.py class ProfilePicture(models.Model): image = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return f'{self.image.url}' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(default='🐥 Your Bio 🙈 🙉 🙊', max_length=200) pic = models.ForeignKey(ProfilePicture, on_delete=models.SET_DEFAULT, default='1') def __str__(self): return f'{self.user.username} Profile' Forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['bio','image','pic'] # widgets = { # 'pic': ImageField(), # } Image of the current dropdown list -
Stuck with reverse lookup for getting dates of each course in django 2.2
I am building a form that has a radio button, of course, and dropdown of dates on which course would take place. Should look like the image shown below Model.py class CourseModel(models.Model): """ Name and Id for each course conducting """ id = models.CharField( primary_key=True, max_length=10 ) name = models.CharField(max_length = 100) def __str__(self): return self.name class Meta: verbose_name = 'Course' verbose_name_plural = 'Courses' class DateModel(models.Model): """ Each Course can have many Dates """ start_date = models.DateField() end_date = models.DateField(null=True) course_id = models.ForeignKey( CourseModel, on_delete = models.SET_NULL, null = True, blank = False ) def __str__(self): return "{} - {}".format(self.start_date, self.end_date) class Meta: verbose_name = 'Date' verbose_name_plural = 'Dates' I have tried various methods in form for reverse lookup but no success. forms.py class ApplyForm(forms.Form): username = forms.CharField(required = True) .... phone_number = forms.CharField() # courses = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) # courses = forms.ModelChoiceField(widget=forms.RadioSelect, queryset = CourseModel.objects, empty_label=None ) # courses = forms.ModelChoiceField(queryset= CourseModel.objects) courses = forms.modelformset_factory(CourseModel, fields=('id', 'name',)) dates = forms.modelformset_factory(DateModel, fields=('start_date','end_date','course_id')) After reading a lot of StackOverflow forms, I found we have to use the reverse lookup to find out dates from course, therefore in forms.py I was trying to create a reverse lookup views.py def apply_page_copy(request): print(request.POST) form …