Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Q objects in unpacking arguments Django
I want to use a Q object while I'm unpacking arguments. So, I have an optional filter that only needs to filter CS_roles. So no users with CS roles are listed. I was thinking to do the filter like this: ~Q(roles__role=Role.CS) so my argument looks like: staff_arguments = {~Q(roles__role=Role.CS)} My filter is: site.users.all().filter(*staff_arguments,) When I do this, I still get users with CS roles. What am i doing wrong? -
Insert newline in django form using forms.py
I am making a login form in django. This is my forms.py: from django import forms from django.views.decorators.csrf import csrf_protect class loginForm(forms.Form): email_id = forms.CharField() password = forms.CharField(max_length=32, widget=forms.PasswordInput) forms.CharField(required=True) My question is, how can I insert a newline in between email_id and password? Because the page looks like this: Thanks in advance. -
Sorting querysets by annotated field of reverse relation
I have 2 models, Form and Row, Each Row has a FK to a Form. I want to sort my Forms by the time of last row addition. class Form(models.Model): ... class Row(models.Model): form = models.ForeignKey( Form, related_name="rows", ) created_at = models.DateTimeField( auto_now_add=True, ) I tried this but it doesnt work: queryset = Form.objects.filter(is_empty=False) queryset = queryset.annotate(last_submit=Max("rows__created_at")) -
Django problem: views.py called twice, variables overridden
I use django to process users data in json recieved thru typeform's api(a google forms-like service). After submitting their typeforms, users are redirected to my django server which passes processed data to a link of a landing page where users' scores are displayed. This worked for a while, but after a lot of back and forth with different verisons of my algorithm, the views.py function is called twice. What's even weirder - the variables get overridden, which shouldnt be possible concering the sctructure of my code. Each score in the list below shouldn't be higher than 40, but it gets multiplied. After I reset the server it's good again but only for one GET request, then it gets messy again regardless whether its the same user's email(used for identifying his/hers submit data) or a different one. This is how it looks in my console: Django version 3.0.3, using settings 'demo_server.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. # First request: user's scores: [['A', 30], ['R', 24], ['E', 20], ['I', 16], ['S', 16], ['C', 14]] {correct link} [04/May/2020 15:01:23] "GET /typeform/dan@hiry.pl HTTP/1.1" 302 0 # Second request: user's scores: [['A', 100], ['R', 82], ['E', 70], ['I', 58], ['S', … -
A field in Django Model has white space. How can I strip it right in the model? I am not using it in form
So, post-uploading my CSV to Django model, I was querying. That's when I got a Zero Division Error in one of my fields which is based on the filter. The filter is a CharField. That has whitespace but of course, Django returns a stripped version of the string when passed through a form. However, it is not a ModelForm. Two Ways: 1) When it brings back the value after hitting submit on the form, it shouldn't strip. (But it isn't a ModelForm) 2) Trim the white space in the CharField in the Model itself. Either of these I have no idea how to do. Can someone help me here? -
Django - ModuleNotFoundError (basic app to print Hello in browser)
I'm new to django so take me easy. I'm just following some youtube tutorials and try to make a simple app to print Hello on the browser with django. And I keep getting this error in the urls.py file ModuleNotFoundError: No module named 'app' I get this error in urls.py file of my project which is bellow: urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app.urls')), path('admin/', admin.site.urls), ] I also made an app called app app\urls.py from django.urls import path import views urlpatterns = [ path('', views.home, name = 'home'), ] app\views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Hello!') I read I think all threads on this topic and nothing helped so far and I can't realise where's my mistake or what I did wrong. -
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 …