Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my js function works inside of script tag and why not in an external java script file django forms
I have a form that displays plain text when component is checked, in django like below class CompanySearchForm(forms.Form): check = forms.BooleanField() def __init__(self, *args, **kwargs): super(CompanySearchForm, self).__init__(*args, **kwargs) self.fields['check'].widget.attrs.update({"onclick": 'show_p()', 'id': 'check'}) And i have also my js file with the following function function show_p() { var checkBox = document.getElementById("check"); var texto = document.getElementById("text"); if (checkBox.checked == true){ texto.style.display = "block"; } else { texto.style.display = "none"; } } My template: {% extends 'base.html' %} {% load static %} {% block extra_styles %} <script href="{% static 'js/ajax_ubigeo.js' %}"></script> {% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.check }} </form> <p id="text" style="display: none">hola</p> {% endblock %} My question is why show_p() works inside of script tag and inside the template. But why not in an external java script file ? -
Django allauth - custom email verification url does nothing
I created a custom email verification url so that the user can be redirected to my react frontend before a get request will be sent. However, on sending the get request, a 200 status code is sent back but no email verification takes place. The url sent looks like this: http://localhost:8000/verify-email/Mw:1joams:KRlaiGKPx7fhQ6fHVYRtxvYo_v4/ and I am not sure if that key looks right. My codes look like these: #Adapter.py from allauth.account.adapter import DefaultAccountAdapter from django.conf import settings class DefaultAccountAdapterCustom(DefaultAccountAdapter): def send_mail(self, template_prefix, email, context): context['activate_url'] = settings.URL_FRONT + \ 'verify-email/' + context['key'] msg = self.render_mail(template_prefix, email, context) msg.send() #Urls.py from allauth.account.views import confirm_email url(r'^verify-email/(?P<key>\w+)/$', confirm_email, name="account_confirm_email"), ACCOUNT_ADAPTER = 'users.adapter.DefaultAccountAdapterCustom' Please can someone tell me what I am doing wrong? -
How to render information from a ForeignKey field through DetailView class?
I have two models (Taxonomia and Distribucion) which are the following: # models.py file class Taxonomia(models.Model): id_cactacea = models.AutoField(primary_key=True) subfamilia = models.CharField(max_length=200) class Distribucion(models.Model): id_distribucion = models.AutoField(primary_key=True) localidad = models.TextField(null=True, blank=True) taxonomia = models.ForeignKey(Taxonomia, on_delete=models.CASCADE, default=1) As you can see in Distribucion there is a one to many relationship with the Taxomia table. Implement the two models in the "admin.py" file so that you can edit the Distribucion table from Taxonomia class DistribucionInline(admin.TabularInline): model = Distribucion extra = 0 class TaxonomiaAdmin(admin.ModelAdmin): actions = None # desactivando accion de 'eliminar' list_per_page = 20 search_fields = ('genero',) radio_fields = {"estado_conservacion": admin.HORIZONTAL} inlines = [DistribucionInline] admin.site.register(Taxonomia, TaxonomiaAdmin) In turn, the file "view.py" renders the Taxonomia table as follows: from repositorio.models import Taxonomia, Distribucion class CactaceaDetail(DetailView): model = Taxonomia template_name = 'repositorio/cactacea_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['distribuciones'] = Distribucion.objects.all() return context I tried to access to context ['distribuciones'] information from the template as follows without getting any results: {% for obj in object.distribuciones %} {{ obj.localidad }} {% endfor %} OBS: For each Taxonomia element there will be four elements from the Distribucion table, so I need to use a FOR loop Is the way I add the information from the Taxonomia … -
AttributeError at /accounts/activate/Ng/5ho-db922c523f2c7f1a7f51/ 'str' object has no attribute 'objects'
I am implementating custom registration flow in which a user gets a verification email upon registration and thence clicks on the confirmation link to activate account. However, clicking the link gives this error: Internal Server Error: /accounts/activate/Ng/5ho-db922c523f2c7f1a7f51/ Traceback (most recent call last): File "/data/data/com.termux/files/home/webapps/django/Bloom/Bloom/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/data/data/com.termux/files/home/webapps/django/Bloom/Bloom/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/data/data/com.termux/files/home/webapps/django/Bloom/Bloom/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/data/com.termux/files/home/webapps/django/Bloom/accounts/views.py", line 118, in activate user = User.objects.get(id=uid) AttributeError: 'str' object has no attribute 'objects' I am using Django 3.0.7 and the function I think orchestrated this error is: def client_sign_up(request): msg = 'Input your credentials' if request.method == "POST": form = ClientSignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.birth_date = form.cleaned_data.get('birth_date') # user can't login until link confirmed user.is_active = False user.save() current_site = get_current_site(request) subject = 'Please Activate Your Account' # load a template like get_template() # and calls its render() method immediately. message = render_to_string('accounts/activation_request.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # method will generate a hash value with user related data 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) username = form.cleaned_data.get("username") raw_password = form.cleaned_data.get("password1") user = authenticate(username=username, password=raw_password) return redirect("accounts:activation_sent") else: msg = 'Form … -
use django-guardian with Custom User
I use custom user And i want to django-guardian to handle the permissions and groups. How i can do that my User : class ProfileUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=255,unique=True) first_name=models.CharField(max_length=255) last_name= models.CharField(max_length=255) departement= models.CharField(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] -
form not saving into user model Django
I'm currently processing a payment thing for an online subscription service and in order to get the users info to send this stuff, I have a payment form. But, for some reason the payment form is not saving to the users account. Everything else actually processes and the only error I can trigger is a 'NOT NULL constraint failed: memberships_usermembership.user_id' Here's what I have in my view - @login_required() def payments(request): user_membership = get_user_membership(request) selected_membership = get_selected_membership(request) form = SubscriptionForm() if request.method == "POST": form_data = { 'full_name': request.POST['full_name'], 'email': request.POST['email'], 'phone_number': request.POST['phone_number'], 'country': request.POST['country'], 'postcode': request.POST['postcode'], 'town_or_city': request.POST['town_or_city'], 'street_address1': request.POST['street_address1'], 'street_address2': request.POST['street_address2'], 'county': request.POST['county'], } token = request.POST['stripeToken'] form = SubscriptionForm(form_data) if form.is_valid(): customer = stripe.Customer.retrieve( user_membership.stripe_customer_id) customer.source = token customer.save() subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id, items=[ {"plan": selected_membership.stripe_plan_id}, ] ) user_membership = get_user_membership(request) selected_membership = get_selected_membership(request) user_membership.membership = selected_membership user_membership.save() form.save(commit=True) subscription_id = subscription.id sub, created = Subscription.objects.get_or_create( user_membership=user_membership) sub.stripe_subscription_id = subscription_id sub.active = True sub.save() try: del request.session['selected_membership_type'] except BaseException: pass return render(request, 'memberships/update-success.html') else: return redirect(reverse('membership_list')) context = { 'selected_membership': selected_membership, 'form': form, } return render(request, 'memberships/payment.html', context) When the form.save() is the line above the return(render) line, it will process everything as normal, and the form … -
How do I properly output a string for a YAML file that includes a "#"?
I'm using Django 3 and Python 3.7. I'm trying to write a function that will output properly formatted YAML. I have this ... def strip_invalid(s): res = '' for x in s: if Reader.NON_PRINTABLE.match(x): # res += '\\x{:x}'.format(ord(x)) continue res += x return res ... yaml_street = load(strip_invalid(street.strip().encode("utf-8", 'ignore').decode("utf-8"))) The problem is, if "street" is "55 E JACKSON BLVD # 150" the above outputs 55 E JACKSON BLVD Note that everything after and including the "#" was removed. How can I adjust the above so that everything is included but perhaps escaped properly for YAML output? -
Error trying to save data in django via ajax
I have a model that references other models, I am trying to save data using ajax Example: class Friend(models.Model): name = ... class Main(models.Model): name = .... friend = models.ForeignKey(Friend, on_delete=models.CASCADE) All body comes from ajax request data = json.loads(request.body.decode('utf-8')) Main.objects.create(name=data['name'], friends=data['friend_id']) This is the error raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Main() got an unexpected keyword argument 'Friends' Any idea or suggestion? -
Can I create a model to receive data for each ForeignKey in Django?
I need to display a form to user enter the quantity for each product (previously registered). For example... Product A: Quantity A Product B: Quantity B Product C: Quantity C I've already create a ProductModel: class ProductModel(models.Model): name = models.CharField(null=False, blank=False, max_length=20) code = models.CharField(null=False, blank=False, max_length=20) And I'm trying to set a model to the Order, like this one: class OrderDetailModel(models.Model): product = models.ForeignKey(ProductModel, on_delete=models.CASCADE) But how can I speccify the quantity related to a specific product? If I create something like this... class ProductModel(models.Model): ... quantity = models.IntegerField(default=0, null=False, blank=False) ... The quantity is a unique number related to each product, right? Or if I use.. class OrderDetailModel(models.Model): ... quantity = models.IntegerField(default=0, null=False, blank=False) ... I get a list in my form to choose the product and insert an unique quantity. Is there any way accomplish this? I'm using this Form: class QuantitiesForm(forms.ModelForm): class Meta: model = OrderDetailModel fields = ("product", "quantity") -
Force geopy to return multipolygon
Geopy's Geocoder wont return with a consistent object. Depending on the search term, it may return a Polygon or a MultiPolygon. GeoDjango (Postgis) wont let me enter a Polygon in a Multipolygon field. Can I ask geopy to always return a MultiPolygon? -
No Topic matches the given query
I'm learning Chapter 18 18.4.3 in Python Crash Course,when i open http://localhost:8000/topics/1 ,I get this problem-No Topic matches the given query. Django 3.0.7 and python 3.8 views.py from django.shortcuts import render,get_object_or_404 from .models import Topic def index(request): return render(request, 'learning_logs/index.html') def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request,'learning_logs/topics.html',context) def topic(request,topic_id): topic = get_object_or_404(Topic,id=topic_id) entries = Topic.entry_set.order_by('-date_added') context={'topic':topic},{'entries':entries} return render(request,'learning_logs/topic.html',context) urls.py app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('topics/',views.topics,name='topics'), path('topics/<int:topic_id>/', views.topic, name='topic'), ] topics.htmal {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li>{{ topic }}</li> <li> <a href="{% url 'topic' topic_id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> {% endblock content %} -
How do I reload Django Webapp code using gunicorn?
I've updated my Django webapp running on a Digital Ocean server and it keeps showing my old code. Is something being cached? I've tried everything to reload the code and nothing is working. Things I've tried: pkill gunicorn sudo systemctl daemon-reload sudo systemctl restart gunicorn kill -HUP masterpid kill -9 masterpid sudo systemctl restart nginx Literally nothing works. Has anyone else had this issue? I'm running my web browser in debug mode with caching disabled so it's not a browser issue. -
Efficiency of using JSONFields vs. Pure SQL approach Django Postgres
I am wondering what is the difference in efficiency using JSONFields vs. a pure SQL approach in my Postgres DB. I now know that I can query JSONFields like this: MyModel.objects.filter(json__title="My title") In pure SQL, it would look like this: MyModel.objects.filter(title="My title") Are these equal in efficiency? -
Is there a way to automate creation of pages(and slugs) as and when a record is created in Django
I'm trying to make a Django website which has all products with all their details(each product has it's own page). However, since there are too many products and they keep changing, I want to automate the creation and deletion of pages according to the database model (models.py). Am I supposed to use a class based view? Am I supposed to use a function based view with a loop in it? -
annotate query in Django
I want to .annotate() a query in Django with the count of the number of races a runner have made in the past, and another .annotate() to select the best chrono made by the runner in the past. class Horse(models.Model): id = AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True, default=None) class Race(models.Model): id = AutoField(primary_key=True) datetime_start = models.DateTimeField(blank=True, null=True, default=None) name = models.CharField(max_length=255, blank=True, null=True, default=None) class Runner(models.Model): id = AutoField(primary_key=True) horse = models.ForeignKey(Horse, on_delete=models.PROTECT) race = models.ForeignKey(Race, on_delete=models.PROTECT) chrono = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True, default=None) I trying to do something like this but I don't know how to make a subquery to access the past races, filtered whit the datetime_start and the horse_id from the current race: def statistic(request, race_id): race = Race.objects.get(id=race_id) runners = Runner.objects.filter(race_id=race.id) \ .annotate(nb_race=Count('race') \ .annotate(best_chrono=Min('chrono')) -
Why am I receiving maximum recursion depth exceeded error message?
Please can someone explain why I am recieving the following error? maximum recursion depth exceeded Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 3.0 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\template\base.py in __init__, line 640 Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe Python Version: 3.7.5 Python Path: ['Z:\\Development\\Intranet\\Education\\EducationProject', 'Z:\\Development\\Intranet\\Education\\EducationProject', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python37_64\\python37.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python37_64\\lib\\site-packages'] Server time: Thu, 25 Jun 2020 20:13:46 +0000 #from django.contrib import admin from django.conf.urls import include from django.conf.urls import url from . import views app_name = "EducationProject" urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^home/', views.homepage, name='home'), url(r'^about/',views.about, name='about'), url(r'^aboutcentre/', views.aboutcentre, name='aboutcentre'), url(r'^facilities/', views.facilities, name='facilities'), url(r'^staff/', views.staff, name ='staff'), url(r'^policy/', views.policy, name='policy'), url(r'^research/', views.research, name='research'), url(r'^teaching/', views.teaching, name='teaching'), url(r'^GCSE/', views.GCSE, name='GCSE'), url(r'^ALevel/', views.ALevels, name='ALevel'), url(r'^University/', views.University, name='University'), url(r'^Journals/', views.Journals, name='journals'), url(r'^Other/', views.Other, name='other'), url(r'^Curriculum/', views.Curriculum, name='curriculum'), url(r'^admissions/', views.admissions, name='admissions'), url(r'^accessibility/', views.accessibility, name='accessibility'), url(r'^employment/', views.employment, name='employment'), url(r'^vacancies/', views.vacancies, name='vacancies'), url(r'^applicationform/', views.applicationform, name='Application'), url(r'^declaration/', views.declaration, name='declaration'), url(r'^education/', views.education, name='education'), url(r'^postsixteeneducation/', views.postsixteeneducation, name='postsixteeneducation'), url(r'^presentemployment/', views.presentemployment, name='presentemployment'), url(r'^previousemployment/', views.previousemployment, name='previousemployment'), url(r'^gapsemployment/', views.gapsemployment, name='gapsemployment'), url(r'^otherinterests/', views.otherinterests, name='otherinterests'), url(r'^referee/', views.referee, name='referee'), url(r'^signature/', views.signature, … -
Rendering number of hits on a page in an API
I'm trying to render the number of pages my detailview gets with django-hitcount on my API. That means I need a field representing it in my serializers.py. I don't know how right this is, but adding hit_count_generic to my list of fields on in my serializers throws back the error: Object of type 'GenericRelatedObjectManager' is not JSON serializable I see the above when I try viewing on my browser. What field am I meant to use in representing the number of hits? -
Django query result SyntaxError: keyword can't be an expression
I'm trying a query in django shell that compares the username against a user given in a variable. variable usuario = 'john.doe' query EncabezadoReporte.objects.filter('user__username'= usuario) and I get the following error: SyntaxError: keyword can't be an expression my understanding is that everything before '=' is a keyword parameter, I don´t understando how to solve this. -
Saving a file to a specific folder using Django Form
I have a form that I am rendering with a FileField() After the form is submitted this is what I am doing in my views. def complete(request): file = request.POST.get('my_uploaded_file') ... get a instance of my object that this is saving to ... inst.file = file inst.save() return render(request, 'myapp/mypage.html') My model looks like this: class MyUpload(models.Model): file = models.FileField(blank=True, upload_to='user_uploads/') And my Forms class myForm(forms.Form): file = forms.FileField(label='File') Now when I select a file and click submit it, the file is updated in the model. When I try to view the image I get a 404 Error. This is the link it is linking me to in the admin panel http://localhost:8000/media/Roku.pcapng -
Display tasks count in base.html
I have a Task model and in my base template I want to display the number of tasks and a list of the tasks. How can I do this without having to import the Task model manually through my context dictionary in every view? Right now I have this: base.html <span class="notification">{{tasks.count}}</span> views.py def dashboard_view(request): context = { "tasks": Task.objects.all(), } return render(request=request, template_name='main/index.html', context=context) As one might imagine, having this in every view night not be practical. -
|as_crispy_field got passed an invalid or inexistent field Django Crispy forms
I'm trying to make a form for users on checking out a product in a shop. But I keep getting this error - '|as_crispy_field got passed an invalid or inexistent field' When I don't use crispy forms the form actually doesn't render at all, so I'm not sure what's going on here... Here's the HTML for my form - <fieldset class="rounded px-3 mb-5"> <legend class="fieldset-label small some-purple px-2 w-auto">Details</legend> {{ order_form.full_name | as_crispy_field }} {{ order_form.email | as_crispy_field }} {{ order_form.phone_number | as_crispy_field }} </fieldset> <fieldset class="rounded px-3 mb-5"> <legend class="fieldset-label small some-purple px-2 w-auto">Delivery</legend> {{ order_form.street_address1 | as_crispy_field }} {{ order_form.street_address2 | as_crispy_field }} {{ order_form.town_or_city | as_crispy_field }} {{ order_form.country | as_crispy_field }} {{ order_form.postcode | as_crispy_field }} {{ order_form.county | as_crispy_field }} <div class="form-check form-check-inline float-right mr-0"> <label class="form-check-label darkgreen section-text" for="id-save-info">Save this delivery information to my profile</label> <input class="form-check-input ml-2 mr-0" type="checkbox" id="id-save-info" name="save-info" checked> </div> </fieldset> I have the form stored in a forms.py file like such - class Meta: model = UserMembership fields = ('full_name', 'email', 'phone_number', 'street_address1', 'street_address2', 'town_or_city', 'postcode', 'country', 'county',) ..... And here's the view for the form - def payments(request): user_membership = get_user_membership(request) selected_membership = get_selected_membership(request) form = SubscriptionForm() if … -
Django Raw Field through multiple levels of relationship
I have a Django project where we are linking multiple levels of relationships through FK's and Many to Many relationships. Specifically I am trying to get the RAW ID field for one of these relationships but run into "has no attribute" or "unknown field specified" I am attempting to get the note text field from the note model. Thanks in advance: class Organization(AbstractExclusions, AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractOrganizationLocationCommonInfo, AbstractAcvitivyInfo): note = models.ManyToManyField('Notes', through="OrganizationNote", blank=True) class Notes(Model): note = models.TextField(blank=True) #this is the field we are after from the Organization level class OrganizationNote(Model): org = models.ForeignKey(Organization, on_delete=models.CASCADE,blank=True, null=True) note = models.ForeignKey(Notes, on_delete=models.CASCADE, blank=True, null=True) class Meta: verbose_name = _('Organization Note') db_table = 'organization_notes' -
Django Pass custom variables to template while using default views
I am currently using a default django view (PasswordChangeView), but I have my own custom template that I want to use with it. I am achieving this by writing this: path('changepassword/', PasswordChangeView.as_view(template_name='account/change_password.html', success_url = '/changepassword/'), name='password_change'), But in that template there is a variable like so: {{ var }}. Is there a way I can pass a value to that variable from urls.py? Or do I need to create an entire new custom view to pass this single variable? -
heroku error: "failed to push some refs to 'https://git.heroku.com/pacific-refuge-35090.git'
I'm trying to get my project pushed onto heroku but I am getting this error and I'm not sure why. I was initially getting a different error, but I think it was due to not having requirements.txt which I fixed. I am on the master branch. Still new to heroku so I am not sure what I am doing wrong. Went ahead and added, committed, and now just trying to push. How can I fix this ? Is it saying I am missing a static root? My static files work correctly locally. remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to pacific-refuge-35090. remote: To https://git.heroku.com/pacific-refuge-35090.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to … -
Django ORM value_lists() unpack ArrayListField
So I have a model something like this class Record(models.Model): name = models.CharField() synonyms = ArrayField(models.CharField()) and I do have the following records: Record 1 = Record(name=rec1, synonyms=['a','b']) Record 2 = Record(name=rec2, synonyms=['c']) Record 3 = Record(name=rec3, synonyms=['d','e']) I want to get only synonyms for all records in a list. I've tried: synonyms_list = Record.objects.all().values_list('synonyms') And it return: [['a','b'],['c'],['d','e']] But i want it to unpack the synonym list and I want the result to be something like this ['a','b','c','d','e'] Is it possible to do it using Django ORM or using postgres query ?