Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error in the verification of a select in a form with javascript
I have a form with multiple choices. What I'm trying to do is the following: I want my form choices not to be repeated, I mean, if I choose one option, it can't be chosen again. I have the following javascript code, but when I choose any option, the alert goes on. Does anybody what error does my code have? Feel free to ask anything you want <script> function validar(){ var pad_gris = $("#id_nota_pad_gris").val(); var pad_verde = $("#id_nota_pad_verde").val(); var pad_azul = $("#id_nota_pad_azul").val(); var pad_rojo = $("#id_nota_pad_rojo").val(); var pad_amarillo = $("#id_nota_pad_amarillo").val(); if ((pad_verde == pad_gris) || (pad_gris == pad_verde)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_azul == pad_verde) || (pad_verde == pad_azul)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_verde == pad_amarillo) || (pad_amarillo == pad_verde)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_verde == pad_rojo) || (pad_rojo == pad_verde)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_gris == pad_azul) || (pad_azul == pad_gris)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_gris == pad_amarillo) || (pad_amarillo == pad_gris)){ alert("Seleccione valores distintos !!"); //reset form document.getElementById('formulario').reset(); } else if ((pad_gris == pad_rojo) || (pad_rojo == pad_gris)){ … -
Django test -- Model object created but cannot be found
I'm calling a Model which is called People and do People.objects.create(first='foo', last='bar', bio='test') This Model uses db_table='"people"."background"' When I run the test, doing People.objects.first() finds something, but doing raw query like SELECT * from people.background gives me nothing. Why is that? -
Issue reaching Django server on AWS Elastic Beanstalk
I have an EB instance running Python 3.6 and Django. I've successfully run the Django app and it appears to be listening on port 8000. I've created a security group that opens all TCP ports and assigned it to that EB instance. When I try to surf to that port, I get a "This site can’t be reached" response in the browser. Any ideas? -
Referencing Object/Model field with dictionary key
I'm looping through a dictionary that has keys that match the fields in an Object Model. With the value from the said dictionary, I query an address and gather some data that I want to then save in the Object. My hope was to use the key from the dictionary to reference the field within the object. I'm having a hard time explaining this with text so I hope the example code below showcases what I'm trying to do. example_dict = { "key": "value", "second_key": "second_value" } class ExampleModel(models.Model): key = models.CharField(max_length=255) second_key = models.CharField(max_length=255) } object_example = ExampleModel() for key in example_dict: data = doDataRequest(key) object_example[key] = data object_example.save() -
How can I use agent feature in my django oscar application?
I have chosen Django oscar for my e-commerce site development. In the meantime, I am looking for a feature like an agent, where they will help buying products from my e-commerce site to the users and I will give them an affiliation profit which will be stored at their wallet. For this feature, I will have to have an internal wallet system which can be debited and credited for agent use only. I am having great travel already. Really looking forward to your kind help. Thank you all. -
How to integrate a payment solution for a marketplace in Django?
The concept of my website is something like a fiverr marketplace - people can request something, other people can offer something to this specific request. The requester can choose what to buy from the offering person(s) and I will take some fees of it. I really do not know where to start. The refunding option, the pay-out for content offering user.. obviously, I want to make it as easy as possible for all involving persons. Should I receive the money and the content offering user has a balance on my site? If yes, how about the pay-outs? Should I just split the payment, like fees to me, payment to the offering user? Where should I start? -
JQuery/JS Regex "Invalid regular expression: missing /" Error
I am designing a Django web app and having some trouble with a Regex error. The part that is not working correctly basically loads the details of any products in the database and displays them in a table. Next to the details, I want a button that will allow the user to view the product in greater detail. I haven't written that part of it yet but right now when I click on the button, it returns a Uncaught SyntaxError: Invalid regular expression: missing / error. This is the code here: <!DOCTYPE html> <html> <body> <div> <h2 id="title">Create product</h2> <input id="name">Name</input> <br> <input id="description">Description</input> <br> <input id="price">Price</input> <br> <button id="add-product">ADD PRODUCT</button> </div> <table id = "product-table"> <td> <button id = "myButton"></button> </td> </table> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ getData(); }); document.getElementById('add-product').onclick = function(){ sendData(); getData(); } function getData(){ $.ajax({ url: 'product/view', dataType: 'json', type: 'GET', success: function(data){ $('#product-table').empty(); var dmJSON = "http://localhost:8000/product/view"; $.getJSON(dmJSON, function(data) { $.each(data, function(i, f) { url = "product/view/" + f.id ; console.log(url); var button = "<button onclick=location.href"+url+"> View product </button>" ; var tblRow = "<tr>" + "<td> ID: " + f.id + "</td>" + "<td> Name: " + f.name + "</td>" + "<td> Description: " … -
bind setAttribute() on form value change
basic jquery question: I have a select2 select where i want to change a CSS background image of a div based on which option is selected and pass it django view context. on change, I can temporarily set the background img, but it only lasts during the change event, then reverts back and gets overwritten by the style file. the other issue is that {{ cover_image_url }} which is django template context displays the last select {{ cover_image_url }} value, not the current one (ex: change select from N1 to N2, no background-image change. change select form N2 to N3, it displays background-image for N2 not N3) how can I bind the change so it's permanent until the page reloads or the select option is changed again? thanks <script> $(document).ready(function() { $('.tags').select2({ selectOnClose: true }).on("change", function(e){ if(this.value != "/"){ // set this background until the next change document.getElementById("image-div").setAttribute("style","background-image:url('{{ cover_image_url }}')!important;") } }); }); </script> -
Django2: Saving instances to model from model formset in view using manual methods
I have a formset which I create model instances in my view. However this is a lot of code and to separate it out I use manual class view methods: class ClassView(LoginRequiredMixin, GroupRequiredMixin, View): template_name = 'form.html' form = Form get(self, request, *args, **kwargs): formset = modelformset_factory( Model, form=self.form, formset=BaseFormSet, extra=0, ) self.formset = formset(queryset=qs) def post(self, request, *args, **kwargs): user = request.user formset = modelformset_factory( Model, form=self.formform, formset=BaseCRVFormSet, extra=0, ) if request.POST['submit'] == 'Submit form': sample_id = request.POST.get('sample_id') obj = Sample.objects.get( id=sample_id ) formset = formset(request.POST) if formset.is_valid(): for form in formset: self.reportVariant(form) self.reportSample(obj, user) def reportVariant(self, form): crv_obj = form.save(commit=False) report = form.clean_report() if report == 'report': # Final report for variant crv_obj.final_reported = True crv_obj.final_report_date = timezone.now() crv_obj.final_vasr_id = crv_obj.primary_vasr_id crv_obj.primary_vasr_id = None crv_obj.save() else: ...more... def reportSample(self, obj, user): ... more saving to model ... My question is, should I be doing this in my form class? After cleaning, calling my methods there reportVariant() methods as an extra to the form class? -
from ckeditor_uploader.fields import RichTextUploadingField
After installing the ckeditor from pip. i try to import ckeditor from models but it keeps giving me ImportError cannot import name get_default_renderer. after i followed the ckeditor documentation thoroughly it still gives me this error. am i doing something wrong or is it my django version 1.10 or the ckeditor version 5.6.1 of which i can see the folder in my project directory## my models.py from django.db import models from django.conf import settings from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete= models.CASCADE) title = models.CharField(max_length=200) text = models.RichTextUploadingField() image = models.ImageField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank= True, null = True) my views.py from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Post from .forms import CommentForm # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'blog/post_list.html', {'posts':posts }) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/post_detail.html', {'post':post, 'form':form }, ) this are my settings.py INSTALLED_APPS = [ 'app', 'cart', 'orders', 'blog', 'ckeditor_uploader', # Add your … -
Django - Edit fieldset field options
so I have a Model that contains a ManyToMany attribute and in the fieldset this displays a full list for this attribute to edit or create. But, in this model I want to show just the active objects on fieldset for create/edit, how can I do it? I tried to write functions, get functions... The only way is merge a function and readonly but is not editable... Models.py class MyModel(models.Model): active: booleanField() So, I want to show in fieldsets just the active=True objects -
Django, how to get sum of two field values
models.py class Iso(models.Model): service_type = models.CharField(max_length=100, blank=True, null=True) field_1 = models.IntegerField(blank=True, null=True) field_1_size = models.IntegerField(blank=True, null=True) field_2 = models.IntegerField(blank=True, null=True) field_2_size = models.IntegerField(blank=True, null=True) In my views.py I have two queryset as follows, now if I want to combine together the queries and if user enters the field_1 value and field_2 value same, it should be summarized. qs1 = Model.objects.values('service_type', 'field_1')\ .annotate(field_total=Sum('field_1_size')) qs2 = Model.objects.values('service_type', 'field_2')\ .annotate(field_total=Sum('field_2_size')) I tried, qs_tot = qs1.union(qs2) it combines queryset but not gives a sum value, if the field_1 and field_2 are same. Any helps will be greatly appreciated. Thank you. -
Django Rest Auth - Key error on Email Confirmation
I am trying to setup email verification in DRF using rest-auth. The registration works correctly and the verification email is sent. However, when going to the verification link I receive a key error. What I understand is that means that this verification key doesn't exist, but I don't understand how to fix that given that the registration process was supposedly a success? I have the following paths in my urls.py: path('', include('rest_framework.urls', namespace='rest_framework')), path('', include('rest_auth.urls')), path('registration/', include('rest_auth.registration.urls')), path('registration/', RegisterView.as_view(), name='account_signup'), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<pk>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'), The following settings in my settings.py: ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = '/' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = False ACCOUNT_EMAIL_REQUIRED = True And this is a screenshot of the error I am getting: Key error -
django FormView not creating object or redirecting to success_url
trying to implement a django form via class-based FormView and following the docs isn't working for me (https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/. Project is 1.11.9 models.py class Contact(models.Model): name = models.CharField(max_length=100) company = models.CharField(max_length=100) email = models.EmailField(unique=True) message = models.TextField() date_created = models.DateField(verbose_name="Created date", auto_now_add="True") forms.py from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact labels = { 'company': 'Company or Organization' } exclude = ('date_created',) views.py from django.shortcuts import render from django.core.mail import send_mail from django.views.generic import FormView, TemplateView from .forms import ContactForm class ContactFormView(FormView): form_class = ContactForm template_name = "contact.html" success_url = '/thanks/' def form_valid(self,form): message = "{name} from {company} / {email} said: ".format( name=form.cleaned_data.get('name'), company=form.cleaned_data.get('company'), email=form.cleaned_data.get('email')) message += "\n\n{0}".format(form.cleaned_data.get('message')) send_mail( subject='new message', message=message, from_email='foo@bar.com', recipient_list=['foo@blah.com',] ) form.save() return super(ContactFormView, self).form_valid(form) urls.py from django.conf.urls import url from django.views.generic import TemplateView from . import views from .views import ContactFormView urlpatterns = [ url(r'^contact/?$', ContactFormView.as_view(), name="contact"), url(r'^thanks/?$', views.thanks, name="thanks"), url(r'^.*$', RedirectView.as_view(url=reverse_lazy('index'), permanent=True), name='home') ] first, I have a 'thanks' view, but success_url on form submit just triggers the direct back to home. also tried success_url = reverse_lazy('thanks') but still being redirected back home. do I need to explicitly overwrite this for it to work? possibly related, form.save() is … -
why does my exception give a syntax error
well new to django and python the website i'm making is an ecommerce website and it has a carts app which deals with the shopping cart in the views.py file i have this function : def get(self, request): try: item_id = request.GET.get('item') quantity = request.GET.get('qty', 1) delete = request.GET.get('delete', 'n') cart, is_deleted, cart_item = self._process_cart(item_id, int(quantity), delete, request) cart_count = cart.total_count request.session['cart_count'] = cart_count return Response({'success': True, 'deleted': is_deleted, 'count': cart.count, 'item_total': cart_item.item_total, 'cart_price': cart.cart_price, 'cart_count': cart_count}, status=status.HTTP_200_OK) except Exception as error: print error it always gives a syntax error so i tried using an if instead of try but the result was my shopping cart didn't work properly afterwards it never updated it's badge and never got anything in it even after an order -
Django make migrations issue changing to new Postgres DB
I have not been able to find a solution on SO that has worked for me yet, so I figured I would post a question. I am running into issues migrating a database schema to a new PostgreSQL DB using django. Here is the connection for my first DB, it works and I am able to run migrations perfectly fine. This is the DB I was using for testing intially, now I want to use a secondary DB and migrate the schema over. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '[HOST]', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': '[PW]', } } Here is the updated settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': '[HOST]', 'NAME': 'test_mh', # this is only difference 'USER': 'postgres', 'PASSWORD': '[PW]', } } I run python3 manage.py makemigrations on the first connection and it is fine. When I run the same command with the updated DB Name I get exceptions that state my tables do not exist. Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "objects_community" does not exist LINE 1: ...y"."state", "objects_community"."date_added" FROM "objects_c... ^ The above exception was the direct cause of the following exception: Traceback … -
How to share django database model between projects in Docker
I have following service structure: service1/ Dockerfile manage.py settings.py .. service2/ Dockerfile manage.py settings.py .. databasemodel/ Dockerfile manage.py settings.py database/ models.py Each service and database models has it's own git repository. How do I share common django database model between them (both services connect to same database). I have implemented manual copying of "database" folder over to service1 and service2, but it feels wrong. I feel like implementing some anti-pattern. I need setup for: 1) development on local machine (something that would bring up database and both services) 2) deployment so that dev-ops team can deploy each git repo to server I am very inexperienced with Django and Python and Docker and Git, please do not assume that I know trivial truths. :) EDIT: I am free to change this structure how I please, however solution should still have git-repo for each service and database models -
Error when migrating django app on heroku bash
First of all, I deployed my django app on heroku. The site works well but when I try to interact with database (fill a form that submits input to db), I get a programming error. I learnt I needed to run a migrate command on heroku bash and did. After a few migrations it returned a lot of error lines, the first saying '..../django.db.backends.until.py, line 85, in _execute return self.cursor.execute(SQL, params) pyscopg2.DataError: integer out of range. Then other lines of error saying the above error led to the others. How can I fix this please? Searched online but couldn't find it PS if I run the migrate command cmd in dev mode on my machine it works well. -
How to create a dynamic model for days of week names in schedule?
For the gym schedule, I need to create a model with which I will get a list of seven days names. The list will be updated daily, so in the first place will always be the current day of the week. Every day the list will be shifted to one day, so, for example, in the cell in which the word “Wednesday” stands today, tomorrow the word “Thursday” will appear, the day after tomorrow - “Friday” and so on. The names of the days should then be retrieved into the view and passed to the template. I tried to do it like this: import calendar import datetime from datetime import * from django.db import models from django.utils.translation import ugettext as _ class DayOfWeekSchedule(models.Model): """General dynamic schedule for a week""" DOW_CHOICES = ( (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ) day_of_week = models.PositiveSmallIntegerField( choices=DOW_CHOICES, verbose_name=_('Day of week') ) def days_of_week(self): my_date = date.today() current_day_name = calendar.day_name[my_date.weekday()] index1 = DOW_CHOICES.index(current_day_name) #from Monday=0 (i.e. Friday=4) list_daynames = list(DOW_CHOICES[index1:] + DOW_CHOICES)[:7] #list of names, current is first list_index = (2, 3, 4, 5, 6, 7, 1) #to compensate systems difference list2 = list(list_index[index1:] + list_index)[:7] context_days … -
Django: first() or get()
Is the way I write discount_code.first().is_active() the right one or would you rather work with .get as (discount) code is a code unique field per event. Different events can have the code. def clean_code(self): input_code = self.cleaned_data['code'] # Check if discount code exists discount_code = self.event.discounts.get(code=input_code) discount_code_exists = discount_code.exists() if not discount_code_exists: raise forms.ValidationError(_("The discount code couldn't be found."), code='code_exists') else: if not discount_code.first().is_active(): raise forms.ValidationError(_("This discount code is not available\ anymore."), code='code_not_active') return input_code -
enabling pylint_django plugin in vscode, pylint stop working
That's my user settings in vscode { "python.pythonPath": "/Users/cristiano/miniconda3/envs/django-rest-2/bin/python", "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.pylintArgs": [ "--load-plugins", "pylint_django" ], } I installed the plugin via conda, same as the pylint pylint 2.1.1 py36_0 pylint-django 0.11.1 py_1 conda-forge pylint-plugin-utils 0.4 py_0 conda-forge If i commented out the "python.linting.pylintArgs" section, pylint works with no problem. I ned to enable the plugin to avoid django-specific errros such as "Entity.objects.all()", but if I enable it, the lint stop working: it does not highlight standard errors o warning the previously was doing it. I have same exact behaviour using vscode for win and mac. I tried also to use the .pylintrc file as described here but I have the same result: lint stop working. Same behaviour using base conda env or a custom one. -
How to join two different queryset in one dict
I have the result of two querysets and I need to put it together to iterate on my view. data = dict() item = get_object_or_404(Item, pk=pk) phase = item.phase_set.all() evaluation = item.evaluation_set.all().exists() data["timeline"] = phase .... return render(request, 'item_detail.html', data) I need to put in data["timeline" the value of phase and the value of evaluation, how can I add the evaluation result in phase result? In my item_detail.html view: {% for timeline_idea in timeline %} .... {% endif %} -
[Postgres][Python] -Why does printing print values in the database, but return does not? How to return a list of strings from database?
I want to manipulate a column in my database by turning it into a list of strings and then feeding it back to a function to grab more rows from the database. However, my function returns <function c at 0x0000025473074598> where as printing prints actual values in the database. def c(x): conn = psycopg2.connect(dbname = NAME, user = USER, password = PASSWORD, host = HOST, port=PORT) cur = conn.cursor() sql = """SELECT * from course where cid ilike '{code}'""" new = sql.format(code=x) cur.execute(new) y = (cur.fetchone()) # I also tried fetchall() cur.close() print(y) #you = [list(i) for i in y] return y if __name__=="__main__": c('CSC42184') print(c) ('CSC42184', 'BLAH', 'BLAH I want to manipulate this') #from the print statement in the function <function c at 0x0000randomnchar> From the comment in the function, I have tried turning it into a list but it returns the same thing <function c at 0x0000blahblah>. I want my function to return as a list of strings so I can index it for uses in other functions. How to do this? -
wagtail and elasticsearch does not support __icontains?
I want to be able to search in one of my custom page models. The search should exclude all predefined page.id which are in a list, and also exclude where the page.url_path contains a certain value. For example: from django.db.models import Q # The view def search(request, search_query): ... CustomPageModel.objects.live().exclude( Q(id__in=list_page_ids) | Q(url_path__icontains='notsearchable') ).search(search_query)) This works when I use: WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.contrib.postgres_search.backend', } } But does not work when I use: WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.search.backends.elasticsearch6', ... } } The error I get from Elasticsearch as backend: FilterError at /search/query/ Could not apply filter on search results: "url_path__icontains = notsearchable". Lookup "icontains"" not recognised. Elasticsearch does not support icontains. So how can I exclude and search on the same model? ps. The CustomModel is used in different url_paths, so there should not be any changes to the model itself. -
Displaying Json table in HTML Table
I have some JSON data that is returned by a Django web app that I want to display within a HTML List. For some reason, it's not working for me. The JSON is generated by a Ajax Get request which displays all the products in the database. The get request works as is supposed to but when I try to display the details of the products to the Html page, nothing is shown. Here is the relevant code I have so far: This is the Views.py file: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from products.models import Product from django.http import HttpResponse, JsonResponse def index(request): return render(request, 'index.html') def viewProduct(request): if request.method == 'GET': product_list = Product.objects.all() products=[] for prod in product_list: products.append({"name": prod.name, "description": prod.description, "price": prod.price}) return JsonResponse(products, safe=False) The Index.html page: <!DOCTYPE html> <html> <body> <div> <h2 id="title">Create product</h2> <input id="name">Name</input> <br> <input id="description">Description</input> <br> <input id="price">Price</input> <br> <button id="add-product">ADD PRODUCT</button> </div> <table id = "employee-table"> <tr> <th>Name</th> <th>Description</th> <th>Price</th> </tr> </table> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> document.getElementById('add-product').onclick = function(){ sendData(); getData(); } function getData(){ $.ajax({ url: 'view/product', dataType: 'json', type: 'GET', success: function(data){ var dmJSON = "http://localhost:8000/view/product"; $.getJSON(dmJSON, function(data) { $.each(data.entries, function(i, f) { var …