Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework User Foreign Key
I am using the base Django Auth User for my user handling and have authentication working. Now I am trying to create a Post method for my Rest API that automatically gets the user from the request, then gets all of the data input, and saves it. I have tried various attempts at serialization. I also had this working as just a plain Django website, but now things are getting interesting making it into an API. Here is my model: class UserIncome(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) preTaxIncome = models.DecimalField(max_digits=15, decimal_places=2) savingsRate = models.DecimalField(max_digits=3, decimal_places=2) taxRate = models.DecimalField(max_digits=3, decimal_places=2) Here is my Serializer(Base, no attempts at making the foreign key): class UserIncomeSerializer(serializers.ModelSerializer): class Meta: model = models.UserIncome fields = ('id', 'user', 'preTaxIncome', 'savingsRate', 'taxRate') Here is the view(Again, just the base. No attempts at foreign key): class UserIncomeList(APIView): #List all snippets, or create a new snippet. def get(self, request, format=None): userIncome = models.UserIncome.objects.get(user=request.user) serializer = Serializers.UserIncomeSerializer(userIncome, many=False) return Response(serializer.data) def post(self, request, format=None): serializer = Serializers.UserIncomeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Should I just make the foreign key the user ID and get that somehow? Thank you! -
Foreign Key does not get saved into the database
This code will execute fine but the foreignkey records won't save in the database: new_org, created = models.Organization.objects.get_or_create(symbol = row['Symbol'], batch=batch_id) new_org.industry, created = models.DictIndustry.objects.get_or_create(value=row['industry'], batch=batch_id) new_org.sector, created = models.DictSector.objects.get_or_create(value=row['Sector'], batch=batch_id) new_org.save() print(new_org.__dict__) the output has the assigned industry and sector: {'_state': <django.db.models.base.ModelState object at 0x1142d0748>, 'id': 3152, 'date_created': datetime.datetime(2019, 2, 7, 21, 36, 55, 883816, tzinfo=<UTC>), 'date_updated': None, 'generation': 1, 'batch': 0, 'symbol': 'DDD', 'industry': <DictIndustry: Computer Software: Prepackaged Software>, 'sector': <DictSector: Technology>} but the database won't have these records: id | date_created | date_updated | generation | batch | symbol | industry_id | sector_id ------+-------------------------------+--------------+------------+-------+--------+-------------+----------- 3152 | 2019-02-07 16:36:55.883816-05 | | 1 | 0 | DDD | | I suspect it has something to do with the way I coded the models but I can't spot anything that seems to be spoiling it: class BaseModel(models.Model): date_created = models.DateTimeField(auto_now=True) date_updated = models.DateTimeField(null=True, blank=True) generation = models.IntegerField(default=DATA_GENERATION) batch = models.IntegerField() class Meta: abstract = True class AttributeBase(BaseModel): source = models.CharField(max_length=16, blank=False, null=False) def __str__(self): if hasattr(self, 'value'): return self.value raise NotImplementedError("value field not implemented for this model and it should have been") class Meta: abstract = True unique_together = ('source', 'parent', 'value', 'generation') class DictBase(BaseModel): value = models.CharField(max_length=128, unique=True) class … -
Why use Vagrant in a Django project?
I've seen people using vagrant with Django project but I'm struggling to understand why. Like many teams, each member might be running and developing in different OS. Can't we solve this issue by using Docker containers? I'm not sure if I have a misunderstanding on the use of containers or if there's other reason which people prefer using vagrant for. -
VSCode terminal shows incorrect python version and path, launching terminal from anaconda works perfectly
I have been stuck on this one problem for hours now and believe I have tried everything outside of throwing my computer out of the window. I have a virtual environment set up on Anaconda using python version 3.7 and Django version 2.1. If I activate this virtual environment from Anaconda everything works smoothly. (movierecommender) bash-3.2$ python -V Python 3.7.2 (movierecommender) bash-3.2$ python -m django --version 2.1.5 However when I try to activate the environment from a vscode terminal I get (movierecommender) maxs-MBP:movies maxswann$ python -V Python 2.7.10 (movierecommender) maxs-MBP:movies maxswann$ python -m django --version /usr/bin/python: No module named django I have Python 3.7.2 64-bit ('movierecommender':conda) showing as my python interpreter in the bottom left of my vscode window yet still get the wrong python version I thought this may be to do with the PYTHONPATH but have tried unsetting and resetting even though I should not have to worry about this in Anaconda as it automatically adds: "python.pythonPath":"/Users/maxswann/anaconda3/envs/movierecommender/bin/python" to a settings.json.vscode file using: python -c "import sys; print(sys.path)" Anaconda-launched terminal ['', '/Users/maxswann/anaconda3/envs/movierecommender/lib/python37.zip', '/Users/maxswann/anaconda3/envs/movierecommender/lib/python3.7', '/Users/maxswann/anaconda3/envs/movierecommender/lib/python3.7/lib-dynload', '/Users/maxswann/anaconda3/envs/movierecommender/lib/python3.7/site-packages'] Vs Code terminal ['', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC'] As you can see it seems to be using … -
Messages request not running properly
I am trying to send a message error when a user fills out a form incorrectly; however, it is not working. I am receving the error, 'function' object has no attribute 'error'. The messages function works on other pages, but for some reason not on this one. I would greatly appreciate any help. views.py def account_settings_password(request): if request.method == 'POST': form = ChangePasswordForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('/student/dashboard') else: messages.error(request, 'Information was incorrect') else: form = ChangePasswordForm() form = ChangePasswordForm() context = {'form' : form} return render(request, 'student/account_settings_password.html', context) HTML {% for message in messages %} <div class="alert alert-primary"> <a class="close" href="#" data-dismiss="alert">×</a> {{ message }} </div> {% endfor %} -
Cant link stylesheet in django
I'm new to django and cant figure out why my stylesheet isn't linking. Helpp! My directory currently looks like this -Proj ----edashboard ---------edashboard --------------static --------------------stylesheet.css ---------mysite --------------settings.py /settings.py STATIC_URL = '/static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = ( os.path.join(SITE_ROOT, 'static/'), ) /index.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'stylesheet.css'%}"> The results don't display any CSS changes -
How to stop getting this "not found" url routing error in django
Though both links are exactly the same, I keep receiving a "Page Not Found at /accounts/login/next?" error whenever I click my link. What's the error in my code? 'explore' works, but 'happening' doesn't! Please help! views.py def explore(request): return render(request, 'explore.html') def happening(request): return render(request, 'happening.html') html template <div id="happening_log"> <a style= "padding-left:5px" href="{% url 'happening' %}">Happening</a> </div> urls.py urlpatterns = [ path('', views.explore, name='explore'), path('<user__name>/', views.home, name='home'), path('happening/', views.happening, name='happening'), ] Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/happening/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='explore'] <user__name>/ [name='home'] /happening/ [name='happening'] users/ ^static\/(?P<path>.*)$ ^media\/(?P<path>.*)$ The current path, accounts/login/, didn't match any of these. -
Logging not propagating upwards
I have a django project (making use of celery) and I am trying to get my logging arch setup. I would like my main requests to the django be in one log file, with logs for the celery tasks in another. I have defined the following, however, I do not get the logs for internals.tasks.cortex . My thought is that I set the logger for internals which should catch internals.tasks.cortex due to propagation? But it doesn't. It is, however, always output to the root logger! ├── internals │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── celery.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tasks │ │ ├── __init__.py │ │ ├── cortex.py │ │ ├── setup.py │ │ └── submission.py │ └── views.py ├── logs ├── manage.py └── xplorioc ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py settings.py # # Logging configuration LOGLEVEL = os.environ.get('LOGLEVEL', 'DEBUG').upper() LOGGING_CONFIG = None CUSTOM_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { '': { 'level': LOGLEVEL, 'handlers': ['console', 'root'], }, 'internals': { 'level': LOGLEVEL, 'handlers': ['console', 'internals'], 'propagate': False } }, 'formatters': { 'basic': { 'format': '%(asctime)s %(name)s / %(levelname)s / %(message)s', … -
Django unexpected keyword argument 'id'
i'm trying to use arguments on django but when middleware is working on the views.py function, it returns me this error: call() got an unexpected keyword argument 'id'. views.py function @SampleMiddleware def myfunc(request, id): return HttpResponse(id) This is my middleware class SampleMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response This is the URL path('myfunc/<id>', views.myfunc, name='myfunc'), -
How to get all objects linked to a given foreign ket field using rest_framework serializers?
I have two models and I want to call the field values associated with the foreign key present in both the models. For example: Say we have two models: from django.db import models from django.contrib.auth.models import User class Bike(models.Model): bike_model = models.CharField(max_length=200) owner = models.ForeignKey(User,on_delete=models.CASCADE) class Car(models.Model): car_model = models.CharField(max_length=200) owner = models.ForeignKey(User,on_delete=models.CASCADE) And the relating serializer class is: from rest_framework import serializers from .models import Bike,Car class BikeSerializer(serializers.ModelSerializer): class Meta: model = Bike fields = ('bike_model','owner') class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('car_model','owner') Now, I want to add a field in BikeSerializer to get all the cars associated with the given owner. That is I want to make the following change: class BikeSerializer(serializers.ModelSerializer): cars_owned = ??? class Meta: model = Bike fields = ('bike_model','owner','cars_owned') I am unable to get how the cars owned can be returned here? -
DRF create writable not model field
Is there any way to create serializer not model writable field from model two fields? Here is my Serializer class UserProfileSerializer(serializers.ModelSerializer): full_name = ? class Meta: model = users.models.User fields = ( 'phone_number', 'email', 'city', 'full_name' ) I want to connect firts_name and last_name into full_name -
Django + django-storages + S3 -> Cannot upload static files. Cannot access public bucket
I just Django 2.1.5 with Python 3.7. All plugins up to date. I use django-storages to upload my static files to S3. I followed this tutorial: https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ But I cannot upload my static files. The error message is: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I followed the tutorial. I created a group and gave if AmazonS3FullAccess, I created a user and accepted the standard Amazon recommendations. I created a new bucket and accepted the standard Amazon recommendations. If I use AWS_DEFAULT_ACL = None instead of AWS_DEFAULT_ACL = "public-read" I can upload the static files and they show up in the Amazon S3 bucket, but I cannot access them. The URLs are correct, but the XML return/error message ist: "AccessDenied" So what am I missing here? Isn't "public-read" the correct parameter to use here? Why do I not have access if my user is in the group "AmazonS3FullAccess"? Should I just change AWS_DEFAULT_ACL to None? Is this a hacky workaround or is this actually OK to do? But even if I do this and I successfully upload my static files, then I still cannot access them publicly. How do I change my bucket to be … -
How to prevent coverage.py in Django from resetting coverage between runs?
Searched the docs, but couldnt find a way to do this. I've been running my test suite with the following command: coverage manage.py run test tests This will run all tests in the 'tests' folder. Following this, to measure coverage I use the report command: coverage report -m The issue is that this measurement is completely reset between runs. So lets say i run all of my tests in the suite and achieve 85% coverage. If i then run/re-run an individual testcase/testmethod, the coverage measurement is reset so the report will only show coverage for that particular testcase/testmethod that was last run. Per my usage, the only way to get an up-to-date coverage measurement is to re-run all test cases (this takes a long time). Is there a way to have the coverage measurement store previous results, and only modify coverage for results of subsequently run tests? -
Is it possible to save an object in Django by iterating over self._meta.get_fields()?
I am trying to dynamically acquire my Django Models using apps.get_model(), and then call a method from said Model to properly save the data I am passing it. temp_model = apps.get_model(app_label='app', model_name=model)() temp_model.save_data(data) So far, I am able to access the Model's that I am working with, as well as the method within each Object. What I am unsure of is how to properly save the data within the Object. I have been attempting to use self._meta.get_fields() to iterate over each field and set the field equal to the data I am passing it, but this is where I am getting caught up. Here is how I am accessing a list of the Model's fields. This is working as expected. fields = [field for field in self._meta.get_fields() if field.name not in ['id', ]] What I am unsure of is how I can then set the fields data to the appropriate piece of data that I want to pass it, and then save the Object. -
Transform JavaScript 2D Array
I am creating a dashboard to show data from various stats. I am using Django and Google Charts for creating graphs. It has been good so far but I am stuck at one particular case. the model class is- class Registration(models.Model): event_type = models.CharField(max_length=80) date_time = models.DateField() count = models.IntegerField() my query is- Registration.objects.filter(event_type__in=['VHRAssmntCompleted', 'VNAAssmntCompleted', 'NonsmokersDeclrtn', 'MWBAssmntCompleted', 'VHCAssmntCompleted', 'SV Document Uploads', 'PapSmear', 'Mammogram',], date_time__range=(d3,d1)).order_by('date_time') I get the data in following format: [["VHR", "2019-02-1", 23], ["VNA", "2019-02-1", 34], ["PAP", "2019-02-1", 50], ["VHR", "2019-02-2", 92], ["VNA", "2019-02-2", 13], ["PAP", "2019-02-2", 65], ["VHR", "2019-02-3", 192], ["VNA", "2019-02-3", 43], ["PAP", "2019-02-3", 11]] To create a Combo Chart in need the data in following format(something like python dataframe): [["date", "VHR", "VNA", "PAP" ], ["2019-02-1", 23,34,50], ["2019-02-2", 92,13,65], ["2019-02-3", 192,43,11]] I am unable to find a way to do this, either format it using Django ORM query itself or transform using JS. I need help with what approach should I go. -
Generate BTC address from electrum through celery
i want to generate a new receiving address from my electrum wallet. therefor i created a celery task which should save the output of the management call command data to the users modelfield "acc_btc_addr". But somehow i guess my task is buggy and i dont know how i call the tasks.py from a view? Any idea tasks.py @app.task def allocate_new_btc_address(): new_address = management.call_command('electrum', 'createnewaddress') try: user = User.objects.update_or_create(acc_btc_addr=new_address) user.save() logger.info("New BTC address has been allocated to the users account") print(new_address) except Exception as e: print(e) views.py def wallet_deposit_gen_new_addr(request, pk=None): if pk: user = get_user_model.objects.get(pk=pk) if request.method == 'POST': .... else: user = request.user args = {'user': user} return render(request, 'MyProject/wallet_deposit.html', args) models.py class User(AbstractBaseUser): user = models.CharField(verbose_name='Username', max_length=20, unique=True) bio = models.TextField(verbose_name='Bio', blank=True, null=True, max_length=2500) acc_btc_addr = models.CharField(blank=True, null=True, max_length=35) ... -
Create a custom authentication
I'm transferring a database to a new project and more precisely the users. Don't ask me why but the passwords in the old database were hashed with md5 and then sha256. I'm using django-rest-auth to manage login. url(r'^api/rest-auth/', include('rest_auth.urls')), I added a custom authenticate method: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'users.auth.OldCustomAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ) } Here is my auth file: class OldCustomAuthentication(BaseAuthentication): def authenticate(self, request): try: password = request.POST['password'] email = request.POST['email'] except MultiValueDictKeyError: return None if not password or not email: return None password = hashlib.md5(password.encode()) password = hashlib.sha256(password.hexdigest().encode()) try: user = User.objects.get(email=email, password=password.hexdigest()) except User.DoesNotExist: return None # User is found every time print('FOUND USER', user) return user, None But I still get an error when I request apiUrl/rest-auth/login/: { "non_field_errors": [ "Unable to log in with provided credentials." ] } Do you have any idea? Or maybe I'm doing it in a wrong way. Thank you in advance. Jeremy. -
If conditional in django template not reaching some branches
I inherited a django 2.0 project at work and am trying to make what should be a simple change to a conditional in a template html file but cannot get it to reach the new branch. I suspect a syntax issue but can't find it. I have a bunch of rows some of which are rejected, some pending approval, some accepted. This code is meant to display them appropriately: <td class="vert-align blue-madison block"> {% if row.is_rejected %} <span class="label label-sm label-danger"> Rejected </span> {% elif not row.is_active %} <span class="label label-sm label-warning"> Pending review </span> {% elif row.id|row_is_pending_deletion %} <span class="label label-sm label-danger"> Pending deletion </span> {% else %} <span class="label label-sm label-success"> Active </span> {% endif %} </td> four branches; Rejected, Pending Review, Pending Deletion, and Active. Active and Pending Review work fine. I haven't tested Pending Deletion. Rejected is the new branch and I cannot get that to show up as it is above. I know the most recent row has is rejected True as I have tested it in the django shell >>> row.is_rejected True And I know that's the same row because I have looked to make sure the data in the row matches between the … -
How to properly send data from APIClient in Django (rest_framework) for a POST request
I've encountered some strange behavior in a Django unittest. Specifically, I'm using the APIClient module from rest_framework.test to simulate GET/POST requests from a unittest. The issue occurs when updating/creating a new object in the Django ORM via a POST request (see the code below): def test_something(self): data = { "name": 'unit testing', "data": {} } response = self.api_client.post(reverse('save_model'), data, format='json') self.assertEqual(response.status_code, 200) @api_view(['GET', 'POST']) def save_model(request): obj, created = MyModel.objects.update_or_create( user_id=request.user, **request.data ) return JsonResponse({ 'id': obj.id, 'name': obj.name, 'user_id': obj.user_id.id }) The error i receive when running the test case: Error binding parameter 1 - probably unsupported type Based on other stack posts involving this error, i would assume i have a type issue for the second parameter (the data field). However when the same exact data is used to store an object in Django shell, it works every time. Additionally, when the request is made from the client (with the same data) the request succeeds every time. If i print the data in the unittest request i get the following: (, u'{}') (, u'unit testing') (, u'unit testing in django') Model code is below: class MyModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) user_id = models.ForeignKey(AUTH_USER_MODEL) data = JSONField() … -
django-summernote view uploaded image from template
I'm trying to view my uploaded images when uploading from summernote. Here is my static and media for settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = "static/" MEDIA_URL = "/./" This articles.html template displays my static files just fine: {% extends 'base.html' %} {% load static from staticfiles %} {% block content %} {% for post in object_list %} <div class="card rounded border-1 border-secondary"> <div class="card-header bg-dark text-light"> <h4>{{ post.title }}</h4> <small>Posted: {{ post.date }}</small> </div> <div class="card-body bg-light"> <img src={{ post.image.url }} width="300" height="200"> <p class="card-text">{{ post.description }}</p> </div> <div class="card-body bg-light"> <a href="{% url 'post_detail' post.pk %}" class="card-link">Read more...</a> </div> </div> <p></p> {% endfor %} {% endblock content %} I need to embed images in my post_detail.html post.body (|safe just for testing): {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body|safe }}</p> </div> {% endblock content %} When I try to update the post.body with the images I get: [07/Feb/2019 12:43:24] "GET /admin/blog/post/2/change/ HTTP/1.1" 200 10150 [07/Feb/2019 12:43:24] "GET /admin/jsi18n/ HTTP/1.1" 200 3185 [07/Feb/2019 12:43:25] "GET /summernote/editor/id_body/ HTTP/1.1" 200 6349 [07/Feb/2019 12:43:27] "GET /static/summernote/lang/summernote-en-US.min.js?_=1549561406677 HTTP/1.1" 200 27 [07/Feb/2019 12:43:38] "POST /summernote/upload_attachment/ HTTP/1.1" 200 179 Not Found: … -
How to fix "fatal error: Carbon/Carbon.h: No such file or directory", when trying to deploy to Heroku - (Django)
I am attempting to deploy a project I made on to Heroku, but when I try to push the project with: git push heroku master it ends up giving me an error that looks like this: appscript_3x/ext/ae.h:26:10: fatal error: Carbon/Carbon.h: No such file or directory #include <Carbon/Carbon.h> ^~~~~~~~~~~~~~~~~ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-jq3tilcm/appscript/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-dpw2ji3n-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-jq3tilcm/appscript/ ! Push rejected, failed to compile Python app. I've tried searching around for what to do, but I can't find anyone with the same problem and I don't know where to go from here. Any help would be greatly appreciated. -
Django: 'ModelForm' object has no attribute
I'm working with Django Forms in order to create a new object, but I'm having problems with it. It all renders OK, but when I submit the Form, an error is raised: "AttributeError at /rutinas/nueva_rutina 'DiaForm' object has no attribute 'ejercicios'" I've tried many possible solutions I read here, but they didn't work. I think the problem is with the M2M relationship, but it can also be for processing two forms at a time. Here are my files models.py class Ejercicio(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=30, default='') descripcion = models.TextField(default='') gif = models.ImageField(default='') def __str__(self): return self.nombre class Rutina(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=30, default='') def __str__(self): return self.nombre class Dia(models.Model): ejercicios = models.ManyToManyField(Ejercicio) rutina = models.ForeignKey(Rutina, on_delete=models.CASCADE) forms.py class RutinaForm(forms.ModelForm): class Meta: model = Rutina fields = '__all__' labels = { 'nombre': _('Nombre') } class DiaForm(forms.ModelForm): ejercicios = forms.ModelMultipleChoiceField(queryset=Ejercicio.objects.all()) class Meta: model = Dia fields = ['ejercicios'] labels = { 'ejercicios': _('Ejercicios') } views.py def nueva_rutina_view(request): if request.method == "POST": form = RutinaForm(request.POST) dia_form_1 = DiaForm(request.POST) dia_form_2 = DiaForm(request.POST) dia_form_3 = DiaForm(request.POST) if form.is_valid() and dia_form_1.is_valid() and dia_form_2.is_valid() and dia_form_3.is_valid(): rutina = form.save(commit=False) dia1 = dia_form_1.save(commit=False) dia2 = dia_form_2.save(commit=False) dia3 = dia_form_3.save(commit=False) rutina.save() dia1.rutina = rutina dia2.rutina … -
Validation not running in django form
I want to run field validatin on my form, as in form and field validation- using validation in practice. My form looks like this: class NameUpdateForm(forms.Form): name = forms.CharField( validators=[ name_zero_min_length, name_max_length ] ) My validators: from django.core.exceptions import ValidationError def name_zero_min_length(name_field): # Check minimum length if not len(name_field) > 0: print('firing zero length') raise ValidationError( "My custom error message name must be at least one character" ) def name_max_length(name_field): # Check that the name is under the max length MAX_LENGTH = 200 if len(name_field) > MAX_LENGTH: print('raising') raise ValidationError( "My custom error message name cannot be more than {} characters".format(MAX_LENGTH) ) My view like this: def edit_kapsule_name(request, kapsule_pk): kapsule = Kapsule.objects.get(pk=kapsule_pk) form = NameUpdateForm(request.POST) response = {} print('pre-validation') if form.is_valid(): print('VALID') name = form.data.get('name') kapsule.name = name kapsule.save(update_fields=['name']) else: print('INVALID') # INVALID print('json') # json errors = form._errors.as_json() print(errors) # {"name": [{"message": "This field is required.", "code": "required"}]} My output is commented in the above code (invalid, and giving a different error that that which I expected). Why is my custom validation not running? This seems to match with my model validation (working), and the second reponse here -
How to config nginx proxy pass using subfolder domain whith gunicorn Django
How can I configure ngnix to redirect a proxypass from a domain with subfolder to /? Example: https://example.com/yoursub/ to localhost without /yoursub/ prefix At the moment the direct access to the server ip http://xxx.xxx.xxx.xx/ from the intranet works without problems. If it's relevant: The backend is a django app with a gunicorn server. Do I have to consider anything about the redirect from https to http? I have no control over the base domain. -
Fetch as google for Vue Js + Django + Webpack loader
I'm working on a Vue js integrated with django with Webpack loader. I followed this tutorial https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html amongst others. Everthing is working, but Google doesn't see my code (using fetch as google) so I am not referenced. Google is just seeing my "index-prod.html" template where webpack load the vue js. Here is the code of my index page : <html lang="en"> <head> <title>Mayer & Coxxx</title> <meta charset="UTF-8"> <meta name="description" content= "XXX"> <meta name="keywords" content="XX"> <meta name="author" content="XX"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/png" href="/static/red_paint_favicon.png"/> {% render_bundle 'app' 'css' %} </head> <body> <div id=app> </div> {% render_bundle 'manifest' %} {% render_bundle 'vendor' %} {% render_bundle 'app' 'js' %} </body> </html> I have try to use prerender-spa-plugin with vue js but because I'm using django webpack loader, it doesn't work for me. So when I use fetch as google, I just see the and nothing else. I can upload my config files if it can help you. It's my last step before ending my production process, I would be glad to be helped because I'm quite new to webpack :D Thank you very much !