Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pyzipcode3 not finding ziptable
A process killed my terminal on a Mac and I created a new virtual environment. Pyzipcode3 is installed there. However, whenever I try to run a command on it's zcdb. I get this error: sqlite3.OperationalError: no such table: zip Not sure how to fix this. This is what I have: zcdb = ZipCodeDatabase() path = settings.GEO_DB_PATH This all runs, so the package seems to be installed, but it's not finding the db. The Settings GEO_DB_PATH has a path to the GeoCity2.mmdb. >>> from pyzipcode import ZipCodeDatabase >>> zcdb = ZipCodeDatabase() >>> zipcode = zcdb[54115] Traceback (most recent call last): File "<console>", line 1, in <module> File "/venv/lib/python3.7/site-packages/pyzipcode/__init__.py", line 108, in __getitem__ zip_code = self.get(str(zip_code)) File "~/venv/lib/python3.7/site-packages/pyzipcode/__init__.py", line 105, in get return format_result(self.conn_manager.query(ZIP_QUERY, (zip_code,))) File "~/lib/python3.7/site-packages/pyzipcode/__init__.py", line 35, in query cursor.execute(sql, args) sqlite3.OperationalError: no such table: zip >>> -
Why am in not able to retrieve the manager profile in django 2.1
I am using django 2.1 and for some reason in the views, using Function based views, i am unable to update the information from the models Manager. I have tried to codes below: models.py User = settings.AUTH_USER_MODEL class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers') phone_number = models.CharField(max_length=10) city = models.CharField(max_length=30) state = models.CharField(max_length=30) postal_code = models.CharField(max_length=30) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='managers') title = models.CharField(max_length=50) company_name = models.CharField(max_length=30) def __str__(self): return self.user.username forms.py class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'username', 'email' ) class ManagerUpdateForm(forms.ModelForm): class Meta: model = Manager fields = ( 'title', 'company_name' ) views.py def manager_profile(request): if request.method == 'POST': user_form = UserUpdateForm(request.POST, instance=request.user) manager_form = ManagerUpdateForm(request.POST, instance=request.user.manager) if user_form.is_valid() and manager_form.is_valid(): user_form.save() manager_form.save() return redirect('user:manager_profile') else: user_form = UserUpdateForm(instance=request.user) manager_form = ManagerUpdateForm(instance=request.user.manager) context={ 'user_form': user_form, 'manager_form': manager_form } return render(request, 'user/manager-profile.html', context) Here is the error message from the console. AttributeError: 'User' object has no attribute 'manager' It comes from the line manager_form.... I am just trying to update the information in the profile page from the table Manager. -
Problema ao usar SmartSelect no Django
boa noite! estou com a seguinte dúvida, não sei como resolver. Preciso que as disciplinas que aparece no dropdown sejam apenas as disciplinas que estão vinculadas a turma, ou seja, eu vou selecionar uma turma e ele me traz só as disciplinas daquela turma selecionada, ao alterar a turma, muda as disciplinas. Sendo que uma turma, tem um curso que tem matriz curricular e a matriz por sua vez tem as disciplinas. Consegui resolver parcialmente utilizando o app Django Smart Selects, porém ele só me traz uma disciplina. Sendo que tem várias. Para ajudar, segue o trecho do código: https://gist.github.com/albertojr/f4c4b4c44a12c7e557e1087ea5026da4 -
cant import class if it under another class [duplicate]
This question already has an answer here: Django circular model reference 7 answers can not add primary contact in company table from contact table from django.db import models # from .models import contact # Create your models here. class company(models.Model): name = models.CharField(max_length=80) telephone = models.CharField(max_length=30,null=True) website = models.URLField() PrContact = models.OneToOneField(contact.name, on_delete=models.CASCADE, default="1",null=True,blank=True) def __str__(self): return self.name class contact(models.Model): name =models.CharField(max_length=80) company = models.ForeignKey(company,on_delete=models.PROTECT) email =models.EmailField(null=True) def __str__(self): return self.name also when i put every model in defrant app the same issue i found i cant import , is ther any way to put primary contact in every company andin the same time add every contac in company -
What is the correct why to setup Django static files dirs and URLs
I can't seem to get the situation of the static file correctly in Django and the documentation is terrible. Here is how I have my static files setup in settings.py and url.py settings.py PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') MEDIA_ROOT = os.path.join(PROJECT_ROOT,"media") urls.py urlpatterns = [ path('', admin.site.urls), path('admin/', admin.site.urls), url(r'^tinymce/', include('tinymce.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) when I want to load a js file that exists in the statics folder I get the following error /static/showhide.js HTTP/1.1" 404 1758 but the file actually is in that path so why do I get 404? -
Django Architecture: Where should I schedule a Celery Beat Periodic Task for ALL users?
I have a django-celery-beat periodic task that needs to be run for every user on every Monday of every week. I'm not sure where the right place to create this task is for the first time to schedule it. I understand that per-user celery tasks can be created wherever in the particular code with PeriodicTask and Interval, but since this is run for every user I'm not quite sure where it should go or how to instantiate it. -
method() takes 1 positional argument but 2 were given in pagination decorator action
I have a problem doing a paginator about an action decorator in django rest framework and I can't find the solution, the question is that it gives me the following error: get_response_data () takes 1 positional argument but 2 were given class InterfacesViewSet(viewsets.ModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer pagination_class = PostPageNumberPagination def get_response_data(paginated_queryset): data =[ { 'id_interface': interface.id_interface, 'id_EquipoOrigen': interface.id_EquipoOrigen_id, 'EquipoOrigen': interface.id_EquipoOrigen.nombre, 'LocalidadOrigen': interface.id_EquipoOrigen.localidad, 'CategoriaOrigen': interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen': interface.id_PuertoOrigen_id, 'PuertoOrigen': interface.id_PuertoOrigen.nombre, 'estatus': interface.estatus, 'etiqueta_prtg': interface.etiqueta_prtg, 'grupo': interface.grupo, 'if_index': interface.if_index, 'bw': interface.bw, 'bw_al': interface.bw_al, 'id_prtg': interface.id_prtg, 'ospf': interface.ospf, 'description': interface.description, 'id_EquipoDestino': interface.id_EquipoDestino_id, 'EquipoDestino': interface.id_EquipoDestino.nombre, 'LocalidadDestino': interface.id_EquipoDestino.localidad, 'CategoriaDestino': interface.id_EquipoDestino.categoria, 'id_PuertoDestino': interface.id_PuertoDestino_id, 'PuertoDestino': interface.id_PuertoDestino.nombre, 'ultima_actualizacion': interface.ultima_actualizacion, } for interface in queryset] return data @action(methods=['get'], detail=False, url_path='registros-data-table', url_name='registros_data_table') def registros_data_table(self, request): queryset = Interfaces.objects.all() page = self.paginate_queryset(queryset) if page is not None: data = self.get_response_data(page) return self.get_paginated_response(data) data = self.get_response_data(queryset) return Response(data) -
website access through IIS windows authentication and django
I am setting up a website through IIS and Django. I would like to secure my IIS site so only the desired people can access it, in particular, I would like to rely on their windows credential within our network for authentication. To do that I have added IIS Windows Authentication and enabled it for the website through. I have also followed the django tutorial on adding REMOTE_USER definitions in settings.py. When I try to access the web site as a user on my network I get the following error: OperationalError at attempt to write a readonly database Request Method: GET Request URL: http://myawesomewebsite.com/ Django Version: 2.2.3 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\scripts\python.exe please help me find the missing piece of the puzzle. I am pretty new to Django and IIS and would appreciate the help Python Version: 3.7.2 DJANGO version 2.23 IIS version: 10.0 Windows Server 2016 -
Django: Should sendgrid emails always be sent from Celery?
I'm using django-sendgrid-v5 and I read somewhere that it isn't good to send emails from the main webserver. Should I process emails from Celery? Or is it fine to call from the main app since I'm using an external service like Sendgrid anyways? -
Diango model property to return list of objects of other model
I have 2 models like this: class Company(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) class Meta: verbose_name = 'Company' And another model: class Product(models.Model): name = models.CharField(max_length=200) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) class Meta: verbose_name = 'Product' Now, I need to make a property in Company model which could return a list of all Product Objects, like @property def products (self): products = [] for i in Product.objects().filter(company=self.id): products.append(i) return products When I mention products (property) in CompanySerializer fields, it give me an error that it cannot return a list of objects. Can anyone solve my problem and tell me what is wrong with the code? -
column app_element.image does not exist - Django PostgreSQL
I apologize if my question is simple, but the database problems are unfamiliar to me. On my VPS server where is my django app I receives the error below, which occurred after adding a new field in my models.py file (in the local repo and later after merging): Environment: Request Method: GET Request URL: http://167.71.54.97/row-bootstrap/ Django Version: 2.2.3 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'crispy_forms'] Installed 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'] Template error: In template /home/app/app/app/templates/solution.html, error at line 78 column app_element.image does not exist LINE 1: ...", "app_element"."slug", "app_element"."created", "app_eleme... ^ 68 : <div class="container-fluid"> 69 : <div class="row justify-content-between"> 70 : <div class="col-lg-9 col-xl-8 offset-xl-1"> 71 : <div class="docs-content"> 72 : <div class="docs-page-title mt-2"> 73 : <h2>{{ solution.name }} 74 : </h2> 75 : <p>{{ solution.created }}, {{ solution.category }}, 76 : <p> 77 : </div> 78 : {% for element in solution.element_set.all %} 79 : <h2 id="{{ element.slug }}">{{ element.file_name }}</h2> 80 : <p>{{ element.tips }}</p> 81 : {% if element.image %} 82 : <a href="{{ element.image.url }}" data-fancybox data-caption="{{ element.file_name }}"> 83 : <img src="{{ element.image.url }}" class="w-50 img-fluid rounded mb-2"> 84 : </a> 85 : {% … -
Combine DetailView and UpdateView?
i am new to Django and i need to know how to have DetailView and UpdateView on same Page. I have a two Models: class Company(models.Model): CustomerNo = models.AutoField(primary_key=True) Company = models.CharField(max_length=200) Str = models.CharField(max_length=200) Zip = models.IntegerField() City = models.CharField(max_length=200) Name = models.CharField(max_length=200) Phone = models.IntegerField() Mobile = models.IntegerField() Email = models.EmailField(max_length=200) Web = models.CharField(max_length=200) Info = models.CharField(max_length=200) def __str__(self): return self.Company class Contact(models.Model): Contact_Company = models.ForeignKey(Company, on_delete=models.CASCADE) Contact_Name = models.CharField(max_length=200) Contact_Phone = models.IntegerField() Contact_Mobile = models.IntegerField() Contact_Fax = models.IntegerField() Contact_E_Mail = models.EmailField() Contact_Web = models.CharField(max_length=200) def __str__(self): return self.Contact_Name I want to build a page where i can see the company data from the first model and a update form for contacts realeted to the first model. I enter the page with pk, from the previous page, its a DetailView for the first Model and with additionally context to list the Contact data with a for loop in Template. I can use UpdateView to get data in the form and save it. but i don't know how do display the realeted Company on the same page. Is there a way to use DetailView and UpdateView together? I can use this UpdateView to change the Contact data, but i … -
How can I know the next value of the Django queryset without having to loop and store values?
I'm writing a website using Django and Vue.js. Although I am admittedly a beginner at both, I find this surprising that I can't seem to be able to know, beforehand the value of the next item of a queryset. I need to know if there is a way to do it in Django. For instance, I perform a search on the database, it returns a queryset, and I start to call the elements of the queryset one after the other. Is there a way to know the next beforehand? def fetch_question(request): question_id = request.GET.get('question_id', None) response = Question.objects.filter(pk=question_id) ''' -
how reconnect django signals after disconnected from a for loop formset
i want send signals only for one view in a formset , i disconnected the signal after the first loop views.py def ProductOrderCreate(request): template_name = 'create_product_order.html' if request.method=='GET': formset = ProductFormSet(request.GET or None) elif request.method=='POST': formset = ProductFormSet(request.POST) if formset.is_valid(): for form in formset: product = form.cleaned_data.get('product') quantity = form.cleaned_data.get('quantity') ProductOrder(product=product , quantity=quantity).save() signals.pre_save.disconnect(create_order_instance,sender=ProductOrder) return redirect('/orders/') return render(request , 'create_product_order.html' , {'forms':formset}) signals @receiver(pre_save , sender=ProductOrder) def create_order_instance(sender, instance, **kwargs): Order.objects.create() pre_save.connect(create_order_instance,sender=ProductOrder) @receiver(pre_save,sender=ProductOrder) def create_ordering(sender,instance,**kwargs): if not instance.ordering: instance.ordering = Order.objects.order_by('-pk')[0] pre_save.connect(create_ordering,sender=ProductOrder) models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) now , i want to reconnect the signals for the next view where should i put this code signals.pre_save.connect(create_order_instance,sender=ProductOrder) i put connected code after the render() but doesnt work as i expected , also outside of the function still not reconnected -
Error in the pythonanywhere.com deployed content done in Django
I deployed a Text to Speech program in pythonanywhere.com, the code was written in Django. which works fine in my local system. But after deployment it shows an error OSError at /checker libespeak.so.1: cannot open shared object file: No such file or directory You can check the link to the webapp: http://maqboolthoufeeq.pythonanywhere.com i have tried with all packages installed, but nothing works This is the settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') SECRET_KEY = ')hu2$o^tr^()chmvuc3(uom45j1ulbf641((5%2%nb%k^-6t#6' DEBUG = True ALLOWED_HOSTS = ['maqboolthoufeeq.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'generator', ] 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', ] ROOT_URLCONF = 'randomgen.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'randomgen.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True … -
how do I prepare STATICFILES_DIRS well
enter image description hereI want to correct path it doesn't work I use django v:2.1 -
django-oscar translation - how to compile? In a virtualenv?
i set up a new django project with the following parameters: Django: 2.2.3 Python: 3.5.2 django-oscar: 2.0 The project is in virtualenv and at the moment i' m using the default sqlite database and the django testserver if needed. I set up the application based on the official document ( https://django-oscar.readthedocs.io/en/2.0.0/internals/getting_started.html ), and i' d like to use translation for hungarian, which is 0% ready based on transifex ( https://www.transifex.com/codeinthehole/django-oscar/ ) (of course i' d contribute if ready) . I found the translation files in the virtualenv: ~/.virtualenvs/ws/lib/python3.5/site-packages/oscar/locale$ ls -l hu* -R hu: total 4 drwxrwxr-x 2 lenovo lenovo 4096 júl 28 08:15 LC_MESSAGES hu/LC_MESSAGES: total 252 -rw-rw-r-- 1 lenovo lenovo 454 júl 28 08:15 django.mo -rw-rw-r-- 1 lenovo lenovo 250927 júl 28 08:15 django.po hu_HU: total 4 drwxrwxr-x 2 lenovo lenovo 4096 júl 28 13:16 LC_MESSAGES hu_HU/LC_MESSAGES: total 500 -rw-rw-r-- 1 lenovo lenovo 470 júl 28 08:15 django.mo -rw-rw-r-- 1 lenovo lenovo 250951 júl 28 13:16 django.po . I edited the django.po file from the hu_HU directory, but my problem is that i can' t create the related django.mo file with makemessages and compilemessages. I tried to follow this translation tutorial: https://django-oscar.readthedocs.io/en/releases-1.6/topics/translation.html , but it does not seem to … -
Extending AbstractBaseUser not hitting ModelBackend - Django
I'm extending AbstractBaseUser with my custom user model. I can create a superuser via shell successfully with the UserManager() below which is created in the database correctly. For testing, I've created a superuser with the username test & password of test. I can run this test user against the check_password("test", "test") method which returns True as expected, but if I try to login via /admin I get "Password Incorrect" with a 200 status code on the POST. User Model class User(AbstractBaseUser): USERNAME_FIELD = ('username') REQUIRED_FIELDS = ('email', 'password') username = models.CharField(max_length=15, unique=True) twitch_id = models.IntegerField(null=True) avatar = models.URLField(null=True, blank=True) is_live = models.BooleanField(default=False) email = models.EmailField(unique=True) password = models.CharField(max_length=50, default="password") register_date = models.DateTimeField(auto_now=True) twitch_token = models.ForeignKey(TwitchToken, on_delete=models.SET_NULL, null=True) twitter_token = models.ForeignKey(TwitterToken, on_delete=models.SET_NULL, null=True) # attempted giving flags from original User model is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() class Meta: db_table = 'users_user' def __str__(self): return self.username """ Properties are redundant with flags above @property def is_admin(self): return self.admin @property def is_active(self): return self.active @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser """ UserManager() class UserManager(BaseUserManager): def create_user(self, username, email, password): """ Creates and saves a User with the given email … -
Custom graphene queries not added
I'm using graphene-django for my graphql API. The propblem is that all my custom queries get not picked up by graphene in the schema. I'm doing everything like this tutorial explains. main schema.py import graphene from item.schema import ItemQuery class Query(ItemQuery, graphene.ObjectType): pass schema = graphene.Schema(query=Query) item schema.py import graphene from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from item.models import UserItem, Item, ItemPrice class UserItemType(DjangoObjectType): class Meta: model = UserItem interfaces = (graphene.Node,) class ItemType(DjangoObjectType): class Meta: model = Item interfaces = (graphene.Node,) class ItemPriceType(DjangoObjectType): class Meta: model = ItemPrice filter_fields = ['item_id'] interfaces = (graphene.Node,) class ItemQuery(graphene.ObjectType): def user_item(self, info): user = info.context.user if not user.is_anonymous: try: return UserItem.objects.entry_set() \ .get(id=id, user_id=user.id) except UserItem.DoesNotExist as ex: return None def user_items(self, info): user = info.context.user if not user.is_anonymous: return UserItem.objects.entry_set() \ .filter(user_id=user.id) \ .all() item_prices = DjangoFilterConnectionField(ItemPriceType) The item_prices query gets picked up by graphene but user_item and user_items not. I'm doing nothing different than the tutorial and can't seem to figure out why they don't get picked up. -
Using django how can I send page-refresh without pressing enter in input field
In my app I have an input field in which the user can write a string. When he presses enter it activates a request for editing the database and the new data gets displayed. I want however that this request is being sent every time the user writes a letter into the input field. How can I achieve this? views.py def search_movie(request): # create new object and save it and redirect title = request.POST['content'] print('title') for item in movie_class.objects.all(): if item.title == title or not title: item.show_movie = True else: item.show_movie = False item.save() movieView(request) return HttpResponseRedirect('/movies/') template <form action="/search_movie/" method="post"> {% csrf_token %} <input type = "text" name = "content"/> <button type="submit">Upload text</button> </form> -
How to add element without submitting to another page
I would like to add a topping to my pizza using XMLHttpRequest without submitting to another page but I can't wrap my mind around how to implement it. So far I'm posting to add_topping route and getting a JsonResponse without any problem. But instead of going to the view, I would like to do it with JavaScript. I have already searched for similar problems but or they are all with PHP or with jquery but I would like to implement it using normal JavaScript with XMLHttpResponse. HTML <form id="add_topping" action="{% url 'orders:add_topping' %}" method="post"> {% csrf_token %} <div class="form-row align-items-center"> <div class="form-group col-auto"> <select class="form-control" name="topping_selected" id="topping_selected"> {% for topping in topping_list %} <option value="{{ topping }}">{{ topping }}</option> {% endfor %} </select> </div> <div class="form-group col-auto"> <button class="btn btn-secondary" type="submit">Add topping</button> </div> </div> </form> views.py def add_topping(request): # If request is not a POST request, return index if request.method == 'POST': # Get the data from the POST request topping_selected = request.POST.get('topping_selected') return JsonResponse({"success":True, "topping_added": topping_selected}) # Else return false return JsonResponse({"success":False}) JavaScript // Function to add topping document.querySelector('#add_topping').onsubmit = function() { // Create request object const request = new XMLHttpRequest(); // Variables to determine the size and topping … -
'NoneType' object has no attribute '__dict__' when overriding form_valid()
I'm trying to override the form_valid function of a CreateView so it sends an email to the user when the form is saved. It saves the element in the database and correctly sends the email, but afterwards it shows the 'NoneType' object has no attribute 'dict' error when trying to redirect. I tried overriding the get_success_url method but it didn't send the message I need to send to the template after it's done. I also tried changing the return redirect(self.get_success_url()) to return redirect(success_url) and the same happens, it redirects with no error but the template misses the message. ###views.py class createpetition(SuccessMessageMixin, CreateView): model = PQS form_class = CrearPeticion template_name = "peticion/createpetition.html" success_url = reverse_lazy('createpetition') success_message = "e" def form_valid(self, form): peticion = form.save() usuario = peticion.nombreUsuario usuario.enviarCorreo('Artemis - Nueva petición registrada con éxito','¡Gracias por comunicarte con nosotros!\n\nTu mensaje:\n\n' + peticion.descripcion) return redirect(self.get_success_url()) ###user models.py def enviarCorreo(self, asunto, mensaje): contenido = render_to_string('correo_base.html',{'mensaje':mensaje}) send_mail(asunto,contenido,'admin@artemis.com',[self.correo])``` -
How to apply delay for a single user in django without disturbing the whole server?
I am building a django website and for certain reasons I have to send an email to user containing a link consisting of a token, although the token is always unique and is of 100 alphanumeric characters yet I want to delay the loading time of the user if link with wrong token is used. The function related to this in my views.py is something like this- import time def my_function(request,token): if User.objects.filter(uid=token): return HttpResponse("Yes") else: time.sleep(5) return HttpResponse("No") But the problem here is that the sleep function not only affects the current user but instead the whole server. Is there any possible way to add this delay in backend or in frontend? If not then is there any other way to punish for entering url with wrong token? -
Django Rest Framework - Latest child per instance
Using Django Rest Framework, I'm building a web application that saves information on Products and its Prices. A Product can have multiple Prices over time. My models look like this: class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): product = models.ForeignKey(Product, related_name='prices', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0) date = models.DateField(default=datetime.date.today) I've set up the following serializers: class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('price', 'date') class ProductSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=True) class Meta: model = Product fields = ('name', 'prices') Now, I want to create an APIView that shows all products with their latest price. Like so: [ { "name": "Product A", "price_latest": 1.00 }, { "name": "Product B", "price_latest": 2.00 } ] Does anyone have any idea on how to achieve this? -
Sub-classing the user model from models.Model directly instead of using custom user models
Everywhere, everyone seems to be using "custom user model" derived from either AbstractUser or AbstractBaseUser class. Why nobody directly sub-classes the user model from models.Model? Won't that be much easier and simpler? What additional functionality does using these custom user models provide?