Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add URL component to current URL via a HTML button? (Django 2.1)
I have a HTML button that is supposed to sort the search results by alphabetical order. Button HTML code: <a href="?a-z=True" type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a> views.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') if request.GET.get('a-z') == 'True': articles = articles.order_by('Title') Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen? -
Django - Unable to open database file (sqlite3.OperationalError)
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } The db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 The root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. My Apache2 config file: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName sub.domain.com ServerAlias sub.domain.com DocumentRoot /var/www/lab <Directory /var/www/lab> Options FollowSymLinks AllowOverride All </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/lab/static <Directory /var/www/lab/static> Require all granted </Directory> <Directory /var/www/lab/chatbot> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/lab/chatbot/wsgi.py WSGIDaemonProcess django_app python-path=/var/www/lab python-home=/var/www/lab/venv … -
Creating a new viewset with multiple filters for the viewset get method
Hi i have a viewset that I am creating. I want to over ride the the get functino and get all the records that have the filtered parameter which is passed into the get view. I also want to be able to do the rest of the crud functionality - GET POST PUT DELETE - and use the paramater that is passed through the url as a parameter for the POST and UPDATE. Right now, when i pass in the parameter, rather than filter the data that is returned, it is giving me no details found which is not what i want. i want it to be used as a secondary filter for all the records that i get back from the database. Here is the code: viewset class PreferenceUserViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer class PreferenceNamespaceViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def list(self, request, namespace=None): # switch user_id value with logged in users id queryset = Preference.objects.all().filter(user_id=1, namespace=namespace) serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) urls: path('preferences/<str:namespace>/', PreferenceNamespaceViewSet.as_view({ 'get':'list' })), path('users/<int:pk>/stacks/', person_stack, name='user-stacks'), I … -
Does rest framework @action kwargs replace class values or not?
I have tried to search the answer for this question on rest framework docs or stackoverflow but I have not been able to find it. Suppose a rest framework viewset: class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() in this case, the extra_action action will have no permission nor authentication classes or will have the ones defined at class level? what happens if I override the get_permissions method? class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_permissions(self): permission_classes = self.permission_classes[:] if self.action == 'extra_action': permission_classes.append(MyPermissionClass) return [permission() for permission in permission_classes] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() Thank you for your help! -
How to enter ForeginKey values in a model with CreateView
I am creating a wiki and need to put in values in the model called revision. This table has a foreigkey to wikipage. My problem is that I am unable to insert values in the revision model. I have tried using def form_valid(self, form) like you would when entering user, without any luck. Models.py class Wikipage(models.Model): title = models.CharField(max_length=100) date_created = models.DateTimeField('Created', auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Wikipages" class Revision(models.Model): wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revisions') content = models.TextField('Content') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) last_edit = models.DateTimeField('Last Edited', auto_now=True) comment = models.TextField('Comment', blank=True) class Meta: verbose_name = 'Revision' verbose_name_plural = 'Revisions' ordering = ['-last_edit'] get_latest_by = ['last_edit'] def __str__(self): return self.content View.py Class WikipageCreateView(CreateView): template_name = 'wiki/wikipageform.html' model = Wikipage fields = ['title'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) The template are as simple as possible with {{ form.as_p }} and all the necessary stuff. -
how to use django_tables2 to filtering table containing data that does not come from django model
I am a newbie in Python and django. I'm creating web application which expose some part of HTTP API of one of my company Security System. Wrapper for the API I keep in file ReducedHXAPI.py. The only data which I keep in db are ip address of the Security System, and authentication data used to login to API. I successfully created a code which shows sortable list of hosts registered in company Security System. Now I'm trying to implement exporting created list of hosts and enabling inline filter for columns. Unfortunately all my attempts (based on tutorials and docs on: https://django-tables2.readthedocs.io/en/latest/index.html and https://django-filter.readthedocs.io/en/master/ ) produce only errors. Could someone help me in making it works and understanding philosophy of django_tables2 and django_filters, please? models.py: from django.db import models class ServerConnection(models.Model): ConnectionName = models.CharField('Connection Name', max_length=200, help_text="Enter name for this connection") ServerAddress = models.CharField('Server Address', max_length=200, help_text="Enter name or IP address of FireEye HX console") APIUser = models.CharField('API User', max_length=200, help_text="Enter name of user who has access to API") APIPassword = models.CharField('API Password', max_length=200, help_text="Enter name of user who has access to API") def __str__(self): """String for representing the Model object (in Admin site etc.)""" return self.ConnectionName ============================================================ views.py (extract) import … -
Sending email from modal in Django
I'm trying to create a simple contact form in a modal window and send email to console at the beginning but it doesn't work. I've got everything set. I've got email backend set correctly as I can send an email from the console. When opening the modal, the url of the website is not changing. Does it have something to do with this? This is what I'm getting in the console [02/Jul/2019 22:30:22] "GET /contact/ HTTP/1.1" 200 1224 [02/Jul/2019 22:30:29] "POST / HTTP/1.1" 200 2229 views.py def email(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): mail = form.cleaned_data["from_email"] subject = form.cleaned_data["subject"] message = form.cleaned_data["message"] send_mail(subject, message, mail, ["example@gmail.com"], fail_silently=False) messages.success("Done") return redirect("homepage") else: form = ContactForm return render(request, "home_page/contact_form.html", {"form": form}) forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) urls.py urlpatterns = [ path('', views.home, name='homepage'), path('contact/', views.email, name='contact')] And html {% load crispy_forms_tags %} <h1>Leave me a message</h1> <form method="post" action=""> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> -
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server
I created backend in Django with REST API and added these api with mobile apps but for website I am calling from another server which is built in .net framework now this server call API and then implement data with frontend. can you tell me this is good option or not because this is adding one another server means it can make my process slow and cost me more but for security purpose is it good or not? first I implemented my api direct in frontend but everyone can check my api and this can harm my website. I am creating e-commerce website. I didn't used php because I know .net better. -
Make ModelForm Field Larger in Django
I have a ModelForm where there is a description field. Django generates the field at its standard size but I'd like to make it, say, twice as large. I seem to be failing at Googling how to do this. HTML {% extends 'base.html' %} {% block body %} <div class="container"> <form method="POST"> <br> <br> <br> {% csrf_token %} <div class="column"> <label for="form.reference">Reference ID: </label><br> <!-- <input type="text" value="{{ reference_id }}">--> {{ form.reference }} <br> </div> <div class="description"> <div class="column"> <label for="form.description">Description: </label> <br> {{ form.description}} </div> </div> <div class="column"> <label for="form.cases">Cases: </label> <br> {{ form.cases }} <br> </div> <div class="column"> <label for="form.count">Count: </label> <br> {{ form.count }} <br> <br> </div> <br> <br> <button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button> </form> Forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') Again I am looking to increase the size of the field for 'description' -
How to get form widgets to render in custom template
I am attempting to have dJango form widgets render on my HTML page. forms.py assignment: class MenuItemsFormBase(forms.Form): name = forms.CharField(max_length=200) html assignment: <div class="col-sm-6 ce_name"> <b>Name:</b><br/> {{ form.name }} </div> From what I understand, this should create an element. Instead, it is rendering the following: " Ricky " What am I doing wrong that is preventing the widgets from rendering? -
Django CBV link product to user and allow to modify only his data
hello I did not understand the principle of django CBV for example I want to create an anonymous voting system and I want to make sure for example that the user can vote only once and I want to crypt also the vote and do some manipulation on the field. add to that I would like to know how to connect an object created to the user and thus allow it to change only these objects (election) my Model #model from datetime import datetime from django.http import Http404 from django.db import models, connection from django.db.models import Q from dzstudent import settings from django.contrib.auth import get_user_model User = get_user_model() class VotingNotAllowedException(Exception): pass class Election(models.Model): """ Represents elections. which can be composed of one or more ballots. Voting only allowed between vote_start and vote_end dates. """ userElec = models.ForeignKey( User, related_name="election", on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False, unique=True, help_text="Used to uniquely identify elections. Will be shown " + "with ' Election' appended to it on all publicly-visible pages.") introduction = models.TextField(blank=True, help_text="This is printed at the top of the voting page below " + "the header. Enter the text as HTML.") vote_start = models.DateTimeField(help_text="Start of voting") vote_end = models.DateTimeField(help_text="End of voting") def __str__(self): … -
Graphene query hangs indefinitely when testing with pytest
I am trying to test my backend, written in Django 2.2.2 and Python 3. I created some graphql queries which are definitely working when testing with the graphql web interface. When testing with pytest and the graphene test client, however, these queries would always hang indefinitely. I put together a reproducible example which is actually based on the code example from the graphene-django documentation. test_example.py: import pytest import graphene from graphene_django import DjangoObjectType from graphene.test import Client from django.db import models class UserModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class User(DjangoObjectType): class Meta: model = UserModel class Query(graphene.ObjectType): users = graphene.List(User) def resolve_users(self, info): return UserModel.objects.all() schema = graphene.Schema(query=Query) client = Client(schema) def test_user(): query = ''' query { users { name, lastName } } ''' result = client.execute(query) assert 0 # dummy assert This example behaves in the same way (stalls forever, no errors). I am using the latest graphene-django (2.3.2) and pytest (4.6.3). I should probably also mention that I'm running this inside a Docker container. Any ideas why this happens? Is this a bug in the graphene-django library? -
What jobs are available for js and Django web app development?
How useful is it in the current software engineer world to know how to make web apps with javascript frontend and Django backend? I want to make a web app from these but I also want to know if this fun project could get me a job doing the same thing at real companies. I have searched a lot on Google for answers but it just pops up with things like if JS is better than Python. -
Date Validation --> end date must be greater than start date
I need to write a script where it validates the end date is greater than the start date. Also the start date/end date cant be before the current date. Needs to be written in Django 1.8. -
Django migration - IntegrityError: null value in column "id" violates not-null constraint
This one has a slightly different flavor from the previous versions of the same question I've seen so far. In essence, the issue is in the django_migration table itself, when the migration object is being created. DETAIL: Failing row contains (null, orders, 0036_foo_migration, 2019-07-02 20:12:51.903881+00). The suggested solutions tend towards the "nuke-em-all" approach: Getting Null Value vilates integrity error when registering user or trying to migrate However, this is not an option for me as the database has been in production for quite some time, has many records, and cannot experience severe downtime. I cannot figure out why NULL is being recorded as the ID of the Django migration object - I've also tried resetting the auto-increment counter, but to no avail. Has anyone else seen this issue? -
How to use Django-jet with Django-oscar
I am trying to integrate Django-jet with Django-oscar, but keep getting the error django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: dashboard I have tried removing oscar core dashboard app from the installed apps list using OSCAR_HIDDEN_FEATURES but does not seem to work. -
Why does pip consistently fail to install pytest-django? .dist-info directory not found error
I have a docker container setup that keeps failing to install this pytest-django==3.4.8 from requirements.txt. If I comment it out everything else installs correctly. Tried everything from tearing down the setup and rebuilding to upgrading pip to deleting the pip cache and still nothing. Any help is appreciated! Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run prefix=options.prefix_path, File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 732, in install **kwargs File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 837, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 1039, in move_wheel_files isolated=self.isolated, File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 346, in move_wheel_files assert info_dir, "%s .dist-info directory not found" % req AssertionError: pytest>=3.6 .dist-info directory not found -
Django open an external link passing POST data
In my Django project i need to call from my function into my views.py an external page passing in POST format some data. i do this: in urls.py: ... url(r'^gocard/(?P<lic_num>\w+)/$', go_ccredit), ... in my views.py i create the function go_ccredit: def go_ccredit(request, lic_num=None, **kwargs): requests.post('https://www.example.com/form_test', data={'lid':lic_num,}) but i got an error because no HTTPResponse vas returned, and no page was open. I need to open an external page because i need to populate some form field with my data (using POST) and some other have to be populated by user. How can i open from my django function my external page passing data in POST ? So many thanks in advance -
How to stop logging sending message of length in django/python
In my settings.py Django project I have my LOGGING dict as LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { 'handlers': ['sentry'], 'level': 'DEBUG', 'propagate': False, }, }, 'handlers': { 'sentry': { 'level': 'DEBUG', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler' } } } Now my problem is as soon as I execute logging.debug("hello") It prints a message in my console that is b'Sending message of length 781 to https://sentry.io/api/12345/store/' It succesfully logs to sentr but how can I get rid of this message printing in my console? -
How to load images on Heroku (Django deployed app)
I've just recently deployed my Django application using heroku, and have an issue where the profile pictures in my blog website don't save (ends up being an image that never loads). Is there any way I can solve this (and if so, without using Amazon S3)? I want to avoid Amazon S3 if possible. Is there anyway or alternatives to implement images into my Heroku website? -
How do I debug individual Django tests in vscode?
I added a launch configuration that allows me to run all tests in dajnge and another that allows me to run the server, both of these work fine. I am looking for a way to debug an individual file, but using ${file} in the arguments gives a normal path which django doesn't like. I want a way to change ${file} into a python path, so that I can debug my tests on a single file. `python manage.py test --noinput --keepdb' python.path.to.my.file' works in the command line. The following configuration seems to be almost right: { "name": "Test File", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "test", "--noinput", "--keepdb", "${file}" ], "django": true }, However, when I run this configuration I get an error, which I think is because ${file} turns into path/to/my/file instead of path.to.my.file. -
Dynamically extending django models using a metaclass
The Problem I am trying to build a framework that automatically extends model classes with additional fields. Here is a short summary of what I am trying to do: Given a model class class Pizza(models.Model): name = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) I automatically want to generate a class with two additional fields per class field yielding a class similar to the following: class PizzaGenerated(models.Model): name = models.CharField(max_length=10) name_new = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) price_new = models.DecimalField(max_digits=10, decimal_places=2) as you can see, for each of Pizza's properties, an additional field with the _new suffix has been added. I need my solution to work irregardless of the Model's structure. In particular, I am looking for a way that allows the replication of ForeignKey-Fields My Approach The above example of extending the Pizza class is solvable with the following code: class ResMetaclass(models.base.ModelBase): def __new__(cls, name, bases, attrs): fields = { k: v for k, v in attrs.items() if not k.startswith('_') and isinstance(v, models.Field) } attrs_extended = { **attrs, **{fieldname + '_new': fieldtype.clone() for fieldname, fieldtype in fields.items()} } bases = (models.Model,) clsobj = super().__new__(cls, name, bases, attrs_extended) return clsobj class EntityBase(models.Model, metaclass=ResMetaclass): class Meta: abstract = True … -
Django many-to-many field filter select able options
I have a many-to-many field at this I want to filter the options displayed in the form. How can I do that? I found this here Django - filtering on foreign key properties but I don't know how to pass my object to the form. The view is an UpdateView. -
how to make "set or get cookies" in Django from js code so that when you switch to another page, the radio does not stop?
` MRP.insert({ 'url': 'http://s7.voscast.com:10196/armnews', 'lang': 'hy', 'codec': 'mp3', 'volume': 65, 'autoplay': true, 'forceHTML5': true, 'jsevents': true, 'buffering': 0, 'title': 'ArmNews 106.9', 'welcome': 'Բարլուս ազիզ', 'wmode': 'transparent', 'skin': 'faredirfare', 'width': 270, 'height': 52 );` -
name 'self' is not defined when running "Tutorial.objects.all()" in cmd
I am trying to do the webapp project using django here's the code in the model.py from django.db import models class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published') def __str__(self): return self.tutorial_title When running Tutorial.objects.all() in the cmd, it return errors "name self is not defined"