Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /app/index I already URL
I got an error,NoReverseMatch at /app/index. I wrote in views.py def index(request): return render(request, 'index.html') def test1(request): return render(request, 'test1.html') def test2(request): return render(request, 'test2.html') in urls.py app_name = "app" urlpatterns = [ path('index', views.index,name='index), path('test1', views.test1,name='test1'), path('test2', views.test2,name='test2'), ] in index.html <tr> <td align="center "> <a class="test1" href="{% url 'test1' %} ">test1</a> </td> <td align="center "> <a class="test2" href="{% url 'test2' %} ">test2</a> </td> </tr> When I access index method, NoReverseMatch at /app/index Reverse for 'test1' not found. 'test1' is not a valid view function or pattern name. error happens. I really cannot understand why I got this error.I already test1&test2 url.How should I fix this? -
Django - .delete() command gives 'Killed' message
I'm trying to delete 85k records from a database of about 300k records, in the shell opened with python manage.py shell When I use MyModel.objects.filter(status='Ter').delete(), it would run for about 15 seconds before giving a message - Killed, and exit me out of the shell. Why is this happening? Is it because I am trying to delete too many records at once? If this deletion method is not possible, what is the best alternative way of deleting those records? -
Is Amazon Route 53 the solution for the Django All-Auth Google clash with AWS in production?
Hello fellow coding ninjas! So I just have one question. As you may know, Google Authorized redirect URIs require a .com or org domain. The AWS EC2 IPv4 Public IP option (with just numbers) does not work in production for Google Django All-auth sign-in. Is the Amazon Route 53 Domain the best way to solve the Google Django All-auth redirect issue in production? I tried using a redirect .org and .com from a dynamic DNS company but that didn't work out. Thanks! -
Django getting right return value for post.request
I am trying to get the product id using request.post in Django. I am currently testing using the console, but the only product_id value I am returned is 1. This is the particular function in the view: def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) products = Product.objects.all() if request.POST: product_id = request.POST.get('product_id') entry_quantity = request.POST.get('entry_quantity') product_obj = Product.objects.get(id=product_id) print(product_id) # print(entry_quantity) # Entry.objects.create(cart=cart_obj, product=product_obj, quantity=product_quantity) return render(request, 'carts/test.html', {'cart_obj': cart_obj, 'my_carts_current_entries': my_carts_current_entries, 'products': products}) This is the html on the template. <form method="POST"> <br> {% csrf_token %} {% for product in products %} {{ product.name }} <br> <button>Add to Basket</button> {{ product.id }} <input type="hidden" name='product_id' value='{{ product.id }}'> <br> {% endfor %} </form> -
Access the form that caused a post_save [Django]
Is there a way I can access the form that caused a post_save? The use case is that I have a field (a checkbox) that isn't attached to a particular model, but it's an extra field in the form itself. I want to know whether the field was checked or unchecked when the form got saved and the model stored, and imho the post_save signal is a good place to put the logic that should process that extra field. I'm also open to suggestions where else I could put that piece of code. -
Stripe: When customer adds card I'm able to receive and store 'source' token in customer model. But Not able to charge customer
def book_now(request): """Schedule Appointment""" if request.method == 'POST': customer = Customer.objects.get(user_id=request.user.id) token = request.POST.get('stripeToken') customer.default_source = token customer.save() charges.create( amount=decimal.Decimal("119.99"), customer=request.user.customer.stripe_id, ) return render(request, 'appointment/book_now.html') Here you can see that I save the token to a Customer. This works successfully. Then When I try to charge customer I get the error that they do not have a card. When I log in to stripe.com, the user does not have a card. And I understand this part because token was never sent to stripe. But my thinking is that it would be sent during the charge. -
suspiscious dependencies in my requirements.txt
asn1crypto==0.22.0 cryptography==1.9 enum34==1.1.6 gyp==0.1 idna==2.5 ipaddress==1.0.17 keyring==10.4.0 keyrings.alt==2.2 pycrypto==2.6.1 pygobject==3.24.1 pyxdg==0.25 SecretStorage==2.3.1 six==1.10.0 virtualenv==15.1.0 These are the dependencies in my requirements.txt in which I never installed while i was setting up a django project, and yet they appeared. Anyone have a clue what these dependencies are? -
Python/Django: Add Data To Localhost DB in PostgreSQL
I'm new to python and Django, currently learning Django REST FW. I've managed to connect to my local postgreSQL db, and have migrated a table as well with the below model from djan go.db import models # Create your models here. class Publisher(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) models.CharField(max_length=30) I'd like to make a post request to /name, take the input values and insert into my db. For now i'll just be happy with hard coding the values per post request. Any ideas how to accomplish this? -
django-import-export :ForeignKey with many fields
I need just export data from my admin. My code now looks like: models.py from django.db import models from services.models import Services,PromoCodes,CauseOfReservedPromocodes # Create your models here. class User(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) email=models.EmailField() password=models.CharField(max_length=200) telephone=models.PositiveIntegerField(max_length=12,blank=True,null=True) userRequest=models.ForeignKey('UsersRequests', blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name + " " + self.surname class UsersRequests(models.Model): date = models.DateField() requestChannel = models.CharField(max_length=30) problem = models.CharField(max_length=200) solution = models.CharField(max_length=200) def __unicode__(self): return str(self.date) + " " + str(self.requestChannel) + " " + str(self.problem) + " " + str(self.solution) And my admin.py is: from django.contrib import admin from .models import User,UsersRequests from import_export import resources, widgets, fields from import_export.admin import ImportExportModelAdmin,ExportMixin class UsersResource(resources.ModelResource): class Meta: model = User fields = ('id', 'name', 'email', 'telephone', 'userRequest') class UserAdmin(ImportExportModelAdmin): resource_class = UsersResource @admin.register(User) class UserAdmin(ImportExportModelAdmin): search_fields = ('name', 'surname', 'email', 'telephone') I try everything to get userRequest work, but it send just integer - id for userRequest. How to get full data from class UsersRequests(models.Model)? -
PostgreSQL/PostGIS Stack builder missing dlls (GeoDjango)
I've installed GeoDjango Spatial Database libraries using Enterprise DB Stack for Postgres 10 and it includes following packages. I am using Windows 10 OS and needed to setup GeoDjango. Please assist PostGIS 2.4.3 bundle includes PostGIS 2.4.3 w GDAL 2.2.3, GEOS 3.6.2, Proj 4.9.3, pgRouting 2.5.2, osm2pgrouting 2.3.3, ogr_fdw 1.0.5 But now on Python I get this error below and I tried many posted answers but couldn't make it work. Quick hint will be great help. Below is the error: (gigfinder) C:\Users\dell\gigfinder\gigfinder>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 324, in execute django.setup() File "C:\Users\dell\gigfinder\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\utils.py", line 212, in … -
How to take input from dropdown list compare it to a value in the database and then run commands using the other relating values of the same model?
So I have this Model: class Mymodel(models.Model) name = models.CharField(max_length=256) model = models.PositiveIntegerField() year = models.PositiveIntegerField() and I have a dropdown as such: <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> I want the user to be able to click a button, and it take their input from the dropdown. Then compare it to values in the database, and once it finds one that matches to return the other values. And lastly have a way to use them in a function in the views.py file. -
Returning Request.Post data from template in Django
I am trying to get the quantity of single product in cart using request.post but its not returning anything. This is what my views.py file looks like: def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) entry_quantity = request.POST.get('entry_quantity') print(entry_quantity) return render(request, 'carts/test.html', {'my_cart': cart_obj, 'my_carts_current_entries': my_carts_current_entries}) This is what my template looks like at the moment: <!doctype html> <html> <head> </head> <body> <h4>These are the current items in your Basket</h4> <form method="POST"> {% csrf_token %} {% for cart in my_carts_current_entries %} {{ cart.quantity }} x {{ cart.product }} <br> {% endfor %} <input type="hidden" name='entry_quantity' value='{{ cart.quantity }}'> <button>Add to Basket</button> </form> </body> </html> I am expecting a console printout of the request.post entry quantity. Thanks in advance. -
Custom save method for images/avatars in Django - how to use.
So, I'm trying to do a little bit of compression of images as well as some other operations. I had a few questions...I have the following save() method for my user class: class User(AbstractBaseUser, PermissionsMixin): ... avatar = models.ImageField(storage=SITE_UPLOAD_LOC, null=True, blank=True) def save(self, *args, **kwargs): if self.avatar: img = Img.open(BytesIO(self.avatar.read())) if img.mode != 'RGB': img = img.convert('RGB') new_width = 200 img.thumbnail((new_width, new_width * self.avatar.height / self.avatar.width), Img.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.avatar= InMemoryUploadedFile(file=output, field_name='ImageField', name="%s.jpg" % self.avatar.name.split('.')[0], content_type='image/jpeg', size=, charset=None) super(User, self).save(*args, **kwargs) I had two questions - 1.) best way for deleting the old avatar file on save, if a previous avatar exists. 2.) What do I pass into InMemoryUploadedFile for the size kwarg? Is this the size of the file...in what unit/(s)?? -
Django is not showing the right path when clicking on a link
This is what it shows when you click on the link Page not found (404) Request Method: GET Request URL: http://localhost:8000/jobapplication/new/1 Using the URLconf defined in careal.urls, Django tried these URL patterns, in this order: ^$ [name='landing-index'] ^admin/ ^accounts/ ^taskmanager/ ^login/$ [name='login'] The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1 This is what I have in the urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.contrib.auth import views as auth_views from landingpage import views as landingpage_views urlpatterns = [ url(r'^$', landingpage_views.index, name='landing-index'), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), url(r'^taskmanager/', include('taskmanager.urls')), url(r'^login/$', auth_views.login, name='login'), ] This is in urls.py in the app taskmanager from django.conf.urls import url from . import views from taskmanager.views import * app_name = 'taskmanager' urlpatterns = [ # Task manager urls url(r'^$', JobApplicationIndex.as_view(), name='index'), url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'), url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'), url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'), url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'), url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'), # Company urls url(r'company/$', CompanyIndex.as_view(), name='company-index'), url(r'company/add/$', CompanyCreate.as_view(), name='company-add'), url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'), # Job Post urls url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'), url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'), # Statistics urls url(r'^kpi/$', views.kpi, name='kpi'), ] And this is what I have in views.py in taskmanager, related to … -
NoReverseMatch Django error when trying to view cart - using Python 3.6
I'm getting the following error, and I'm having trouble figuring out why. NoReverseMatch at /cart/ Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[^/]+)$'] I had no problems until I made some changes to my template. I also changed my product's pk values but I'm guessing that shouldn't affect anything? I also used clearsessions to in case that might have been the problem. I think that Django is saying it can't find a match for the url that I'm providing, but everything seems right to me. I made some changes to my code, and tried to revert it to a previous state, but I'm still getting the same error messages. I'll present my code, and if you could tell me where I'm likely making a mistake, that would be awesome. Here is my product_detail.html template {% extends "buylist/Header.html" %} {% block content %} <p>{{product.name}}</p> <p>{{product.price}}</p> <form action="{% url 'add_to_cart' product.id %}" method="post"> {% csrf_token %} <input type="number" name="quantity" min="1" max="{{product.quantity}}"> <button type="submit">add</button> </form> {% endblock %} I use a form to link the url with the product url and add that to my cart Here are my associated urls.py and Views.py urls.py path('cart/', views.get_cart, name='cart'), path('cart/add/<product_id>', views.add_to_cart, … -
Returning Quantity of Current Cart Entry using Django View
I have the following view where I want to return the quantity of the current cart entry. def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) product_quantity = request.POST.get('product_quantity') return render(request, 'carts/test.html', {'my_cart': cart_obj, 'my_carts_current_entries': my_carts_current_entries}) How would I reference the current entry quantity, e.g. if there is an entry in the database called 23x Chicken Nuggets I want it to return the quantity. On the template if I return: {{ my_carts_current_entries }} it will return all the current entries but without the quantity. For clarity I have included an extract of my models.py from the said application: class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True) cart = models.ForeignKey(Cart, null=True) quantity = models.PositiveIntegerField(default=0) def __str__(self): return self.product.name -
How to save values not in a form into a database
I want to insert two calculated values into the database where they are not involved in an entry in the form. Finance balance and monthly payment are calculated and then sent to the database. The code below doesn't do it, so what can enable me to do it in record_input in views.py? Traceback C:\Python34\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) G:\NEA Computer Science\mysite\finance\views.py in record_input form += Customer(finance_balance=CustomerForm.clean_finance_balance(self) NameError: name 'self' is not defined The version of Django is 1.11.6. forms.py from django import forms from .models import Customer class CustomerForm(forms.ModelForm): def clean(self): super(CustomerForm, self).clean() if self.cleaned_data["list_price"] < self.cleaned_data["deposit"]: raise forms.ValidationError({"list_price": "List price cannot be greater than the deposit."}) try: if self.cleaned_data["interest_rate"] < 0: raise forms.ValidationError({"interest_rate:": "Interest rate must be greater than 0."}) except: raise forms.ValidationError({"interest_rate:": "Interest rate must be a positive number."}) if self.cleaned_data['payment_method'] != "Cash" and self.cleaned_data['list_price'] == self.cleaned_data['deposit']: raise forms.ValidationError({'payment_method': 'Payment method cannot be cash when list price and deposit are the same.'}) def clean_finance_balance(self): if self.cleaned_data["payment_method"] != "Cash": self.finance_balance = self.cleaned_data["list_price"] - self.cleaned_data["deposit"] else: self.finance_balance = 0 self.finance_balance = self.cleaned_data["finance_balance"] return self.finance_balance def clean_monthly_payment(self): if self.cleaned_data["payment_method"] != "Cash": # Formula for monthly … -
Advice on methodology for changing datasource of angular material2 datatable
I have an Angular Material2 Database component that I designed that is populated based on a service which makes an http call to my Django database using the django rest framework. I need to present several of these datatables in my website, each with different data using a different URL to the same backend datasource to get the data. I am new to Angular and to the optimal architecture for the language in designing the site. Do I: Create a new component for each datatable, passing the url to the service? Create a new component for each datatable and a new service for each url? Create a single datatable component with a controller and have it connect to the same service, passing the url? Should directives be used to modify the source of the datatable? Thanks for the help on this. I searched multiple places and can't find an example of the situation that I have. Connecting one datatable to an external source is very straight forward in design but multiple tables is a mystery of how best to design this in a DRY and component fashion. -
Django Database Conection to Postgres
im using the default base script to connect to my postgres db, in production using cpanel. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } but when i try run (env) ./manage.py makemigrations, return this line: FATAL: no pg_hba.conf entry for host "::1", user "databaseser", database "databasename", SSL off. Its possible to fix this by CPanel hosting or just editing the postgres config file?, and how? -
RabbitMQ too many unwanted queues
I'm using celery 4.0.2 with RabbitMQ 3.6.14, configured with five queues on four servers connecting to rabbitmq-server running on one of the servers. before a recent deploy on production server, every things just worked fine, but after that, RabbitMQ generates thousands of unwanted queue and after a few hours, RAM usage goes high (20G or higher), celery logs miss heartbeat from other celery servers and stop working. Look at /var/lib/rabbitmq/mnesia/<server_name>/queues shows thousands of files and rabbitmqctl list_queues shows those files: ... d143e25a2ffe4dbca881978d658739b1 1 6046df6f62bc422c981d416706fe4af2 1 4acc0d442fcd43a1b0ef379c370706b1 1 d24e24a680534e33a8572f38d29ea6cd 1 619f7c89b43c4400ad8bf4556ec968d6 1 ffa5a991910941d3a03b844f85880a26 1 41e66894e5c34ad5b32d3e4e6307138c 1 4dd03ac9171448759a7b964a91d7422b 1 24ff24e8fe074f5b979a9d4e4674ba08 1 16ff4b981c11422ca2d437a5fba05706 1 726271ce0ab04886acd7f59fd930dc82 1 c07a58e36fcd4623ae7c4210ef073bdf 1 .... I never created these files (manually or in the code). Also, deleting all mnesia/queues files and restart RabbitMQ works, but only for a few hours and again the same problem. I really appreciate for any help. -
Haystack with Elastic search autocomplete returning empty list - django
In my autocomplete function I am getting query but SearchQuerySet().autocomplete is returning empty list. Here is my models class ProductCreateModel(models.Model): user = models.ForeignKey('accounts.User', related_name='user',db_index=True, on_delete=models.CASCADE,editable=False) title = models.CharField(max_length=120,db_index=True,) slug = models.SlugField(max_length=255,unique=True,blank=True) description = models.TextField(max_length=250,db_index=True,) category = models.ManyToManyField('categories.SubCategory', related_name= 'product_category',db_index=True,) brand_name = models.CharField(max_length=120) Here is my search_index.py class ProductCreateModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/product_text.txt') user = indexes.CharField(model_attr='user',faceted=True ) title = indexes.NgramField(model_attr='title') description = indexes.NgramField(model_attr='description',null = True) category = indexes.CharField(model_attr='category' ) brand = indexes.CharField(model_attr='brand_name',faceted=True ) availability_region = indexes.CharField(model_attr='availability_region',faceted=True ) # district = indexes.CharField(model_attr='product_location.') def get_model(self): return ProductCreateModel def index_queryset(self, using=None): return self.get_model().objects.filter(publish_date__lte=datetime.datetime.now()) Here is my product_text.txt {{object.title}} {{ object.description|default:"" }} In views.py def product_autocomplete(request): print('hello',request.GET.get( 'query')) sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] print(sqs) s = [] for result in sqs: d = {"value": result.title, "data": result.object.slug} s.append(d) output = {'suggestions': s} print('hihi' ,output) return JsonResponse(output) When I search for product in my site it shows empty list as: Quit the server with CTRL-BREAK. [16/Feb/2018 01:30:03] "GET / HTTP/1.1" 200 3256 hello ne PUT http://127.0.0.1:9200/haystack/_mapping/modelresult [status:400 request:0.004s] [] hihi {'suggestions': []} Here query is getting correct but I don't know why the SearchQuerySet().autocomplete() is returning empty list? I am using django-version 2.0.1 ,django-haystack==2.5.1,elasticsearch==5.0.1 -
Custom User model in rest-auth: RelatedObjectDoesNotExist
I am trying to implement the registration using django rest-auth library. I followed every instruction from the installation and usage guide, including the part with a custom user serializer. And here the problems begin. We register a new user, confirm the email and when I try to update the user, i get the same error: "RelatedObjectDoesNotExist at /rest-auth/user/ User has no userprofile." I can't figure out how to make registration to create simultaneously a user and a profile for him. I know that this question has been asked before, but I didn't find anything that would explain why is this happening. I am looking for a bare-simple WORKING example of registration using django-rest-auth and a custom User model models.py: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, related_name='profile') tagline = models.CharField(max_length=140, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @receiver(post_save, sender=User) def create_profile_for_user(sender, instance=None, created=False, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) @receiver(pre_delete, sender=User) def delete_profile_for_user(sender, instance=None, **kwargs): if instance: user_profile = UserProfile.objects.get(user=instance) user_profile.delete() serilizers.py class UserSerializer(UserDetailsSerializer): curriculumVitaeLink = serializers.CharField(source="userprofile.curriculumVitaeLink", required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ( 'curriculumVitaeLink' ) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) curriculumVitaeLink = profile_data.get('curriculumVitaeLink') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if … -
Django TestCase creating new test_ functions with exec and setattr in setUp()
The code below is intended to get programmatically created tests to run, which isn't happening. class TestAdminGetViews(TestCase): def setUp(self): self.factory = RequestFactory() self.admin_user = models.UserManager.create_user(email='test@test.com',password='12387343ad!' ,user_type=utils.UserTypes.admin.name) self.client = Client() #create the test methods programmatically where URLNames.object.name = view.name for url in utils.URLNames: #an Enum object #is there a view associated with with this URLName? if callable(getattr(views,url.name)): #placeholder code just to see if tests run str_function = '''def test_{}(self):\n\tself.assertIs(True,True)\nglobal my_function\nmy_function = test_{}'''.format(url.name, url.name) exec( str_function ) print( my_function ) setattr(self,'test_' + url.name,my_function) #factory, admin_user, client and all the functions show themselves #as being attached to self print(str(self.__dict__)) The print function shows that the code runs "successfully". The dictionary contains factory, admin_user and client, all of which are accessable in the hard-coded test_ functions. The programmatically created functions also show in the dictionary with the correct name and function name. However, the Django test environment does not run the programmatically created functions. Why? A little background color: My last staging deployment had an undetected issue with GET requests. I'd like to avoid those simple errors in the future with tests. Instead of writing a new test_function() for every view, I'd like to create GET view tests programmatically. -
Validate two field uniqueness with ParentalKey
I am trying to validate two field uniqueness (product and attribute) with product being a ParentalKey from modelcluster.fields. However, if I try and add a record I get the following error: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: ProductAttribute has no product. If the record already exists then it runs without error. This makes me think that product doesn't get set until after the clean method is called Here is my model class ProductAttribute(Orderable, models.Model): def __init__(self, *args, **kwargs): super(ProductAttribute, self).__init__(*args, **kwargs) product = ParentalKey('products.Product', related_name='attribute') attribute = models.ForeignKey( 'products.ProductGroupAttribute', ) value = models.CharField( max_length=255, ) def clean(self, *args, **kwargs): if self.product.group.name != self.attribute.group.name: raise ValidationError({'attribute':'Product Group and Attribute Group must be the same'}) super(ProductAttribute, self).clean(*args, **kwargs) my question is, where would I validate those two fields together and be able to gracefully handle the error. I also tried unique_together however that throws a constraint error that I can't really handle gracefully. Thank you in advance. -
How to test Django's UpdateView?
As a simplified example, I've written an UpdateView for a Book model, as well as a ListView to redirect to upon success: from django.urls import reverse from django.views.generic import ListView from django.views.generic.edit import UpdateView from .models import Book class BookUpdate(UpdateView): model = Book fields = ['title', 'author'] class BookList(ListView): model = Book The Book model is defined as class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100, blank=True) def get_absolute_url(self): return reverse('books-list') where urls.py is from django.urls import path from books.views import BookUpdate, BookList urlpatterns = [ path('books/', BookList.as_view(), name='books-list'), path('book/<int:pk>/', BookUpdate.as_view(), name='book-update') ] In books/tests.py I've tried to write the following test: class BookUpdateTest(TestCase): def test_update_book(self): book = Book.objects.create(title='The Catcher in the Rye') response = self.client.post( reverse('book-update', kwargs={'pk': book.id}), {'author': 'J.D. Salinger'}) self.assertEqual(response.status_code, 200) book.refresh_from_db() self.assertEqual(book.author, 'J.D. Salinger') However, this test fails because the book's author appears not to be updated after the POST request, even after refreshing from the database: FAIL: test_update_book (books.tests.BookUpdateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/Scratch/book_project/books/tests.py", line 46, in test_update_book self.assertEqual(book.author, 'J.D. Salinger') AssertionError: '' != 'J.D. Salinger' + J.D. Salinger On the other hand, if I run the development server and fill out the fields manually, everything seems to work as expected. How …