Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement a semantic search in a Django blog project
I am working on implementing a semantic search in my Django Blog app. e.g. yesterday post, latest posts on machine learning etc. Is there any framework to do so? Do I have to use Machine Learning for it? -
URLconf does not appear to have any patterns in it/Circular import error
I am following a tutorial found in the Django documentation and upon attempting to map a view to a URL I received the following error: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'pollSite.urls' d oes not appear to have any patterns in it. If you see valid patterns in the file th en the issue is probably caused by a circular import . I have a pollSite project and a poll app. pollSite/pollSite/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] pollSite/poll: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world") I thought I may have mistyped something so I went back and copied the code from the docs and pasted it directly into my editor and still got the same error. I'm not sure what a circular import is but I am also working with virtualenv for the first time and am not sure if that could be causing this. Any suggestions? Tutorial incase anyone was interested: https://docs.djangoproject.com/en/2.2/intro/tutorial01/ -
Cannot test session params within Django test
I have home template that shows the message if it's provided: base.html <main role="main"> <div class="container"> {% if message %} <br> <span class="text-success">{{ message }}</span> <br><br> {% endif %} {% block content %} {% endblock %} </div> </main> home.html {% extends 'base.html' %} {% block content %} <span>Hello</span> {% endblock %} views.py def home(request): params = {} if 'message' in request.session and request.session['message']: params['message'] = request.session['message'] del request.session['message'] return render(request, 'products/home.html', params) And test for this code that I cannot make work: class HomeTests(TestCase): def test_home_shows_message_if_session_param_is_provided(self): self.client.session['message'] = 'test' self.client.session.save() response = self.client.get(reverse('home')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'products/home.html') self.assertContains(response, 'test') I get AssertionError: False is not true : Couldn't find 'test' in response. That's because request.session doesn't contain message param so I set it in incorrect way. Please help me to find the correct one. -
Why are the selected values removed from the multi select in the admin page?
I wrote a multi-select form for the admin page. The selected data is saved in the database, but for some reason it is not displayed as selected (no selected property). When I try to save the object again, I get an error that the data in this field is not selected. It seems that when refresh the page, the selects just fly off. What could be the problem? I'm use Django 1.9 and django-jet. models.py registration = models.CharField(_('registration'), max_length=255) forms.py class ConditionAdminForm(forms.ModelForm): REGISTRATION_CHOICES= ( ('Any', _('Any')), ('Constant', _('Constant')), ('Temporary', _('Temporary')), ) registration = forms.MultipleChoiceField(choices = REGISTRATION_CHOICES, label=_("registration form")) def clean_registration(self): registration = self.cleaned_data['registration'] if not registration: raise forms.ValidationError("...") registration = ', '.join(registration) return registration class Meta: model = Condition fields = '__all__' admin.py class ConditionInlineAdmin(admin.StackedInline): model = Condition form = ConditionAdminForm admin html <div class="form-row field-registration"> <div> <label class="required" for="id_condition_set-0-registration">registration:</label> <select multiple="" id="id_condition_set-0-registration" name="condition_set-0-registration" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"> <option value="Any">Any</option> <option value="Constant">Constant</option> <option value="Temporary">Temporary</option> </select> <span class="select2 select2-container select2-container--jet" dir="ltr" style="width: auto;"> <span class="selection"> <span class="select2-selection select2-selection--multiple" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false" tabindex="0"> <ul class="select2-selection__rendered"> <li class="select2-search select2-search--inline"> <input class="select2-search__field" type="search" tabindex="-1" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" placeholder="" style="width: 0.75em;"> </li> </ul> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span> </div> </div> -
What is the correct way to store transactions
I'm trying to use Django to build an app that will record transaction between entities. Entities could be a person or a company. Then I would like to build a functionality where I can record transactions between entities. Examples of the type of transactions I would like to record, Entity A Brought x Share of Entity B Stock from Entity B. Entity A Brought y Share of Entity B Stock from Entity C. Entity A Sold z Share of Entity B Stock to Entity B. What are some tables/models and fields I would need to achieve this? -
settings file's variable manages from database in django
Is possible to load variable's value from database dynamically in django? I'm new in django. I tried to give value to this settings.py's file variable from admin panel on django. settings.py RECAPTCHA_PUBLIC_KEY = '' #How to set this value from admin panel dynamically RECAPTCHA_PRIVATE_KEY = '' I have to implement settings.py's variable from database. can i change value from database? in django -
What is the use of forms.py file and class myform(): in an app when we have CLass Base dViews (CBV)?
As I am new to Django and there is not much information about the use of defining forms.py file with form classes and where are they used. I mean to say that we can do all of the work by CBV, then what is the use of Function based view and explicitly defining Forms classes inside forms.py. Any help would be appreciated. -
How to Prefill Form with URL Parameters (Django)
I would like to prefill a form with URL parameters, but I am unsure as to how I should configure my URLs. I need to fill multiple fields, so is using URL parameters still the best method? In the tutorials I have been reviewing, most cases only use 1 or 2 parameters from the GET request. In my view, I am only handling one field currently as I am having trouble with just one parameter. You can see in the form model the other fields I would like to fill. Any help is greatly appreciated! views.py def new_opportunity_confirm(request): form_class = OpportunityForm account_manager = request.GET.get('account_manager') form = form_class(initial={'account_manager': account_manager}) return render(request, 'website/new_opportunity_confirm.html', {'form': form}) urls.py re_path(r'new_opportunity/new_opportunity_confirm/(?P<account_manager>\w+)/$', view=views.new_opportunity_confirm, name='new_opportunity_confirm'), new_opportunity_confirm.html <form action="" method="post" name="newOpportunityForm" id="newOpportunityForm"> {% csrf_token %} <div class="field"> <label class="label">Account Manager:</label> <div class="select"> <select name="account_manager" id="account_manager" required> <option value="{{ form }}">{{ form }}</option> </select> </div> </div> -
Hov can get the translated values in select?
I get select with values Without and With. How can I get already translated values Без and С in django.po in a select? models.py CONFIRMATION_WITHOUT = 'without' CONFIRMATION_OTHER = 'other' CONFIRMATION_WITH = 'with' CONFIRMATION_CHOICES = ( (CONFIRMATION_WITHOUT, _('Without')), #Без (CONFIRMATION_OTHER, _('Other')), #Другое (CONFIRMATION_WITH, _('With')), #С ) income_proof = models.CharField(_('proof'), max_length=255, choices=CONFIRMATION_CHOICES, default=CONFIRMATION_WITHOUT) #[u'without', u'with'] forms.py income_proof = forms.ModelChoiceField(queryset=CreditPayment.objects.values_list('income_proof', flat=True).distinct(), widget=forms.Select(attrs={'class': 'selectpicker form-control', 'title':_("Income proof")})) html {{ form.income_proof }} -
Django Rest API Type error for positional argument
Django fires me this error and i am not getting why.. TypeError at /api/v1/article __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/article Django Version: 2.2.2 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given This is my serializer class: class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'title', 'body', 'category'] these are my models: from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) detail = models.TextField() class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) And this is my view class ArticleListCreateGet(ListAPIView, CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer and this my url path('api/v1/article', views.ArticleListCreateGet, name='article'), I am not getting whats wrong with my code, can anyone tell me why i am seeing above error? -
What is the best DB-design of used car in django
I have fixed list of Makes and Models which belongs to certain Make and ModelYearNames which also belongs to Models; ex) . hyundai / aaa / 2010 new a~2014a hyundai / aaa / 2015~ a~ hyundai / bbb / 2014~ new b audi / ttt / 2010~ new t audi / qqq / 2019 car Mto1 make make 1toM model model 1toM modelYearName car Mto1 modelYearName car Mto1 model Here's what I've designed so far, class Manufacturer(models.Model): make = models.CharField(max_length=30, primary_key=True) class Model(models.Model): make = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) model = models.CharField(max_length=40) class ModelYearName(models.Model): model = models.ForeignKey(Model, on_delete=models.CASCADE) model_year_name = models.CharField(max_length=50) class Car(models.Model): make = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) model_year_name = models.ForeignKey(ModelYearName, on_delete=models.CASCADE) Is this the best way to design the DB table? If so, How do I save, for example, a record that showing Make, Model, ModelYearName that is in correct hierarchy? (ex 2014~ new b(ModelYearName) should be paired only with bbb(model), hyundai(make) -
Remove, add and modify fields dynamically in django
I want to give a choice to my users by Add/Remove/modify fields, and then save them in the database dynamically if Data was modified. I use Django version 2.1, Thanks for help -
save() missing 1 required positional argument: 'self' Error while using Django Signal Dispatcher
models.py class es_event(models.Model): #some attributes reg_applicants = models.FilePathField(path=None) ev_admin = models.ForeignKey('es_user',related_name='events',on_delete=None) slug = models.SlugField(max_length=250) def save(self, *args, **kwargs): self.slug = slugify(self.ev_name) return super(es_event, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('event_detail', kwargs={'id': self.id, 'slug': self.slug }) views.py class CreateEventView(LoginRequiredMixin,CreateView): login_url = "/login/" model = es_event fields = ['ev_name','ev_venue','ev_description','ev_date','registrant_name','registrant_age','registrant_phone','registrant_email','registrant_institution'] def form_valid(self, form): form.instance.ev_admin = self.request.user.es_user return super(CreateEventView, self).form_valid(form) Now when a new row is added to es_event. I want to set the reg_applicants field with a path(including filename) eg: if es_event.id is 5 then filename should be Registered_5.csv To do that I created this Signal in models.py @receiver(post_save, sender=es_event) def set_csv_path(sender, **kwargs): rel_path = "reg_csv/Registered_{}.csv".format(sender.id) path = os.path.join(settings.MEDIA_ROOT,rel_path) sender.reg_applicants = path sender.save()# error statement which gives me this error save() missing 1 required positional argument: 'self' I think there is something wrong with the signal dispatcher function set_csv_path(). I don't know what it is -
Django and OAuth2 - 403 Unauthorized: Authentication credentials were not provided & 401 Forbidden
I have an auth server running via Okta, but I didn't make Django work with OAuth2. I've read and tried several tuts and docs and now I'm a little confused. I test my API and grab a new access token via Postman, but when I connect to it, I get two different unauthorized error. On http://localhost:8000/api/love-buddy I get Status: 401 Unauthorized: {"detail": "Authenticationcredentials were not provided."} On http://localhost:8000/api/hello I get Status: 403 Forbidden" And http://localhost:8000/api/user is working without an access token. How can I protect my Django resource server with OAuth2 and how do I make a successful access? settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'analytics', 'rest_framework', 'rest_framework_mongoengine', 'oauth2_provider' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } urls.py # OAuth2 provider endpoints oauth2_endpoint_views = [ url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name="authorize"), url(r'^token/$', oauth2_views.TokenView.as_view(), name="token"), url(r'^revoke-token/$', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"), ] if settings.DEBUG: # OAuth2 Application Management endpoints oauth2_endpoint_views += [ url(r'^applications/$', oauth2_views.ApplicationList.as_view(), name="list"), url(r'^applications/register/$', oauth2_views.ApplicationRegistration.as_view(), name="register"), url(r'^applications/(?P<pk>\d+)/$', oauth2_views.ApplicationDetail.as_view(), name="detail"), url(r'^applications/(?P<pk>\d+)/delete/$', oauth2_views.ApplicationDelete.as_view(), name="delete"), url(r'^applications/(?P<pk>\d+)/update/$', oauth2_views.ApplicationUpdate.as_view(), name="update"), ] # OAuth2 Token Management endpoints oauth2_endpoint_views += [ url(r'^authorized-tokens/$', oauth2_views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), url(r'^authorized-tokens/(?P<pk>\d+)/delete/$', oauth2_views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete"), ] urlpatterns = [ path('', … -
DoesNotExist at /login/ Group matching query does not exist
I am Trying to Solve one Problem related to "Group matching query does not exist." Error But Going Nowhere , It's getting more Trickier for me to Solve , NEED HELP !!? I Have Already tried SITE_ID = 1 in Settings.py but Nothing Happened Views.py : = from django.shortcuts import render from django.views.generic import TemplateView from django.http import HttpResponseRedirect from django.contrib import auth from django.template.context_processors import csrf from django.contrib import messages # Create your views here. def user_login(request): if request.user.is_authenticated: messages.add_message(request, messages.INFO, 'You are already Logged in.') return HttpResponseRedirect('/home') else: c = {} c.update(csrf(request)) return render(request, 'loginmodule/login.html',{}) context_processors.py := from django.contrib.auth.models import Group def hasGroup(user, groupName): group = Group.objects.get(name=groupName) return True if group in user.groups.all() else False def menu_processor(request): menu = {} user = request.user if hasGroup(user, 'Consultant'): menu['Appointments'] = '/appointment -
`manage.py inspectdb` tells me that I don't have an ENGINE specified in my default database, but the docs say that default can be blank
I'm creating a django web app that is going to be a database management portal for multiple databases. Because the web app will touch multiple databases, it doesn't make sense to have a default. However, when I run manage.py inspectdb I get an error saying that the ENGINE value isn't set on my database. It most definitely is. Here's my DATABASES setting in settings.py DATABASES = { 'default': { }, 'my_db': { 'NAME': 'my_db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '192.168.0.255', 'PORT': '', 'ENGINE': 'sql_server.pyodbc', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } If I run manage.py inspectdb using this setup I get this error: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. This doesn't make sense to me, since it says in the documentation that 'default' can be a blank {}. However, if I supply a dummy NAME and ENGINE variable to the default db, it seems to work fine for the default DB, but it ignores my_db. If I set default to look at my_db's information I get a login error (so I know at least something is working right there, even if my creds are bad). So, … -
Django task scheduler for windows
Is there a django task scheduler for windows 10 ? I have gone through entire google search it seems and there is nothing that I can make work for django server running on windows. -
Django: send message to all users (sessions)
I have a python+django project and want to implement following functionality: by certain trigger (at certain time or by manual admin action) show message to all active users (i.e. to all sessions). Webpush seems unnecessary here as far as django has nice built-in messages subframework. I guess I may develop such functionality manually: make sql table session_messages, each time take snapshot of all sessions and show message, perform some checks to assure that message is shown only once and only to active users, etc. etc. Question: maybe there is some nice little library that already does it? Or even maybe django messages are able to do it "from the box"? I've googled a bit but found only packages for webpush integrations. Thanks :) -
How to make my html button disabled if a model Boolean field of false
I’m trying to create a like button and dislike button. My button works, but users can click it more than one time, which they shouldn’t be able to . Here is my modal: Here is my view: Here is my buttons in html How to only allow the user to press the button one time? And also if you know, how to make it so when I press the like button , the whole page does not reload in Ajax -
How to interact with a REST api made with DRF
I am trying to use a REST api made with django REST framework to send data to my react native app. For authentification, I am using allauth which creates an authtoken when a user is created. My problem is: I don't know what to do next (once I have the token). I want to be able to retrieve my user's data with the API, but I don't know how to handle the authentification with DRF. Do I have to send the token every time I make a request? If yes, what would the json would like? (frontend with react native) How do I send the data back? Would it look like this: def sendUsername(request): return request.user.get_username() if not how? and if yes, it doesn't look very safe so is there a way to make it at least a little bit more secure? I am really new to this so sorry if it looks dumb. Thank you for your time. -
How to fix "Default VPC not found" error during Django app deployment to Elastic beanstalk ( I created Default VPC but no luck )
Note: I am pretty new to the AWS world so please let me know if I could improve my questions in any way by providing additional info. Thanks! I am trying to deploy a basic Django app to Elastic Beanstalk following this AWS documentation as an IAM user with AdminAccess permissions. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But the process failed In this step https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-deploy when I try to create a new env The error is about default VPC not found. After seeing this error I tried to create a default VPC following this stack overflow post: Creating load balancer failed Reason: Default VPC not found After setting up the default VPC I retried creating a new env but no luck, just got the same error. Does this look familiar to anyone? I am seeing the following error: Creating application version archive "app-190621_102335". Uploading django-new-turt/app-190621_102335.zip to S3. This may take a while. Upload Complete. Environment details for: django-test-env Application name: django-new-turt Region: us-east-1 Deployed Version: app-190621_102335 Environment ID: e-mrnu7mxmuu Platform: arn:aws:elasticbeanstalk:us-east-1::platform/Python 3.6 running on 64bit Amazon Linux/2.8.6 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2019-06-21 14:23:39.348000+00:00 Printing Status: 2019-06-21 14:23:38 INFO createEnvironment is starting. 2019-06-21 14:23:39 INFO Using elasticbeanstalk-us-east-1-970880513547 as Amazon S3 storage bucket for environment data. … -
How to capture network traffic with selenium
I'm starting a new Django project, I'm trying to capture the network traffic with Selenium. I have already achieve this objective with Selenium-wire, but Django doesn't like to work with selenium-wire ( must start the server with "--nothreading --noreload", connection bug... ). I'm looking for achieve this with modern solutions, like parsing the network devtools of firefox directly or with a firefox addons. I'm using Firefox Geckodriver for my test. for x in range(0, 10): profile = profile_firefox() options = options_firefox() driver = webdriver.Firefox(firefox_profile=profile, options=options, executable_path='/Users/*****/Desktop/selenium-master/headless_browser/geckodriver') try: driver.set_window_position(0, 0) driver.set_window_size(randint(1024, 2060), randint(1024, 4100)) time.sleep(randint(3,10)) driver.get(url) wait = ui.WebDriverWait(driver, 10) time.sleep(randint(8,10)) if driver.find_element_by_xpath("//*[@id=\"container\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button"): driver.find_element_by_xpath("//*[@id=\"container\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button").click() del driver.requests time.sleep(randint(8,10)) driver.find_element_by_xpath("//*[@id=\"container\"]/main/div/div/div[1]/div[2]/form/div/div[2]/div[1]/button").click() time.sleep(randint(10,20)) for request in driver.requests: if request.path == "https://api.*********.**/*******/*******": request_api = request raw = str(request_api.body) request_api = raw.split(('b\'')) payload_raw = request_api[1] payload = payload_raw[:-1] if payload: header = request.headers time.sleep(8) break except: print("Houston on a eu un probleme") firefox_closing(driver) Thanks a lot if you have any clue or advice about my code or solutions. -
django-scheduler not performing expected job
I am using the package from here After I perform python manage.py runserser I was expecting that `print("Scheduler started!")' would print on the console every 5 seconds but I do not see that. What am I missing ? -
Manager still not available event with the get_user_model method
I'm trying to give the user the possibility to update his profile. The situation is the following : I have a custom User Model (Member) with a Babysitter Profile available under the unique condition to precise that you are a Babysitter. I almost found a way to get the complete form (Member + Babysitter - two forms in one). But there are two issues, the main issue is when i'm trying to save the entire profile after the update, i still get the following message : "Manager isn't available; 'auth.User' has been swapped for 'accounts.Member'", event with the get_user_model method. And the second issue, less important for now, is that i don't find a way to get the actual data displayed in form so the user can update it. Here's the code forms.py from apps.authentication.babysitters.models import Babysitter from apps.authentication.accounts.models import Member from django import forms from django.contrib.auth.forms import UserChangeForm # Getting a custom user model from django.contrib.auth import get_user_model class MemberProfileForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email', 'full_name', 'password', 'is_babysitter',) class BabysitterProfileForm(forms.ModelForm): class Meta: model = Babysitter fields = '__all__' exclude = ('member',) member -> models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.utils import … -
I found an Autocomplete plugin on the web but I do not understand how to implement it in my template
Can you help me with this plugin : https://www.jqueryscript.net/form/Bootstrap-Combo-Box-Typeahead-Plugin-jQuery.html I'm using Bootstrap 3 and I already put the plugin in my static folder. I tried to put an id to my select field but it doesn't worked. forms.py class IndividuForm(forms.Form): individu = forms.ModelChoiceField(queryset=Individu.objects.order_by('nom'), empty_label="") def __init__(self, *args, **kwargs): super(IndividuForm, self).__init__(*args, **kwargs) self.fields['individu'].widget.attrs={'class': 'combobox','id':'mySelect'} The script <script> $('.mySelect').combobox() </script>