Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Complicated querying databases
Please see scenario below: class Case(models.Model): name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) class Suite(models.Model): name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) cases = models.ManyToManyField(Case, through='SuiteThroughModel') class Project(models.Model): name = models.CharField(max_length=200) documentation = models.CharField(max_length=2048, blank=True) suites = models.ManyToManyField(Suite, through='ProjectSuiteThroughModel') class ProjectSuiteThroughModel(OrderedModel): project = models.ForeignKey(Project, on_delete=models.CASCADE) suite = models.ForeignKey(Suite, on_delete=models.CASCADE) class SuiteThroughModel(OrderedModel): case = models.ForeignKey(Case, on_delete=models.CASCADE) suite = models.ForeignKey(Suite, on_delete=models.CASCADE) What I'm trying to do is retrieving all suites from a particular Project. This is how I went about it: project = Project.objects.get(name='xyz') suites = project.suites.all() # outputs nothing In Django docs I learned that I can get the data from the other end of the query: suites = Suite.objects.filter(project__name='xyz') # outputs nothing suites = Suite.objects.filter(projectsuitethroughmodel__project__name='xyz') # outputs nothing The data is there but how can I access it ? -
Multi-user efficient time-series storing for Django web app
I'm developing a Django app. Use-case scenario is this: 50 users, each one can store up to 300 time series and each time serie has around 7000 rows. Each user can ask at any time to retrieve all of their 300 time series and ask, for each of them, to perform some advanced data analysis on the last N rows. The data analysis cannot be done in SQL but in Pandas, where it doesn't take much time... but retrieving 300,000 rows in separate dataframes does! Users can also ask results of some analysis that can be performed in SQL (like aggregation+sum by date) and that is considerably faster (to the point where I wouldn't be writing this post if that was all of it). Browsing and thinking around, I've figured storing time series in SQL is not a good solution (read here). Ideal deploy architecture looks like this (each bucket is a separate server!): Problem: time series in SQL are too slow to retrieve in a multi-user app. Researched solutions (from this article): PyStore: https://github.com/ranaroussi/pystore Arctic: https://github.com/manahl/arctic Here are some problems: 1) Although these solutions are massively faster for pulling millions of rows time series into a single dataframe, I … -
How does git push heroku master save file/folder data in heroku server's db
I was trying to understand and replicate git push myserver master in my Django project but didn't understand , how to integrate git push myserver master similar to git push Heroku master. Can anyone help me out? Thanks in advance. -
Django login view does not not return set-cookie header for session ID (redirects back to login view)
I am getting the following response from the Django (2.2) default login view: Request URL: https://api.n.exchange/en/accounts/login/?next=/en/referrals/ Request Method: GET Status Code: 200 OK Remote Address: 104.25.23.99:443 Referrer Policy: no-referrer-when-downgrade Cache-Control: max-age=0, no-cache, no-store, must-revalidate CF-RAY: 51105b439e71b50e-VNO Connection: keep-alive Content-Encoding: br Content-Language: en Content-Type: text/html; charset=utf-8 Date: Wed, 04 Sep 2019 13:37:09 GMT Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Expires: Wed, 04 Sep 2019 13:37:09 GMT Server: cloudflare Set-Cookie: csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; expires=Wed, 02 Sep 2020 13:37:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax Transfer-Encoding: chunked Vary: Cookie, Origin X-Frame-Options: SAMEORIGIN X-NewRelic-App-Data: PxQGUlFVCwoGR1JTDwQFX1IAFB9AMQYAZBBZDEtZV0ZaCldOdxRdARBfWA9JB1JSXgMOTFReWRIWWFQdAxMXCh4UUQdPSw5+XAJQD2cIVhVKUVIVRE8IHwBKUVAPBw5QVggOBltfUVYDUw5WFBUFHhFVAFAABABbAQEGWFYGWQVSRk0EVl1EAzk= Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,he;q=0.7,lt;q=0.6,de;q=0.5 Connection: keep-alive Cookie: __cfduid=d76f7b7d2a1caa6948456ad6829dc25991553698344; _ga=GA1.2.2123122031.1553698346; _ym_uid=1553698347983819119; _ym_d=1553698347; crisp-client%2Fsession%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=session_76921095-b26c-4790-a968-82cf111e3940; _hjid=e834477e-35c2-4ef9-aacd-5fb2d644ae2c; crisp-client%2Fsocket%2F6eb9ed9e-2c8b-48e8-a0ce-62c3ce81fb61=1; _gid=GA1.2.1927749960.1567447617; USER_TZ=Europe/Vilnius; django_language=en; _ym_isad=1; _ym_visorc_42222484=w; _ym_visorc_45642111=w; csrftoken=BHfEypgp6ux4FvQr14G06DQnqHjRL0tXZYP4Cg2b67naaFkxFw29g0C5UVettETb; _gat=1 Host: api.n.exchange Referer: https://api.n.exchange/en/accounts/login/?next=/en/referrals/ Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 X-NewRelic-ID: VQUAV1VaDhADVVlXBQgBVw== next: /en/referrals/ As you can clearly see, the set-cookie header for the sessionid which represents the authenticated Django session is missing. What could be the cause? (at first, I was thinking the reason is that we have a self signed HTTP certificate behind Cloudflare but we have migrated to a valid letsencrypt certificate and removed cloudflare to test it, but the problem persists). Thanks! Do I … -
full_clean() missing 1 required positional argument: 'self'
I'm currently using django version 2.2.4 and trying to create an edit button that will update my models. When trying to save the updated value an TypeError occured which it stated that "full_clean() missing 1 required positional argument: 'self'". I can't seem to detect any error from my codes. Thanks in advance for helping me. my views.py file def lab_edit(request, pk, template_name='webapp/lab_edit.html'): lab= get_object_or_404(Labs, pk=pk) form = LabForm(request.POST or None, instance=Labs) if request.method == "POST": if form.is_valid(): form.save() return redirect('lab') return render(request, template_name, {'form':form}) my lab_edit.html file <div class='container'> <h2>EDIT LAB</h2> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> </div> my LabForm class LabForm(forms.ModelForm): class Meta: model = Labs fields = ('labcode', 'name','administrator') -
Rest API usage in Django and other projects
if we have only webpage and we access form browser to our project still rest api is needed?? Rest API only use for accessing our data from other platforms? Can we create our templates from rest API or its better we don't use rest API for that and we use regular Django ways to tgat -
hide "add", "change", "delete" actions in djaongo admin
I have a piecce of code like this: class PlatformEnvInLine(admin.TabularInline): model = PlatformEnv extra = 1 classes = ['collapse'] fields = ('environment',) My PlatformEnv Model looks like this: class PlatformEnv(models.Model): id = models.AutoField(db_column='ID', primary_key=True) ... environment = models.ForeignKey(Environment, models.DO_NOTHING, db_column='Environment_ID', blank=True, null=True) When the PlatformEnvInLin is shown now, you can select an environment via dropdown. But next to the dropdown there are buttons displayed to add, change or delete a environment. How can I hide these buttons? -
Is it possible to access non db key from request in Django signal?
I'm doing an api request and I'm sending a non-db key with the request. In Django's pre-signal I want to use that key to make a decision. Is it possible to do it? If yes how can I do it? Example Scenario: # POST request body from postman { "field1": 10, "custom_field": True } # test model class TestModel(models.Model): field1 = model.IntegerField(default=0) field2 = model.CharField(default="test") # django pre save signal pre_save.connect(test_function, sender=TestModel) # test function in some helper def test_function(sender, instance, raw, using, update_fields, **extra_fields): # here I'm using the custom field which is not in model if instance.custom_field: instance.field2 = "hello" else: instance.field2 = "hi" I'm getting an error i.e. AttributeError: 'ModelTest' object has no attribute 'custom_field' I hope you understand. Thanks in advance. -
Django deployment on apache errors
Hello guys I'm trying to deploy my django project on apache but I am facing some errors mainly with the vhost configuration. Err.1:Port :82 used for the VirtualHost is not an Apache define variable. Err.2:The number of DocumentRoot does not match the number of ServerName in c:/wamp64/bin/apache/apache2.4.39/conf/extra/httpd-vhosts.conf file Err.3:The path C:/Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/static/static for httpd-vhosts <VirtualHost *:82> ServerName localhost WSGIPassAuthorization On ErrorLog "logs/mobile.error.log" CustomLog "logs/mobile.access.log" combined WSGIScriptAlias / "C:/Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/wsgi_windows.py" <Directory "C:/Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/static/static" <Directory "C:/Users/Administrator.HR-JUGOR/Anaconda3/envs/MMA/Mobile/static/static"> Require all granted </Directory> </VirtualHost> -
there is an error while using "all_task.has_next" (all_task is an object) in my code
**in my project for learning basic thing, i used Django paginator and i implement a code to show last page with condition to check isCurrentPage? is last page or not. when i visit to last page it shows emtypyPage, That page contains no results todolist.html <nav aria-label="Page navigation example"> <ul class="pagination justify-content-end"> <li class="page-item"><a class="page-link" href="?pg=1" ><<</a></li> {% if all_task.has_previous %} <li class="page-item"><a class="page-link" href="?pg={{ all_task.previous_page_number}}">{{ all_task.previous_page_number}}</a></li> {% endif %} <li class="page-item"><a class="page-link" href="?pg={{ all_task.number }}">{{ all_task.number }}</a></li> <li class="page-item"><a class="page-link" href="?pg={{ all_task.next_page_number }}">{{ all_task.next_page_number }}</a></li> {% if all_task.has_next %} <li class="page-item"><a class="page-link" href="?pg={{ all_task.paginator.num_pages}}">>></a></li> {% endif %} </ul> </nav> views.py ```paginator = Paginator(all_task, 5) ```page = request.GET.get('pg') ```all_task = paginator.get_page(page) ```return render(request, 'todolist.html',{'all_task':all_task})** -
Python Django List All Posts Belonging To One Category
I want to list all posts belonging to one category using the python django framework. I think the best way is to use django.views.generic.ListView My Models: class Category(models.Model): name = models.CharField(max_length=250) slug = models.SlugField(max_length=250, blank=True) def __str__(self): return self.name def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('category-detail', kwargs=kwargs) def save(self, *args, **kwargs): value = self.name self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) My Url-Patterns: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('category/<str:slug>/', CategoryListView.as_view(), name='category-detail'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail') ] My View: class CategoryListView(ListView): paginate_by = 8 template_name = 'blog/category_list.html' context_object_name = 'posts' def get_queryset(self): return Post.objects.filter(category_id=Category.objects.filter(slug=self.kwargs.get('slug')).first().id).all() This works for me. However it seems like it is not the most elegant way to do it, since I have to get the category_id first and then filter the posts. Is there are more elegant way to do this? -
django admin - How to add javascript at the end of a file
I am trying to add a custom javascript file to a Django admin model page. I am using a class Media in the ModelAdmin, but the file is been loaded in the head section. I need at the end of the file. Does anyone knows how to do that? Thank you all! class Media: js = ( 'js/jquery.mask.min.js', 'js/mask.js', ) The aim of these scripts is to have masks working for some fields in the form. -
How to filter listview using a dropdown box
Is this possible, I've tried using django-filters, but it means a button then needs to be pressed. Is it possible to use navbar type links to filter a listview? -
No pdb prompt when telnet connects to celery for rdb debug?
I successfully connect via telnet, but the debugger does not appear (i.e. no pdb prompt). Probably something stupid, but.... FYI this is on a Macbook pro. Python 2.7, Django 1.11. -
Django cron runs multiple time, but it shouldn't
I have multiple crons set in Django. In each CronJob I have set ALLOW_PARALLEL_RUNS = False. To run crons I have used linux crontab like follows : */1 * * * * /home/social/centralsystem/venv/bin/python3.6 /home/social/centralsystem/manage.py runcrons After some times of running (for example after 2 monthes) I see lots of crons running that make a lot of load on the server. My question is that what causes this happen? -
Django create empty
I created a couple a models like Organization. The problem that I noticed with tests I can use create method on a model even if short_name is empty or not it will save a new instance. I did set Validator it does not help class Organization(models.Model): # auto creates with signals pre_save code = models.CharField( primary_key=True, max_length=255, blank=False, null=False, help_text='Unique code or id that can be used to identify organization' ) name = models.CharField( max_length=255, blank=False, null=False, help_text='Short name of the organization' ) short_description = models.CharField( max_length=255, blank=False, null=False, help_text='Brief overview of the organization', validators=[MinLengthValidator(1)] ) Test # this will pass @pytest.mark.django_db def test_organization_create(): obj = Organization.objects.create(name='TEST') assert obj.code Desired behaviour is whatever I create Organization instance if I don't specify short_name will throw error. -
Running "migrate" won't produce migrations folder
As the title says running python manage.py migrate runs the migrations but no migrations directory is produced in the app directory hence no tables from models.py exist. Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK This is quite new error to me. What should I do ? -
Can't open pdf file generated by python pdfkit
I am using Pdfkit in django to generate html template to pdf. When I return the response with PDF attachment, I try to open it but I can't. I installed wkhtmltopdf to fix path problem but it doesn't solve the problem. Code: path_wkhtmltopdf = 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) pdf =pdfkit.from_url('http://google.com', 'out.pdf', configuration=config) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'inline;' return response Images: http://prntscr.com/p1o4ff http://prntscr.com/p1o4t1 -
Django, Docker, Python - Unable to install Pillow on python-alpine
I have a dockerized django app that I want to put in production. But ever since I added an Imagefield Pillow is required and I struggle to install Pillow in the Docker container. As far as I understand it, adding the dependencies jpeg-dev ibjpeg & zlib-dev should be enough for django (?). With the configuration below I receive the error: Error on runserver: product.Product.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". product.Product.thumbnail: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". If I add Pillow to requirements.txt (or putting pip install Pillow in the Dockerfile) I get an even longer error message while trying to build the container. Without putting pip install Pillow in Dockerfile or requirements.txt - this is my configuration. Dockerfile: # pull official base image FROM python:3.7-alpine # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /usr/src/kitschoen-dj RUN pip install --upgrade pip # install psycopg2 RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql \ && apk add postgresql-dev … -
Django multiple database routing. Missing 1 required positional argument: 'model'
I am trying to link an external database to my Django project in order to perform validation. I have tried my best to follow the official django tutorials on routing and other sources and have managed to get to the point where my database is recognised and the model is read. However, when I enter the shell and try to access one of the models associated with this db, like so: from get_ext.models import ExternalTable ExternalTable.objects.all() I get the following error: TypeError: db_for_read() missing 1 required positional argument: 'model' Here is the current setup of my dbs, router and model: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'colltooldb', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'externaldb', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } } get_ext/models.py from django.db import models class ExternalTable(models.Model): ''' FIELDS ''' class Meta: managed = False db_table = 'external_table' get_ext/routers.py class ExtRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'get_ext': return 'external' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'get_ext': return 'external' return None What is causing this error? I recognise, that I don't really have a lot of knowledge in this particular domain, … -
#Django Clientside Filtering
how to dynamically filter the data present in a table using client side filtering after loading the data into table from external API in Django-python. (it should be dynamically filtering according the word search by user enters in a search box, note:no search button we should use only search box) -
how can i relate question and answer set to one particular article?
i created one article on stack,at the end of this article provide link to next page which have set of ques-ans related to stack but when i create second article on linked list then on the next page it still display ques-ans for the stack.how can i differentiate ques-ans to one particular article? one post have multiple ques-ans so i use foreign key concept but still i not get a result which i want. in blog/models.py class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() author = models.ForeignKey(User, on_delete = models.CASCADE) qustion_set = models.ForeignKey(Practice,default = "",editable = False,on_delete = models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) in practice.models.py class Practice(models.Model): question = models.TextField() answer = models.TextField() def __str__(self): return self.question def get_absolute_url(self): return reverse('practice-create') it gives operational error like no such column: blog_post.qustion_set_id -
django-elasticsearch-dsl suggest not working
I have created the following document using django-elasticsearch-dsl. @registry.register_document class QuestionDocument(Document): class Index: name = 'questions' class Django: model = QuestionModel fields = ['title', 'text'] Now when i try to do a suggest with below command QuestionDocument.search().suggest("questions", "text", completion={'field': 'title'}).to_queryset().all() I get the following error: elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'Field [title] is not a completion suggest field') What am i doing wrong here? and how can i fix it? I tried to find a tutorial in the package documentation but couldn't find anything. -
Why I get empty data sent by ajax request?
There is a form. It has a field for uploading a file. I submit this form and send it to server by ajax request, post method. var frm = $('#contact_form'); frm.submit(function (e) { e.preventDefault(); $.each($("div[class^='contact_form_']"), function(ind, value){ $(value).hide(); $(value).prev().css('border', 'none') }) var form_data = new FormData($('#contact_form')[0]); for(var pair of form_data.entries()) { console.log(pair[0]+ ', '+ pair[1]); } $.ajax({ beforeSend: function(jqXHR, settings) { jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val()); }, type: frm.attr('method'), url: '', data: form_data, processData: false, contentType: false }); return false; }); I'm use the formdata. I look at the client - there is data. But they do not come to the server (request.POST={}). What could be the reason? def post(self, request, *args, **kwargs): print(request.GET, request.FILES, request.POST) contact_form = ContactFormForm(request.POST, request.FILES) if contact_form.is_valid(): contact_form = contact_form.save() file = request.build_absolute_uri('/')[:-1] + settings.MEDIA_URL + str(contact_form.file) return JsonResponse({}) else: response = {} for k in contact_form.errors: response[k] = contact_form.errors[k][0] return JsonResponse({'response': response, 'result': 'error'}) -
fetch data based on category django
I am creating a stock photography portal so i have the main page where all the image category are listed what i want that when i click on any category then it should fetch data based on category view.py: def imageview(request): #cat_image = request.GET.get() allimage = image.objects.all() cat= category.objects.all() context = {'allimage': allimage, 'cat': cat} return render(request, 'image/search.html', context) models.py: class category(models.Model): name = models.CharField(max_length = 100) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent') verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class image(models.Model): title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'home/tboss/Desktop/image' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('category', null=True, blank=True, on_delete=models.CASCADE) description = models.TextField(max_length=1000) def __str__(self): return self.title urls.py: urlpatterns = [ path('', views.home, name = 'home'), path('search/', views.imageview, name= 'imageview') ] also i'm trying to include category based search. I don't know what will be the best way to do this