Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static css and images not loading in django
I am new to Django. I ran the project in Debug = True at that time all CSS and images are loading properly. I try to change Debug = False. Now I face problems. Sometimes CSS is not loading . some times images are not loading. I have two images in the folder. One is loading and the other is not loading. In Develop mode Debug = True at that time is working properly. I try to restart using python3 manage.py runserver change STATIC_URL = "../../static/" But above changes are not working Some images loaded something not loaded settings.py STATIC_URL = "/static/" STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] mysite/static/images/icon/1.png //come mysite/static/images/icon/2.png //not come both 1.png and 2.png are in folder sometimes CSS is loading. sometimes it is not loading I am using python3 manage.py runserver 0.0.0.0:5000 to start the project -
Django Forms - Validation error shown twice
I want to show up some validation errors for each fields in the form. If email already already exists If username is less than 8 characters If passwords don't match If password field is less than 8 characters forms.py class RegisterForm(forms.Form): username = forms.CharField(widget = forms.TextInput(attrs ={"class":"form-control mb-2 mr-sm-2" ,"placeholder":"username"})) email = forms.EmailField(widget = forms.TextInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) password = forms.CharField(widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) password2 = forms.CharField(label = "Confirm Password",widget = forms.PasswordInput(attrs = {"class":"form-control mb-2 mr-sm-2"})) def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2!=password: raise forms.ValidationError("Passwords dont match") if len(password)<8: raise forms.ValidationError("Password must be atleast 8 characters long") return data def clean_username(self): username = self.cleaned_data.get('username') qs = User.objects.filter(username = username) if qs.exists(): raise forms.ValidationError("username exists") return username def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email = email) if qs.exists(): raise forms.ValidationError("email exists",code="error1") return email''' register.html <form method="POST" class="was-validated"> {% csrf_token %} <div class="form-group"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {%endif%} {{form.as_p}} </div> … -
Django - Translation default language change problem
I have two languages which is 'en' and 'tr'. In settings.py i changed the LANGUAGE_CODE to 'en'. Site loading in english this works fine. But my site url doesn't contain mysite/en and language dropdown value is not en. Both are 'tr' how can i change the default language to en? Thanks.. -
problem on delete TypeError: __init__() missing 1 required positional argument: 'on_delete'
i am working with django on pychrm, i have tested a project and everything is working, but when i tried to use another project and go back to the first project i have this error there, knowing that i have used the same version of django==1.9.5 test = models.ForeignKey(Test) TypeError: __init__() missing 1 required positional argument: 'on_delete' so where is the problem? I don't want to change anything in code, I want to change just of packages if there is a problem in package -
Why cant i write a data record without foreign-key with a model which contains a nullable foreign-key?
I have consulted the django documenation which says if you want a foreign key which can be optional you need the following options to be set on the model: on_delete=models.SET_NULL, blank=True, null=True, default=None I dropped the complete database, checked the field in MYSql admin. The field is correctly set to optinally contain NULL values. Could anyone explain why this is happening or what im doing wrong? Model: Model: class MediaImage(models.Model): class Meta: verbose_name = _("Image") verbose_name_plural = _('Image') date_created = models.DateTimeField(auto_now_add=True) date_changed = models.DateTimeField(auto_now=True, auto_now_add=False) content = models.FileField(upload_to=person_directory_path, storage=private_storage, verbose_name=_("Image")) title = models.CharField(max_length=50, verbose_name=_("Titel"), blank=True) classification = models.CharField(max_length=10, default="image") person = models.ForeignKey(Person, on_delete=models.SET_NULL, blank=True, null=True, default=None) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("User")) View: @login_required def mediafiles_add_image(request): if request.method == "POST": form = MediafilesAddImage(request.user, request.POST, request.FILES) if form.is_valid(): image_file = request.FILES['content'] if request.POST['person_id']: ImageFile = MediaImage(content=image_file, person_id=request.POST['person_id'], title=request.POST['title'], user_id=request.user) else: ImageFile = MediaImage(content=image_file, title=request.POST['title'], user_id=request.user) ImageFile.save() return redirect('mediafiles') else: form = MediafilesAddImage(request.user) return render(request, 'mediafiles/mediafiles_add_image.html', {'form': form}) return HttpResponseForbidden('Something went wrong.') The error occurs on the line: ImageFile.save() The record should be normally saved here but im getting error: AttributeError at /admin/datawarehouse/mediaimage/add/ 'NoneType' object has no attribute 'id' -
Query set with OuterRef
While the result is the expected outcome it feels like I use lots of nesting. Especially that I used Ticket and not Event for total_outstanding_revenue. I wonder if you have a better and shorter way to write that query? My query set gives me the following result: total_outstanding_revenue: <QuerySet [{'event__pk': 4, 'total_outstanding_revenue': 56000}, {'event__pk': 5, 'total_outstanding_revenue': 9000}, {'event__pk': 6, 'total_outstanding_revenue': 29000}]> Here my query set: outstanding_revenue = ( Ticket.objects.filter(pk=OuterRef('pk')) .annotate( sold_tickets=Count( 'attendees', filter=Q( attendees__canceled=False, attendees__order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE ), ), ) ) .annotate( available_tickets=ExpressionWrapper( F('quantity') - F('sold_tickets'), output_field=IntegerField() ) ) .annotate( outstanding_revenue=ExpressionWrapper( F('available_tickets') * F('price_gross'), output_field=IntegerField() ) ) .values('outstanding_revenue') ) total_outstanding_revenue = Ticket.objects.filter(event__organizer=1, event__status=EventStatus.LIVE).annotate( outstanding_revenue=Subquery(outstanding_revenue)).values( 'event__pk' ).annotate(total_outstanding_revenue=Sum('outstanding_revenue', output_field=IntegerField())).values( 'event__pk', 'total_outstanding_revenue' ).order_by() -
Django: Combining two for loops
Is there a way to combine the two for loops into one? I was looking for a solution like this. But it didn't work that way: ticket_stats_by_event = { x['pk']: {'sold_tickets': x['sold_tickets'], 'available_tickets: y['avaiable_tickets']} for x, y in sold_tickets_by_event, available_tickets_by_event } The result will be: <EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]> Here the full function: def ticket_stats_by_event(self, organizer): sold_tickets_by_event = [ x for x in self.sold_tickets if x['organizer'] == organizer.pk ] # <EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]> available_tickets_by_event = [ x for x in self.available_tickets if x['organizer'] == organizer.pk ] # <EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]> ticket_stats_by_event = { x['pk']: {'sold_tickets': x['sold_tickets']} for x in sold_tickets_by_event } for item in available_tickets_by_event: pk = item.pop('pk') ticket_stats_by_event[pk].update(item) return ticket_stats_by_event -
"error readlink /var/lib/docker/overlay2 invalid argument" when I run docker-compose up
I'm trying to dockerize project written in django and postgresql. What I've already done: I have environment variables stores in env_file: SECRET_KEY=value DEBUG=value ALLOWED_HOSTS=['192.168.99.100'] DB_NAME=postgres DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 My Dockerfile: FROM python:3.7-stretch ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt /code/ WORKDIR /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml file: version: '3' services: db: image: postgres:11-alpine restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_PASSWORD: postgres container_name: "my_postgres" ports: - "5432:5432" web: build: . command: python /code/cameo/manage.py runserver 0.0.0.0:8000 volumes: - .:/code/ env_file: - env_file ports: - "8000:8000" depends_on: - db volumes: postgres_data: Please help, I don't know what I'm doing wrong. -
How to delete unnecessary import from entire project
I found some stackoverflow solution and they didn't satisfy me -- please don't recommend those link.. I have a django project with more than thousand of python file and i want to delete all the unused or unnecessary import from those file in single command. i want to delete those in just single command. is the any way to delete those? -
How to fix "Invalid password format or unknown hashing algorithm." in a custom User Model Django
models.py class UserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Please provide a valid Phone') user = self.model( phone = phone, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user phone_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Phone number should be in the format '+9999999999', Up to 14 digits allowed.") class User(AbstractBaseUser): phone = models.CharField(validators=[phone_regex],max_length=15,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active admin.py class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('phone',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: … -
when webdriver can’t find elem,Failed to establish a new connection
when i use WebDriverWait and can't find the elem,it reminds me urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7fde08091f98>: Failed to establish a new connection: [Errno 111] Connection refused Here is my code: elem = WebDriverWait(driver,time_len).until(EC.presence_of_element_located((By.XPATH, xpath))) error: INFO isElementExist common 2019-06-21 18:32:44,099 //*[@id="phone-state"]元素查找出错 HTTPConnectionPool(host='127.0.0.1', port=39243): Max retries exceeded with url: /session/7512e5500bbe03e5d8d6490081733642/element (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fde08091f98>: Failed to establish a new connection: [Errno 111] Connection refused')) INFO isElementExist common 2019-06-21 18:32:44,100 traceback.format_exc(): Traceback (most recent call last): File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 160, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "/usr/local/python3/lib/python3.7/site-packages/urllib3/util/connection.py", line 80, in create_connection raise err File "/usr/local/python3/lib/python3.7/site-packages/urllib3/util/connection.py", line 70, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 603, in urlopen chunked=chunked) File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 355, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/local/python3/lib/python3.7/http/client.py", line 1229, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1275, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1224, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/local/python3/lib/python3.7/http/client.py", line 1016, in _send_output self.send(msg) File "/usr/local/python3/lib/python3.7/http/client.py", line 956, in send self.connect() File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 183, in connect conn = self._new_conn() File "/usr/local/python3/lib/python3.7/site-packages/urllib3/connection.py", line 169, in _new_conn self, "Failed to establish a new connection: %s" … -
dynamically add js variable value in django template url with appname and namespace
I have multiple apps in project and using appname and namespace for urls. I need to dynamically add js variable value in django template url with app name. If I write without appname like -- var temp =23 var href = "{% url 'report_page' id=0 %}".replace(/0/, temp.toString()) It is giving desired result as-- "{% url 'report_page' location_id=23 %}" But when I use appname its not working for me e.g var href = "{% url 'appname : report_page' id=0 %}".replace(/0/, temp.toString()) Let me give you the exact code: In django template: <html> <a href="{% url 'appname : report_page' id=0 %}">Report</a> </html> var href = "{% url 'appname : report_page' id=0 %}".replace(/0/, temp.toString()) In url.py of the appname: appname = 'appname' urlpatterns = [ url(r'^report-page$', views.report_page, name='report_page'), url(r'^report-page/(?P<id>[0-9]+)$', views.report_page, name='report_page'), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In views: def report_page(request): import pdb;pdb.set_trace() # location_id = request.GET['id'] return render( request, 'report.html', {'id' : request.user.id, 'id' : ''} ) Note: I'm using django 1.11 and I have also tried below one but getting empty string: var temp =$('#check_id').val() <a href="{% url 'appname: report_page' %}?id="+temp;>Report</a> -
Sentry not receiving exceptions
I recently started using sentry for my Django Project. Everything was working fine in the development environment, but when i pushed it to prod, even though exception were getting thrown, but sentry wasn't reporting them on the dashboard. I tried enabling the debug setting in sentry config, and in the logs it said "Sending error event", but the event is still not being received. Can someone help with this issue? Python - 3.6.7 Sentry-sdk - 0.9.0 -
Facing connectionError in django while using ElasticSearch with docker
I am trying to load instances from my django model to the elasticsearch server but i get the error - elasticsearch.exceptions.ConnectionError: ConnectionError(: Failed to establish a new connection: [Errno -8] Servname not supported for ai_socktype) caused by: NewConnectionError(: Failed to establish a new connection: [Errno -8] Servname not supported for ai_socktype) I have established an instance of elasticsearch server using docker on my localhost on port 9200 using command - docker run -d -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:6.0.0 I am able to access the server using the curl/localhost plz help. Thanks in advance -
How to implement pagination in a Django and React App without using the rest framework?
I am working on a website whose back-end is in Django and front-end is developed using React.I want to add the pagination feature in the website but don't know how it will be implemented in the frontend part. Also I am not using REST framework to develop the back-end site. I want to know what all information I have to send to the React front-end site for this to work. How should I proceed? -
How to auto delete Web Scraper duplicate data in Django
I have a webscrapper in python. It's saving the result in a django model thus when I refresh the page it runs the webscrapper duplicating the already existing data. I tried to remove the data by using the list(dict.fromkeys (my2) ) function but no use. views.py def Scrappy(request): session = requests.Session() session.headers = { "User-Agent": 'User-Agent'} url = 'https://www.google.com/blog/' content = session.get(url, verify=False,).content soup = BeautifulSoup(content, "html.parser") obj1 = soup.find_all( 'div', {'class': 'td_module_3 td_module_wrap td-animation-stack'}) obj2 = soup.find_all( 'div', {'class': 'td_module_10 td_module_wrap td-animation-stack'}) for x in obj1: linkX = x.find('a', {'class': 'td-image-wrap'}) #saving the fetched data into variables link_x = linkX.get('href') title_x = linkX.get('title') img_src_x = x.find('img', {'class': 'entry-thumb'})['src'] link_x.replace(u"\u2019", "-") link_x.decode('utf-16', 'ignore') img_src_x.replace(u"\u2019", "-") img_src_x.decode('utf-16', 'ignore') new_Web = WebScraper() new_Web.web_title = title_x new_Web.web_url = str(link_x) new_Web.my_img = str(img_src_x) try: my = {new_Web} my = list(dict.fromkeys(my)) new_Web.save() except: pass # new_Web.save() for y in obj2: linkY = y.find('a', {'class': 'td-image-wrap'}) #saving the fetched data into variables link_y = linkY.get('href') title_y = linkY.get('title') img_src_y = y.find('img', {'class': 'entry-thumb'})['src'] img_src_y.replace(u"\u2019", "-") img_src_y.decode('utf-16', 'ignore') link_y.replace(u"\u2019", "-") link_y.decode('utf-16', 'ignore') new_Web2 = WebScraper() new_Web2.web_title = title_y new_Web2.web_url = str(link_y) new_Web2.my_img = str(img_src_y) try: my2 = ["new_Web2"] my2 = list(dict.fromkeys(my2)) new_Web2.save() except: pass # new_Web2.save() return … -
How to move a selected object in a form from one view to another?
I'm new in Django, I hope you can help me. I have a model named Derogation with 3 ForeignKey. I have 2 forms (with each one or two ModelChoiceField) spread across multiple views. In a final view, I would like to recover all these instances to create a Derogation object and save it in the database. I tried to pass the objects trough urls but i'm not sure how it works. I don't want to use the sessions. models.py class Derogation(models.Model): createur = models.ForeignKey(Createur, on_delete=models.CASCADE) individu = models.ForeignKey(Individu, on_delete=models.CASCADE) raison = models.ForeignKey(Raison, on_delete=models.CASCADE) forms.py class IndividuForm(forms.Form): individu = forms.ModelChoiceField(queryset=Individu.objects.order_by('nom'), empty_label="") class RaisonForm(forms.Form): raison = forms.ModelChoiceField(queryset=Raison.objects.all(), empty_label="") class CreateurForm(forms.Form): createur = forms.ModelChoiceField(queryset=Createur.objects.all(), empty_label="") views.py def index(request): individu_form = IndividuForm(request.POST or None) if individu_form.is_valid(): individu = individu_form() return HttpResponseRedirect('/raison/%s' % individu) #Not sure return render(request, 'derog_bv/index.html', {'individu_form':individu_form}) def raison(request, individu): raison_form = RaisonForm(request.POST or None) createur_form = CreateurForm(request.POST or None) if raison_form.is_valid() and createur_form.is_valid(): raison = raison_form() createur = createur_form() return HttpResponseRedirect('/recap/%s%s%s' %individu %raison %createur) #really not sure return render(request, 'derog_bv/raison.html', {'raison_form':raison_form}) def recap(request, individu, raison, createur): #Here I want to save my Derogation object return render(request, 'derog_bv/recap.html') -
How to filter results from ansible tower api query
Using postman, I need to only show results where name=TestWorkflow Here are results returned for my query: Get http://ansible-awx.pxdtools.io:8000/api/v2/workflow_job_template_nodes/ { "results": [ { "id": 1323, "summary_fields": { "workflow_job_template": { "id": 121, "name": "TestWorkflow", } } }, { "id": 29, "summary_fields": { "workflow_job_template": { "id": 61, "name": "Livraison en TEST", }, } } ] } i already tried many of these filters : https://docs.ansible.com/ansible-tower/latest/html/towerapi/filtering.html This query does not work because name is inside results/summary_fields Get http://ansible-awx.pxdtools.io:8000/api/v2/workflow_job_template_nodes/?name=TestWorkflow { "detail": "WorkflowJobTemplateNode has no field named 'name'" } the expected results i want will be { "results": [ { "id": 1323, "summary_fields": { "workflow_job_template": { "id": 121, "name": "TestWorkflow", } } } ] } -
What should I do to render profile.html with form have information of 2 tables in database?
I had a extended table from User model in Django is userinfo. I created form with list of field: 'first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone_number', 'email'. And I had a trouble with model in Meta class in forms.py UserInfo Model class UserInfor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField() gender = models.CharField(max_length=10) address = models.CharField(max_length=255) phone_number = models.CharField(max_length=10) avatar = models.ImageField(upload_to='profile-image', blank=True) def __str__(self): return self.user.username forms.py from django import forms from django.forms import ModelForm from .models import UserInfor, User class ProfileForm(ModelForm): class Meta: model = User, UserInfor fields = ['first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'phone_number', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}), 'last_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Last Name', 'class': ' form-control input-md'}), 'date_of_birth': forms.DateInput(attrs={'placeholder': 'Date of Birth', 'class': 'form-control input-md'}), 'gender': forms.RadioSelect(choices=[('nam', 'Nam'), ('nữ', 'Nữ'), ('khác', 'Khác')]), 'address': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Address', 'class': 'form-control input-md'}), 'phone_number': forms.TextInput(attrs={'placeholder': 'Phone Number', 'class': 'form-control input-md'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control input-md'}), } labels = { 'first_name': "Họ", 'last_name': "Tên", 'date_of_birth': "Ngày sinh", 'gender': "Giới tính", 'address': "Địa chỉ", 'phone_number': "Số điện thoại", 'email': "Email", } -
Django: .annotate gives back unexpected results
Currently, I have these two query sets: ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate( sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') ) ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate(available_tickets=Coalesce(Sum('tickets__quantity'), 0)) .order_by('organizer') ) Results are: <EventQuerySet [{'pk': 6, 'organizer': 1, 'sold_tickets': 1}, {'pk': 1, 'organizer': 1, 'sold_tickets': 529}, {'pk': 5, 'organizer': 1, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'sold_tickets': 2}]> <EventQuerySet [{'pk': 1, 'organizer': 1, 'available_tickets': 1721}, {'pk': 4, 'organizer': 1, 'available_tickets': 30}, {'pk': 5, 'organizer': 1, 'available_tickets': 10}, {'pk': 6, 'organizer': 1, 'available_tickets': 20}]> Now my idea was to combine these. However, I always get unexpected and wrong numbers in my query: ( Event.objects.filter(organizer=1) .values('pk', 'organizer') .annotate( available_tickets=Coalesce(Sum('tickets__quantity'), 0), sold_tickets=Count('attendees', filter=Q(attendees__canceled=False)) ) .order_by('organizer') ) Here the result <EventQuerySet [{'pk': 6, 'organizer': 1, 'available_tickets': 20, 'sold_tickets': 2}, {'pk': 1, 'organizer': 1, 'available_tickets': 1765746, 'sold_tickets': 2116}, {'pk': 5, 'organizer': 1, 'available_tickets': 10, 'sold_tickets': 1}, {'pk': 4, 'organizer': 1, 'available_tickets': 60, 'sold_tickets': 4}]> Is there something about .annotate that I don't understand? -
django - primary key in search_fields?
I have thousands of objects for a django model in my database and I want to be able to search by primary key. I know I can just go to /admin/my_app/my_model/pk/ to enter into the admin for that particular object, but I want to be able to see it in the search results, to see all the display fields. When I add 'pk' or 'id' to the search_fields, I get this error: Cannot resolve keyword 'pk' into field. Choices are: ... So I'm guessing it's not possible straight away but wonder if there is a workaround? -
Error during template rendering: __str__ returned non-string (type NoneType)
I have a problem I can have the rendering of all the pages with my database empty. But when I introduce data I have a problem: Error during rendering template str returned non-string (type NoneType). below one of the codes that generate this type of error at line of render. Thank you in advance. models.py class Filiere(models.Model): departement=models.ForeignKey( "Departement", verbose_name="Département", on_delete=models.CASCADE) code_filiere=models.CharField("Code de la filière", max_length=10, unique=True) libelle_filiere=models.CharField("Libellé de la filière", max_length=100) def __str__(self): self.libelle_filiere #Description d'une option class Option(models.Model): filiere=models.ForeignKey("Filiere", on_delete=models.CASCADE, verbose_name='Filière') niveau=models.ManyToManyField("niveau", through='Posseder_Niveau') code_option=models.CharField("Code de l'option", max_length=6,unique=True,) libelle_option= models.CharField("Libelle de l'option", max_length=100) effectif=models.IntegerField("Effectif", default=0, validators=[ MinValueValidator(limit_value=0 , message=" Attention votre option a un effectif négatif"), ]) def __str__(self): return self.libelle_option class Posseder_Niveau(models.Model): niveau=models.ForeignKey("Niveau", on_delete=models.CASCADE) option=models.ForeignKey("Option", on_delete=models.CASCADE) class Niveau(models.Model): libelle_niveau=models.CharField("Libellé du niveau", max_length=25, unique=True) semestre=models.ManyToManyField("Semestre", through="Posseder_Semestre") cursus=models.ForeignKey('Cursus', on_delete=models.CASCADE) def __str__(self): self.libelle_niveau forms.py class Option_Form(forms.ModelForm): class Meta: model=Option # exclude=("niveau",) fields='__all__' def __init__(self, *args,**kwargs): super().__init__(*args, **kwargs) for _, value in self.fields.items(): value.widget.attrs['placeholder']=value.label value.widget.attrs['class'] = 'form-control required' views.py def option(request): # import ipdb; ipdb.set_trace() f=Option_Form() if request.method=="POST": f=Option_Form(request.POST) if f.is_valid(): f.save() else: return render(request, 'configuration/ajout_option.html', {'f': f}) traceback C:\Program Files\Python37\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Program Files\Python37\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars … -
In Django model, how to save DateTime for two different timezones at the same time when saving one field with auto_now_add = True option?
I am a Django model which has an auto current time saving DateTime field. I want to add another DateTime field for another timezone which time difference with the previous DateTime field is exact time difference between two time zones. This is how I have done. I think there should be better way to get it done. It's Django, right? class IcecreamManager(models.Manager): def create_icecream(self, name=None, qty=None): icecream = self.create(name=name, qty=qty) icecream.create_date_kr = buy.create_date + datetime.timedelta(hours=9) icecream.save() return iceream class Icecream(models.Model): name = models.CharField(max_length=100) qty = models.IntegerField(default=0) create_date = models.DateTimeField(auto_now_add=True) create_date_kr = models.DateTimeField(null=True) objects = BuyFourManager() >>> Icecream.objects.create_icecream(name='Vanila', qty=3) -
Django: Check multiple conditions before save model
This is my models.py: class Department(models.Model): name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Department') def __str__(self): return '{}'.format(self.name) class Users(models.Model): name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Name') last_name = models.CharField(max_length=20, blank=False, null=False, verbose_name='Last Name') department = models.ForeignKey(Department, related_name='user_department', on_delete=models.CASCADE) def __str__(self): return '{} {} - {}'.format(self.name, self.last_name, self.department) class WeeklyCheck(models.Model): department = models.ForeignKey(Department, related_name='weeklycheck_department', on_delete=models.CASCADE) start_date = models.DateField(blank=False, null=True, verbose_name='Start date') end_date = models.DateField(blank=False, null=True, verbose_name='End Date') active = models.BooleanField(default=True, verbose_name='Active?') def __str__(self): return '{} / {} to {} - {}'.format(self.department, self.start_date, self.end_date, self.active) class Attendance(models.Model): user = models.ForeignKey(Users, related_name='attendance_user', on_delete=models.CASCADE) date = models.DateField(blank=False, null=True, verbose_name='Date') check = models.BooleanField(default=True, verbose_name='Check') def __str__(self): return '{} / {} / {}'.format(self.user, self.date, self.check) def clean(self): qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_a = Users.objects.filter(department__name='Department A') if not qs and department_a: qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_b = Users.objects.filter(department__name='Department B') if not qs and department_b: qs = WeeklyCheck.objects.filter(start_date__lte=self.date, end_date__gte=self.date, active=True) department_c = Users.objects.filter(department__name='Department C') if not qs and department_c: raise ValidationError('You can not check! The week is not active.') I have departments (Department) that have users (Users). Each department marks weeks (WeeklyCheck) that have a start date and end date and may or may not be active. Each user checks on a certain date (Attendance). What I want … -
re.findall() returning empty tuples [duplicate]
This question already has an answer here: re.findall behaves weird 2 answers I have a regex '[-][0-9],\s*[0-9]*(?!(km)|(Km)|(metres?)|(miles?)|(m)|(mi))'. When I use this on regexr.com it matches '558,21' and other patterns. but if I am using re.findall() in python re.findall( '[-]*[0-9]*,\s*[0-9]*(?!(km)|(Km)|(metres?)|(miles?)|(m)|(mi))' , text) it is returning me this as the output even though '558,21' is present in text variable: [('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', ''), ('', '', '', '', '', '')] What might be the reason for it?