Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-tenants create user in a tenant only
I am currently setting up Django Tenants (https://django-tenants.readthedocs.io/en/latest/) with the Saleor Web Framework (https://github.com/mirumee/saleor-platform). I've managed to get the Saleor GraphQL endpoints up and running for two different sites. However, my users have to be created using the public schema or the login process does not work. For instance if run ./manage.py create_tenant --domain-domain=newtenant.net --schema_name=new_tenant --email=new@gmail.com this doesn't work. But running ./manage.py create_tenant --domain-domain=newtenant.net --schema_name=public --email=new@gmail.com works. The problem with creating in the public schema is that the created user will have access to all of the tenants. Extract from my settings.py SHARED_APPS = [ "django_tenants", "saleor.clients", # Django modules "django.contrib.contenttypes", "django.contrib.sites", "django.contrib.staticfiles", "django.contrib.auth", "django.contrib.postgres", "storages", # Local apps "saleor.plugins", "saleor.account", "saleor.discount", "saleor.giftcard", "saleor.product", "saleor.checkout", "saleor.core", "saleor.graphql", "saleor.menu", "saleor.order", "saleor.seo", "saleor.shipping", "saleor.search", "saleor.site", ] TENANT_APPS = ( # The following Django contrib apps must be in TENANT_APPS "django.contrib.contenttypes", "django.contrib.sites", "django.contrib.staticfiles", "django.contrib.auth", "django.contrib.postgres", "storages", # Django modules # Local apps "saleor.plugins", "saleor.account", "saleor.discount", "saleor.giftcard", "saleor.product", "saleor.checkout", "saleor.core", "saleor.graphql", "saleor.menu", "saleor.order", "saleor.seo", "saleor.shipping", "saleor.search", "saleor.site", "saleor.data_feeds", "saleor.page", "saleor.payment", "saleor.warehouse", "saleor.webhook", "saleor.wishlist", "saleor.app", # External apps "versatileimagefield", "django_measurement", "django_prices", "django_prices_openexchangerates", "django_prices_vatlayer", "graphene_django", "mptt", "django_countries", "django_filters", "phonenumber_field", ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = … -
TypeError: expected str, bytes or os.PathLike object, not tuple in Django
I am getting an error TypeError: expected str, bytes or os.PathLike object, not tuple many times tried different ways from the internet nothing worked. Could anyone help me with this problem. Here is my template part in settings.py file : from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIRS = (os.path.join(BASE_DIR / 'templates'), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIRS,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Why don't I get the Correct Result out of my Django Paginator
I am trying to create paginated pages in this view def all_users(request): users = Person.objects.all() pag = Paginator(users, 3) page_num = request.GET.get('page') page_obj = pag.get_page(page_num) context = { 'users': users, 'title': 'All Users', 'page_obj': page_obj } return render(request, 'index/users.html', context) Here is users.html : {%extends 'index/base.html'%} {%block content%} <section class="all-users"> {%for user in users%} <article> <h1 class="username">{{user.username}}</h1> <hr> <p><b>Email: </b><span class="email" class="">{{user.email}}</span></p> <p><b>FirstName: </b><span class="first-name" class="">{{user.first_name}}</span></p> <p><b>LastName: </b><span class="last-name" class="">{{user.last_name}}</span></p> <p><b>Joined on: </b>{{user.date_joined}}</p> {%if is_staff%} <p>{{user.username} is a staff member</p> {%else%} <p><span class="full-name">{{user.first_name}} {{user.last_name}}</span>, a.k.a {{user.username}} is a normal member</p> {%endif%} </article> {%endfor%} </section> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> <script type="text/javascript"> let users = '{{users}}' for(let username of document.getElementsByClassName('username')){ if (username.textContent.length >= 15 && username.textContent.length <= 20 ){ username.style.fontSize = '30px' }else if (username.textContent.length >= 11 && username.textContent.length <= 14 ){ username.style.fontSize = '45px' } } </script> {%endblock content%} as you can see in the paginator i want three users per page but that doesn't even work I … -
Jquery/Ajax function does not work when clicking on icon for Django site
I have a script for an ajax request using jquery which acts to upvote a post on my django site. It works fine when I click on the part with the word "upvote", but when I click on my upvote icon, it doesn't register and shows 404 not found in console. I suspect this has something to do with document and not being able to act on icons. Could anyone help me identify the issue, or know a workaround? Below is my code and picture of error, thanks! template.html <form action="{% url 'main:upvote-post' %}" method=POST> {% csrf_token %} <!-- check to see if user has already upvoted post.--> <span> {% if post.upvoted %} <button type="submit" class="btn btn-success btn-sm upvote-btn card-link" id={{post.id}} name="post_id" value={{post.id}}> <svg width="1.5em" height="1.5em" viewBox="0 0 16 16" class="bi bi-shift" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M7.27 2.047a1 1 0 0 1 1.46 0l6.345 6.77c.6.638.146 1.683-.73 1.683H11.5v3a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1v-3H1.654C.78 10.5.326 9.455.924 8.816L7.27 2.047zM14.346 9.5L8 2.731 1.654 9.5H4.5a1 1 0 0 1 1 1v3h5v-3a1 1 0 0 1 1-1h2.846z"/> </svg> <span id="total_upvotes_for_{{post.id}}"> <!-- insert post id into the element here so it could be called in the script --> {{ post.total_upvotes}} </span> Upvotes </button> … -
Keeping field values on Form fields after request.GET - but also passing other kwargs
I have this form: class TaskSelectForm(forms.Form): def __init__(self, *args, **kwargs): # department = kwargs.pop('department') super(TaskSelectForm, self).__init__(*args, **kwargs) (...) I can call the form in my view with something like this: TaskSelectForm(request.GET) and it'll work fine. When i make a GET request the page loads and the fields are still filed.. Just as expected However, i need the form to take an extra parameter, something like this TaskSelectForm(request.GET, department = department) Problem is that for every GET request the form fields become empty. The form doesn't retain the values from the last request. I want the form fields to keep the last values.. How can i achieve this? I'll post the whole code below just to make sure i didn't mess up: class TaskSelectForm(forms.Form): def __init__(self, *args, **kwargs): department = kwargs.pop('department') super(TaskSelectForm, self).__init__(*args, **kwargs) department_tasks = Task.objects.filter(department = department) distinct_cr = [(k['client_repr'], k['client_repr']) for k in department_tasks.values('client_repr').distinct()] distinct_td = [(k['task_description'], k['task_description']) for k in department_tasks.values('task_description').distinct()] distinct_us = [(x.id, (str(x))) for x in department.users.all()] for _ in [distinct_cr, distinct_td, distinct_us]: _.sort(key = lambda x: x[0]) _.insert(0, ('', '---------')) self.fields['client_repr'] = forms.ChoiceField(choices = distinct_cr, required = False) self.fields['task_description'] = forms.ChoiceField(choices = distinct_td, required = False) self.fields['from'] = forms.DateField(widget = forms.DateInput()) self.fields['to'] = forms.DateField(widget … -
how can I retrieve my data from jsonreponse without index?
I am trying to send the data in a simple jsonview without an index instead of having an index , my view is really simple where I dont need to use an django DRF {"reviews": [{"id": 2, "enrollment_id": 28, "rating_score": 3, "comments": "11111111111111", "created_at": "2020-09-20T03:52:12.811Z", "updated_at": "2020-09-20T03:52:12.811Z"}]} , but I am trying to have [{"id": 2, "enrollment_id": 28, "rating_score": 3, "comments": "11111111111111", "created_at": "2020-09-20T03:52:12.811Z", "updated_at": "2020-09-20T03:52:12.811Z"}] class StudentJsonView(View): def get(self, *args, **kwargs): students = Student.objects.values('id', 'first_name', 'last_name', 'gender', 'dob') paginator = Paginator(students, 100, orphans=5) page = self.request.GET.get('page') or 1 try: current_page = paginator.page(page) except InvalidPage as e: page = int(page) if page.isdigit() else page context = { 'page_number': page, 'message': str(e) } return JsonResponse(context, status=404) context = { 'students': list(current_page) } return JsonResponse(context) ``` -
Managing static files in Django 3.1
There are some changes in the Django 3.1 update and settings file has bee changes a bit as import os has been dropped. I have created a new project on Django 3.1 and referred to the official documentation for managing static files. I also tried this solution from StackOverflow but it didn't work out for me. My project structure: . ├── db.sqlite3 ├── app │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── project │ ├── asgi.py │ ├── __init__.py │ ├── settings │ │ ├── base.py │ │ ├── __init__.py │ │ ├── local.py │ │ ├── production.py │ │ └── __pycache__ │ ├── urls.py │ └── wsgi.py ├── manage.py ├── static │ ├── css │ │ └── main.css │ └── js │ └── fullscreen_toggle.js └── templates local.py: import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '----secretKey----' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
How can I filter with prefetch_related table count in Django ORM?
content = Content.objects.filter(Q(**query) | Q(**query2)). prefetch_related('like').all() return content Hello. I want to return content which has more than 10 like. How can I do thtis? -
Django LeafletWidget custom style of geometry
I'm using django and leaflet for my app where I display gps tracks on a map. For my edit page of a gps track I use the LeafletWidget. Now I want to change the line style of this element. #forms.py class ActivityEditForm(forms.ModelForm): class Meta: model = Activity fields = ('name', 'track', 'desc') widgets = { 'track' : LeafletWidget() } And here a part of my html: //activity_edit.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="hidden" name="next" value="{{ request.GET.next }}"> <button type="submit">Save</button> </form> Result: I'm a beginner in front-end and css. But I don't want the default blue line for the track. I want to change it to a red line with bigger width. In my normal map view I can change the style of the track on loading the tracks as geojson. But in the form it is already loaded and displayed and I don't know how to access the track to change its style. -
CreateView Saving prblem?
I have three models. #Peronal_info Models: class Personal_info(models.Model): pinfo_id = models.AutoField(primary_key=True) userid = models.OneToOneField(User, on_delete=models.CASCADE) nfullname = models.CharField(validators=[max_len_check], max_length=128) efullname = models.CharField(validators=[max_len_check], max_length=128) dob_ad = models.DateField() dob_bs = models.DateField() gender = models.CharField(max_length=6) citizen_no = models.CharField(max_length=56) cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE) cissue_date = models.DateField() language = models.CharField(max_length=56) p_district = models.CharField(max_length=56) p_vdc = models.CharField(max_length=56) p_ward = models.CharField(max_length=2) telephone = models.BigIntegerField(null=True, blank=True) mobile = models.BigIntegerField() mother_name = models.CharField(validators=[max_len_check], max_length=128) mother_cit = models.CharField(max_length=10, null=True) father_name = models.CharField(validators=[max_len_check], max_length=128) father_cit = models.CharField(max_length=10, null=True) image = models.FileField(upload_to="photos/", null=True, blank=True) cit_image = models.FileField(upload_to="citizens/") inclu_image = models.FileField(upload_to="inclusions/", null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager def __str__(self): return str(self.efullname) Education Models: class Education(models.Model): edu_id = models.AutoField(primary_key=True) userid = models.ForeignKey(User, on_delete=models.CASCADE) institute = models.CharField(max_length=255, validators=[max_len_check]) board = models.CharField(max_length=128, validators=[max_len_check1]) pexam = models.CharField(max_length=16) faculty = models.CharField(max_length=16) division = models.CharField(max_length=16, validators=[max_len_check2]) tmarks = models.IntegerField() percent = models.FloatField(null=True, blank=True) mainsub = models.CharField(max_length=16, validators=[max_len_check2]) image = models.FileField(upload_to="educations/", null=True, blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager def __str__(self): return str(self.userid) V_applied Models: class V_applied(models.Model): appNo = models.IntegerField(null=True, blank=True, default=add_one) p_srlno = models.IntegerField(blank=True, null=0, default=0) userid = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Vacancy,on_delete=models.CASCADE) inclusive = models.ManyToManyField(Inclusive) bank = models.CharField(max_length=128,choices=bank_choice) v_no = models.CharField(max_length=32, validators=[max_len_check1]) dep_date = models.DateField() … -
Password does not match for user "postgres" after deleting postgresql from local machine
I am running an application in 3 separated docker containers. One for postgresql, another one for Django and the third one for nginx. In my settings.py I retrieve data for my db settings from .env file like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } I used sqlite for development but was building docker image using postgresql and it was working perfectly fine. Then for testing purposes I connected postgresql to django as development database with the exactly same settings. But after I returned to sqlite and built another image with this db settings it actually started returning password error. db_1 | Connection matched pg_hba.conf line 99: "host all all all md5" db_1 | 2020-09-20 16:39:02.730 UTC [36] FATAL: password authentication failed for user "postgres" db_1 | 2020-09-20 16:39:02.730 UTC [36] DETAIL: Password does not match for user "postgres". My docker-compose file: version: '3.8' volumes: postgres_data: static: media: services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: ashowlsky/foodgram:v3.8 restart: always command: gunicorn foodgram.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/code/static/ - ./media:/code/media/ ports: - "8000:8000" depends_on: - db env_file: - ./.env nginx: image: nginx:1.19.2 ports: - "80:80" … -
AssertionError: 404 != 200 Failure in Django
I wrote test for all aspects of my model, but the very simple and basic one fails. Here is the urls.py app_name = 'projects' urlpatterns = [ path('all/', ViewProjects.as_view(), name='all_projects'), path('project/<slug:project_slug>/', ProjectDetail.as_view(), name='project_detail'), path('new/', ProjectCreateView.as_view(), name='project_create'), path('', HomeView.as_view(), name='home'), ] and its respective test: class TestProject(TestCase): def test_project_list_view(self): url = reverse('projects:home') response = self.client.get(url) self.assertEquals(response.status_code, 200) This test gets failed, here is the traceback: (Portfolio) PS D:\GitHub\Portfolio> python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .[2020-09-20 21:34:36,616] log: WARNING - Not Found: / F ====================================================================== FAIL: test_project_list_view (projects.tests.TestProject) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitHub\Portfolio\projects\tests.py", line 11, in test_project_list_view self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 2 tests in 0.113s FAILED (failures=1) Destroying test database for alias 'default'... However, when I run python manage.py runserver the urls, views and template are all connected. What is the problem? Please help thank you. -
Configuring Django with Nginx, uWSGI and Mysql on Docker
Нашел статью по настройке данного стека, но нашел в ней пару неточностей или я что-то упустил, пока понять не смог что не так. Докер начал изучать недавно, поэтому пока много чего непонятно. https://zotovp.wordpress.com/2019/07/07/djangouwsginginxpostgresql-in-dockerdocker-compose-for-development-and-production-deployment-%d1%80%d0%b0%d0%b7%d0%bc%d0%b5%d1%89%d0%b5%d0%bd%d0%b8%d0%b5-djangouwsginginxpostgresql-%d0%b2/ Основная проблема у меня возникла в файле docker-compose.yml. В статье в конце файла указан том и в нем сокет ports: - "8080:8080" volumes: sock: Если убрать эту настройку, то начинает ругаться на том сокета в настройках django и nginx. volumes: - ./code:/code - sock:/sock Я решил изменить и эти куски заменив таким образом: volumes: - ./code:/code - ./sock:/sock После этих изменений для режима "dev" все заработало. Но когда я попробовал переключить на режим "prod" проект django перестает запускаться. Переключение dev и prod осуществляется в файле docker-compose.yml согласно статье: #command: uwsgi --ini /etc/uwsgi.ini command: bash -c "python /code/projectname/manage.py collectstatic --noinput && python /code/projectname/manage.py migrate && python /code/projectname/manage.py runserver 0.0.0.0:8000" Основной вопрос у меня связан с настройкой сокета, а также причина почему при переключении в prod режим проект перестает работать. Дерево проекта: . ├── code │ ├── behelit │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ ├── settings.cpython-38.pyc │ │ │ ├── urls.cpython-38.pyc │ │ │ └── … -
Vue.js data not updating when receiving message from socket
I'm trying to design a vue.js app that updates data about the state of a game upon receiving a "new_state" message from a socket. The socket is implemented using django channels. This is what the code looks like: const ws_scheme = window.location.protocol == "https:" ? "wss" : "ws" const gameSocket = new WebSocket( ws_scheme + '://' + window.location.host + '/ws/play/' + game_id + '/' ) let vue = new Vue({ el: '#app', data: { current_turn: 0, last_turn: -1, current_card: 0, last_card: -1, number_of_stacked_cards: 0, last_amount_played: 0, won_by: -1, my_cards: [], other_players_data: {}, }, created() { gameSocket.onmessage = function(e) { data = JSON.parse(e.data) this.current_turn = data.state.current_turn this.last_turn = data.state.last_turn // ... update the other data }; }, }); When I receive the message, logging the data makes it apparent that I'm receiving correct information. However, if I go and type vue.current_turn after receiving the message, it's still 0 instead of the new value; same for all the other members of the data object. I tried with vue.current_turn = data.state.current_turn and it does work this way, but obviously it should work with this. What's wrong with my code? And generally speaking, what's the best way of accomplishing what I'm after, i.e. updating … -
Django file download as attachment on form submit doesn't work on mobile
I'm trying to generate a file by writing to io.BytesIO and then send it on form submit as file attachment. Everything works fine in Firefox on Linux, but mobile browsers send a GET request when I accept the download in browser and save the HTTP response as the downloaded file. Here is my view function: @csrf_exempt def download_file(request): if request.method == 'POST': buffer = io.BytesIO() buffer.write('Text file content'.encode('UTF-8')) buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='file.txt') return HttpResponse('<form method="post"><button>Download</button></form>') This is what the logs look like when form is submitted from Firefox on Linux: [20/Sep/2020 18:15:31] "POST /test/ HTTP/1.1" 200 17 Downloaded file looks like on Linux: Text file content This is what the logs look like when form is submitted from Firefox on Android: [20/Sep/2020 18:16:47] "POST /test/ HTTP/1.1" 200 17 [20/Sep/2020 18:16:48] "GET /test/ HTTP/1.1" 200 52 And this is what the downloaded file looks like on Android: <form method="post"><button>Download</button></form> -
Django form : how I can get a second user with instance?
I try to understand how I can fill automatically the seller user field: Assume I got private group with two users (one is consumer the other is seller) Only consumer can have access to this form. So form.instance.consumer = self.request.user works well. form.instance.channel = self.object works well also. In my forms I'm using crispy forms and it's only display two fields (rate and comment). But my question is how I can get seller user? I'm beginning with Django :) #Channel REVIEW @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class ChannelReview(generic.DetailView, FormMixin): model = Channel context_object_name = 'channel' template_name = 'channel_review.html' form_class = ChannelRatingForm def get_context_data(self, **kwargs): context = super(ChannelReview, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.channel = self.object form.instance.seller = seller #### Here is my question form.instance.consumer = self.request.user form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_valid(form) def get_success_url(self): return reverse('channel:channel_detail',kwargs={"slug":self.object.slug}) def get(self,request,*args,**kwargs): self.object = self.get_object() if not (request.user == self.object.consumer or request.user == self.object.seller): return HttpResponseRedirect('/') return super(ChannelReview, self).get(request,*args,**kwargs) class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, … -
How to fix Connection reset by peer
i am using django to stream a video from my server , its all fine, but when i reload the video page while the video is on stream , i get this error : ConnectionResetError: [Errno 104] Connection reset by peer so what i am doing wrong ?? models.py class VideoUpload(models.Model): Video_Description = models.CharField(max_length=500) slug = models.SlugField(unique=True) Video = models.FileField(upload_to='videos/%Y/%m/%d/', null=True, verbose_name="") timestamp = models.DateTimeField(auto_now_add=True) views def render_video(request): video = VideoUpload.objects.last() return render(request,'stream_dj/video.html',{'video':video}) html <video name='demo' controls autoplay width='50%' height='40%'> <source src="{{video.Video.url}}" type="video/mp4"/> </video> </body> -
cant print objects in postgresql on html page "404 not found"
so this is my html code {%block content%} {%for v in vot%} <img src="{{vot.img.url}}" alt=""> <div >{{vot.name}}</div> <div >From {{vot.roll}}</div> {% endfor %} {%endblock%} and this is from views def vo(request): vot = reg.objects.all() return render(request, 'index.html', {'vot': vot}) OUTPUT IMAGE i get this as output . it ignores {{}} variables for some reason name img every thing is declared in models class reg(models.Model): name=models.CharField(max_length=100) roll=models.IntegerField() img=models.ImageField(upload_to='pics') and shows this in terminal "GET / HTTP/1.1" 200 232 i have 3 objects in database but it only prints from 3 times and ignore jinja variables -
How can I solve django TypeError: __init__() got an unexpected keyword argument 'thread critical' error in gitlab-ci?
I have a Django project and I am using gitlab-ci for it but my tests failed! I used to use bitbucket-ci before and I had no problem. My .gitlab-ci.yml file is: image: python:latest services: - postgres:latest variables: POSTGRES_DB: ci POSTGRES_USER: postgres POSTGRES_PASSWORD: 123456 cache: paths: - ~/.cache/pip/ before_script: - python -V # Print out python version for debugging - pip install -r requirements.txt test: variables: DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB" script: - python manage.py test --settings sohbat_backend.ci_settings but I get this error that I have never seen anywhere! Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 14, in <module> from django.core.management.base import ( File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 11, in <module> from django.core import checks File "/usr/local/lib/python3.8/site-packages/django/core/checks/__init__.py", line 10, in <module> import django.core.checks.database # NOQA isort:skip File "/usr/local/lib/python3.8/site-packages/django/core/checks/database.py", line 1, in <module> from django.db import connections File "/usr/local/lib/python3.8/site-packages/django/db/__init__.py", line 16, in <module> connections = ConnectionHandler() File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 148, in __init__ self._connections = Local(thread_critical=True) TypeError: __init__() got an unexpected keyword argument 'thread_critical' -
Django redirecting URL view for the latest post
I am a novice to Django, so excuse me if this seems rather trivial. I am trying to create a link to the latest issue for an online magazine. Here is my code: home.html: {%extends 'base.html'%} {%load static%} {% block content%} <button href="#"> Latest Issue</button> {%endblock%} views.py: from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Issue from .forms import PostForm, EditForm, IssueForm, IssueEditForm from django.urls import reverse_lazy from django.http import HttpResponse class HomeView(ListView): model = Issue template_name = "home.html" class IssueView(ListView): model = Issue template_name='issues.html' class IssueDetailView(DetailView): model = Issue template_name = 'issue_details.html' def get_context_data(self, **kwargs): context = super(IssueDetailView,self).get_context_data(**kwargs) context['posts'] = Post.objects.all() return context #This is to pass in my post model, so I can display the posts for each issue in issue-details.html. urls.py: from django.urls import path from .models import Post, Issue #from . import views from .views import HomeView, ArticleDetailView, AddPostView,EditPostView, DeletePostView,about_view, submit_view,IssueView, AddIssueView, IssueDetailView, EditIssueView urlpatterns = [ path('',HomeView.as_view(),name="home"), path('issue/',IssueView.as_view(), name="issue"), path('issue/<int:pk>', IssueDetailView.as_view(), name='issue-detail'), ] #Irrelevant urlpatterns omitted. I looked at this solution, but I was not able to implement it, especially since it is from 9 years ago. I did not know what view to put/create for … -
Django How can I pass a subquery in LEFT JOIN
I have 3 models (A,B,C): class A(models.Model): url = models.URLField() uuid = models.UUIDField() name = models.CharField(max_length=400) id = models.IntegerField() class B(models.Model): user = models.ForeignKey(C, to_field='user_id', on_delete=models.PROTECT,) uuid = models.ForeignKey(A, to_field='uuid', on_delete=models.PROTECT,) and I want to perform the following SQL query using the Django ORM: SELECT A.id, COUNT(A.id), COUNT(foo.user) FROM A LEFT JOIN (SELECT uuid, user FROM B where user = '<a_specific_user_id>') as foo ON A.uuid = foo.uuid_id WHERE name = '{}' GROUP by 1 HAVING COUNT(A.id)> 1 AND COUNT(A.id)>COUNT(foo.user) My problem is mainly with LEFT JOIN. I know I can form a LEFT JOIN by checking for the existence of null fields on table B: A.objects.filter(name='{}', b__isnull=True).values('id', 'name') but how can I LEFT JOIN on the specific sub-query I want? I tried using Subquery() but it seems to populate the final WHERE statement and not pass my custom sub-query in the LEFT JOIN. -
Face detection box does not appear on the local server. (Django)
It is a mask detection code (camera.py) using Yolo model. I tried to implement this on django server. The video appeared on the screen by webcam without any problems. However, the face detection box is not showing up. I tried using VideoStream instead of VideoCapture, but the results were the same. And when I printed out the jpeg, I checked that it came out properly. What's the problem?... import cv2,os,urllib.request import numpy as np from django.conf import settings # from imutils.video import VideoStream import imutils # load our serialized face detector model from disk os.chdir(r'C:/Users/rjsgh/OneDrive/Desktop/Mask_Detection/warming_up_project/streamapp') weightsPath = "./face_detector/yolov4-tiny-obj_best.weights" cfgPath = "./face_detector/yolov4-tiny-obj.cfg" yoloNet = cv2.dnn.readNet(weightsPath, cfgPath) layer_names = yoloNet.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in yoloNet.getUnconnectedOutLayers()] LABELS = ["Mask", "No Mask"] COLORS = [(0,255,0), (0,0,255)] class yoloDetect(object): def __init__(self): self.vs = cv2.VideoCapture(0) def __del__(self): self.vs.release() cv2.destroyAllWindows() def detect_mask(self, frame): (h,w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1/255.0, (416, 416), swapRB=True, crop=False) yoloNet.setInput(blob) layerOutputs = yoloNet.forward(output_layers) class_ids = [] cofidences = [] boxes = [] for output in layerOutputs : for detection in output : scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5 : box = detection[:4] * np.array([w,h,w,h]) (center_x, center_y, width, height) = box.astype("int") x … -
how can I download image with different sizes in jquery or python django?
I have an image which is displayed to user. User can select the size of image which he/she want to download. How can I do so. I don't want to store the different sizes of image. I want to create a function with parameter specifying the size which will be called when the user click the download button. From that function the image should get downloaded (without changing the actual file size and should not create a new file or if created should not get stored anywhere). If it is possible to do such thing in jquery will be appreciated, so that there will be no need to send request to backend, if not then in python django. -
How do I send a post with Django superuser authorization with the post method of HttpClient in Angular?
Can someone tell me how to login to my Django superuser making a post? (I am using HttpClient) I usually use httpie to do it: http -a post lalala.com:80 whatever="whatever" Now I need to get django to do the same thing. I tried: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'Basic ' + btoa('mydjangosuperuser:mypassword') }) }; var item = ({key: key, url: url} as Object) return this.http.post<any>(this.fullDictURL, item, httpOptions) .pipe( catchError(this.handleError) ); } -
'CustomerPurchaseOrder' object has no attribute 'get_user_visible_fields'
I am doing import-export to excel in my admin.py, every time i click the import button i receive this error 'CustomerPurchaseOrder' object has no attribute 'get_user_visible_fields' i dont know what is wrong with my code, i been following the documentation (below). did i miss something in my code?. class CustomerPurchaseOrderResource(resources.ModelResource): class Meta: model = CustomerPurchaseOrder fields = ('profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) class CustomerPurchaseOrderAdmin(ImportExportModelAdmin): list_filter = ("process", "deliverySchedule", "inputdate") list_display = ( 'profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) ordering = ('id','requestedDate') resource_class = CustomerPurchaseOrder this is my models.py class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customerdeliveryaddress = models.ForeignKey(CustomerDeliveryAddress, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Delivery Address") customer_Purchase_Order_Detail = models.ForeignKey('CustomerPurchaseOrderDetail', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer Purchase Order") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") attachment = models.ImageField(upload_to='images', null=True, blank=True) requestedDate = models.DateField(auto_now_add=True) deliverySchedule = models.ForeignKey(DeliverySchedule, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Schedule") deliveryDate = models.DateTimeField(null=True, blank=True) instructionToSeller = models.CharField(max_length=500, null=True, blank=True) paymentmethod = models.ForeignKey('PaymentMethod', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") address = models.CharField(max_length=500, null=True, blank=True) city = models.CharField(max_length=500, null=True, blank=True) country = models.CharField(max_length=500, null=True, blank=True) recordStatus = models.ForeignKey(RecordStatus, on_delete=models.SET_NULL, null=True.) ..... this is the documentation i follow https://django-import-export.readthedocs.io/en/stable/getting_started.html this is my full traceback Environment: Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File …