Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/React App: How to have both Django URLS (for the api to send data) and React URLS (to render my components) in my web app, compatibly
I just added this to the urls.py in my react folder: re_path(r'^(?:.*)/?$', views.index), after following this stackoverflow post: react routing and django url conflict. My error in the dev tools is: Unknown_URL_Scheme However, in my situation, this creates problems. My method of sending JSONs to my react is through the url: "api/leads," which is now inaccessible. How do I produce a way for my react urls to exist in harmony with my django urls? Attached are my django urls.py, react--> App.js, urls.py, views.py, index.html, and DataFetching.py (where you will be able to see how I send the data from my api). Django: urls.py from django.urls import path from . import views urlpatterns = [ path('api/lead/', views.LeadListCreate.as_view()), ] Django Project: urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('', include('leads.urls')), path('', include('frontend.urls')), ] React--> urls.py from django.urls import path, re_path from . import views urlpatterns = [ #path('', views.index), re_path(r'^(?:.*)/?$', views.index), ] By the way, I tried to look at the documentation for urls(r^...) and it wouldn't tell me how to import it, but instead basically said that urls is basically the same as re_path; this may be the problem, nonetheless, I would … -
Return updated HTML table values into Views.Py
Hi I have an html table that has values that is originally pulled from a database. They are editable and if the user updates the value, I want to be able return the updated values to Views.py and then from there save the updated value back into the database. For example, I have the table below: <table> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> {% for x in VAR %} <tr> <td>Yes</td> <td>{{ x }}</td> <td><div contenteditable>{{ x.a }}</div></td> <td><div contenteditable>{{ x.b}}</div></td> <td><div contenteditable>{{ x.c}}</div></td> </tr> {% endfor %} </table> If they update x.a for example, I want to return the new value to Views. When I try a POST request, I return a blank value / empty list. How do I return the updated values into my Views.py? -
How do I check if user exists or not and add or update the database in DRF according to that?
I am writing an app in which the user inputs either their email or number to continue. If the user only writes one of those, I need to check if either the email or number belong to an existing user so I can use that user. If the user writes both things, I need to check if the user exists (if it does, I use it, if not I create it). If the user exists with only email or number, I need to update the other field that does not match. I wrote something but I'm not sure how to go on, I'm pretty new at this. This is what I have so far in my serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def checkuser(self, email, number): if order['email'] or order['number'] in User: return User elif order['email'] or order['number'] not in User: pass elif order['email'] and order['number']: if not in User: UserSerializer() elif order['email'] or order['number']: if User.objects.filter(**validated_data).exists(): return User.objects.create(**validated_data) -
Multiple autocomplete-light dropdowns in django template
I am building a web application that requires searching for a specific user record by entering one of two attributes: first name OR last name. Eventually there will be two more search attributes, but currently having problems with having two autocomplete-light drop-downs in the same template. The problem is that only the second input is working as expected. Below are the relevant code sections (with irrelevant code removed). This approach is not "DRY" but my priority is to have a working implementation before optimization/refactoring. forms.py class StudentChoiceFieldLN(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.all().order_by("last_name"), widget=autocomplete.ModelSelect2(url='student-ln-autocomplete'), ) def __init__(self, *args, **kwargs): super(StudentChoiceField, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("last_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) class StudentChoiceFieldFN(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.all().order_by("first_name"), widget=autocomplete.ModelSelect2(url='student-fn-autocomplete'), ) def __init__(self, *args, **kwargs): super(StudentChoiceFieldFN, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("first_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) views.py class StudentLNAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Student.objects.all() if self.q: qs = qs.filter(last_name__istartswith=self.q) return qs class StudentFNAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Student.objects.all() if self.q: qs = qs.filter(first_name__istartswith=self.q) return qs def index(request): students_choice_ln = StudentChoiceFieldLN() students_choice_fn = StudentChoiceFieldFN() context = { 'students_choice_ln': students_choice_ln, 'students_choice_fn': … -
bytes object has no attribute 'encode'
/tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in dispatch response = super().dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/utils.py in post return super().post(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in post return self.render_next_step(form) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in render_next_step return super().render_next_step(form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render_next_step return self.render(new_form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render context = self.get_context_data(form=form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in get_context_data rawkey = unhexlify(key.decode('ascii')) im getting this error and i dont know what exactly should i do, i already tried to change rawkey = unhexlify(key.decode('ascii')) to rawkey = unhexlify(key.encode('ascii')) and im still getting the same exact error. im … -
Django Server Wont Relaunch after change
I've been experimenting with both the django and django rest framework. My projects all used to be working fine, but the other day I had to hard reset my macbook. Since then whenever I go open an old project, or even make a new one whenever I make changes in my vscode project folder, my server does not update and relaunch. Also when I run 'python manage.py migrate' it says there are no migrations to be made, even though I have created new models. The only time python manage.py migrate' had worked was straight after using the 'pip install django'. (Just an fyi, but I completely remade a project I had done previously (a follow through on youtube), when I had first made the project it worked perfectly, but when remaking it the server does not relaunch after changes nor do migrations work) -
PyMongo + Django: MongoClient constructed in settings returning no data
My Django app constructs a MongoClient in the settings file, and this works in local environments. mySettings.py: # mysettings.py MONGO_HOST = os.environ.get('MONGO_HOST') MONGO_PORT = int(os.environ.get('MONGO_PORT')) MONGO_DATABASE = os.environ.get('MONGO_DATABASE') MONGO_USERNAME=os.environ.get('MONGO_USERNAME') MONGO_PASSWORD=os.environ.get('MONGO_PASSWORD') MONGO_CLIENT = MongoClient( host=MONGO_HOST, port=MONGO_PORT, username=MONGO_USERNAME, authSource=MONGO_DATABASE, password=MONGO_PASSWORD, connect=True ) When I use this instance on a local workstation, it works as expected. However, when I use it in a Kubernetes pod, queries like the ones below return zero/empty instead of the proper count/data. #mybrokenscript.py client = settings.MONGO_CLIENT database = client["mydatabase"] collection = database.get_collection('myCollection') print("Count: ", collection.count()) # returns 0, though the collection contains data for doc in collection.find(): # we never get here When I construct a local MongoClient with the same values, it works as expected. #myworkingscript.py client = MongoClient( host=settings.MONGO_HOST, port=settings.MONGO_PORT, username=settings.MONGO_USERNAME, authSource=settings.MONGO_DATABASE, password=settings.MONGO_PASSWORD ) database = client["myDatabase"] collection = database.get_collection('myCollection') print("Count: ", collection.count()) # returns the right number for doc in collection.find(): # works as expected To be clear, the two scripts above generate different results. In the first, Count is 0. In the second, Count is the number of documents in the collection. Any idea what could be happening? Python 3.6.8 Mongo 4.4.4 pymongo 3.7.1 Django 3.1 -
Django Storing Images Locally And Remotely
I have built an image sharing website on django in which i'm storing my thumbnails images on server and original images on object storage. The problem i'm facing is that i'm able to upload the images onto the server and object storage but facing issues to download from object from object storage as my media_root is set at the location of the server. This is my settings.py code : # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') This is my download function code : def download(request,id): previous_url = request.META.get('HTTP_REFERER') if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() ''' End reCAPTCHA validation ''' if result['success']: image = Image.objects.get(id=id) file_name = os.path.basename(image.image.name) file_path = image.image.name fl = storage.open(file_path, "rb") content_type = mimetypes.guess_type(file_path)[0] response = HttpResponse(fl, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(file_path) return response else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return redirect(previous_url) else: return redirect(previous_url) Please refer the error image while download the image : Error Image -
How can I make a field case insensitive and unique only?
I'm trying to add object to my models that are unique and case insensitive so if I add 'car' first and then I try to add 'cAr' it should return an error. I don't know how to that, though. How can I make this happen? This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name This is the serializer: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' -
Django rest-framework ListCreateAPIView doesn't return the full path for the file
I just started using Django rest-framework, and I wanted the JSON response to return the URL for the file stored in the server, I used generics.ListCreateAPIView class class PeopleList(generics.ListCreateAPIView): queryset = People.objects.all().order_by('registration_time') serializer_class = PeopleSerializer and it worked actually! it returned a full path clickable URL: { "id": 1, ... "profile": "http://127.0.0.1:8000/media/profile_image/IMG_20190826_105834_vwKLf10.jpg", ... }, But then I had to use the list function because I needed the request object, now the response only contains the path without the domain: { "id": 1, ... "profile": "/media/profile_image/IMG_20190826_105834_vwKLf10.jpg", ... }, so the question is, How can I return the whole URL? -
How to tell serializer field is in nested dict?
I have the following models: class Holding(models.Model): ticker = models.CharField(max_length=32) class Fund(models.Model): name = models.CharField(max_length=32) holdings = models.ManyToManyField(Holding) JSON looks like this: { "name": "iShares Index Fund" "holdings":[ { "holding": { "ticker": "AAPL" }, { "holding": { "ticker": "AMZN" } ] } My serializers looks like this: class HoldingSerializer(serializers.ModelSerializer): class Meta: model = Holding fields = '__all__' class FundSerializer(serializers.ModelSerializer): holdings = HoldingSerializer(many=True) class Meta: model = Fund fields = '__all__' however it doesn't work because holding is nested How do I tell the HoldingSerializer that the ticker is inside a nested object? I've tried class HoldingSerializer(serializers.ModelSerializer): ticker = serializers.CharField(source='holding.ticker') class Meta: model = Holding fields = '__all__' but I dont think source is used to specify the source in the json; it is used to specify the source from the django models, is that correct? however I still get the error {'holdings': [ { 'ticker': [ErrorDetail(string='This field is required.', code='required')], }, { 'ticker': [ErrorDetail(string='This field is required.', code='required')] }] } -
Adding array into excel using openpyxl (formatting issue)
I am using "openpyxl" to put an array into an excel file for users to download on a django site. The data goes into the excel fine using the following loop: for row_num, row in enumerate(matrix, 3): for col_num, item in enumerate(row, col_start - 12): ws.cell(column=col_num, row=row_num, value=item) wb.save(excel_file_path_from_db) My problem is that when the data enters the excel is is not in number format. I think it could be because i am getting my atix values from a user input via: matrix = ast.literal_eval(list(request.GET)[0]) print(matrix) Any ideas how I can make my matrix come into the excel file in number format? -
Module not found while running server in django
I am trying to start a new django project and I have decided to split my settings into production, staging and development following this tutorial https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html On running python manage.py runserver --settings=mysite.settings.development,I get this error File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crosspoint.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line … -
Django | Adding/changing code in 3rd party packages with monkey patching
(+/- 3 months experience with Django) I'm using the django-newsletter package to create and send newsletters to subscribers on my website. It uses a message.html template for which the context is added in the Submission model: class Submission(models.Model): # Some irrelevant code, only showing the send_message method below: def send_message(self, subscription): variable_dict = { 'subscription': subscription, 'site': Site.objects.get_current(), 'submission': self, 'message': self.message, 'newsletter': self.newsletter, 'date': self.publish_date, 'STATIC_URL': settings.STATIC_URL, 'MEDIA_URL': settings.MEDIA_URL } unescaped_context = get_context(variable_dict, autoescape=False) subject = self.message.subject_template.render( unescaped_context).strip() text = self.message.text_template.render(unescaped_context) message = EmailMultiAlternatives( subject, text, from_email=self.newsletter.get_sender(), to=[subscription.get_recipient()], headers=self.extra_headers, ) if self.message.html_template: escaped_context = get_context(variable_dict) message.attach_alternative( self.message.html_template.render(escaped_context), "text/html" ) # some more code irrelevant to the question message.send() Essentially upon Submitting the newsletter, the context is added in variable_dict in the Submission.send_message method. In order to add more Personalization possibilities I would like to add my own context variables to this. From what I understand is that it's best to use monkey patching to achieve this, but I am not able to access the variable_dict from outside the method itself. Below is my monkey patch code: ## Monkey Patching ## # monkey_patches.py DJANGO_NEWSLETTER_CONTEXT_PATCH = True # adds context to Submission def monkey_patch(): if DJANGO_NEWSLETTER_CONTEXT_PATCH: from newsletter.models import Submission old_send_message … -
how to maintain website on django with redis and memchached on aws
weird question but can I find explanation of how I should control this structure on ec2 instances like one instance for Django one for Redis and other? or I can do in one instance what you all think about that -
Add forms to a Django formset dynamically using htmx?
There are several writeups on how to use javascript to add forms dynamically to a Django formset. For example this or this. I just learned about htmx. How can I add forms dynamically to a Django formset using htmx instead of hand-coded javascript? I thought maybe I could use click-to-load, but it seems odd to call back to the server to get an empty row. Maybe this just isn't an htmx thing. -
Heroku Build succeeded but “application error”
I'm trying to deploy a django application on Heroku. The heroku build succeeded but I have the "application error" when I go to my web site URL host. I don't where I can find a solution, Could you please give me some help ? Here is the build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.9 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.8.6 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.7 Downloading Django-3.1.7-py3-none-any.whl (7.8 MB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0.tar.gz (370 kB) Collecting psycopg2-binary==2.8.6 Downloading psycopg2_binary-2.8.6-cp38-cp38-manylinux1_x86_64.whl (3.0 MB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Collecting asgiref<4,>=3.2.10 Downloading asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting pytz Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) Building wheels for collected packages: gunicorn Building wheel for gunicorn (setup.py): started Building wheel for gunicorn (setup.py): finished with status 'done' Created wheel for gunicorn: filename=gunicorn-20.1.0-py3-none-any.whl size=78917 sha256=6781fff294c8bda3c2eda9afb07e9359bd87e521eb8b3dbc744ece40c3d69fc1 Stored in directory: /tmp/pip-ephem-wheel-cache-tmd9budj/wheels/21/4b/32/9be8daf8a4d73da26e4dba66c47c9b4b7d838a6b372981a3ed Successfully built gunicorn Installing collected packages: dj-database-url, asgiref, sqlparse, pytz, Django, gunicorn, … -
Django app accessing WooCommerce database - how to follow coupon to order relationship in the template
I am developing a Django application which provides read-only access to a WordPress WooCommerce database. I have created a view where I would like to show a list of WooCommerce coupons and any related order data where the coupon was used. The relation between a coupon and the order it was used in is in the table WpWcOrderCouponLookup, and I am passing the contents of this table by adding it as an additional parameter in get_context_data. What I can't figure out is how to access a specific record in the WpWcOrderCouponLookup structure from inside the template. I'll include my code below. Since I am using an existing Wordpress database, my models came from an inspectdb command, and I modified the output to include what I hope are the correct foreign key relations. This is the relevant model code: class WpPosts(models.Model): id = models.BigAutoField(db_column='ID', primary_key=True) # Field name made lowercase. post_author = models.PositiveBigIntegerField() post_date = models.DateTimeField() post_date_gmt = models.DateTimeField() post_content = models.TextField() post_title = models.TextField() post_excerpt = models.TextField() post_status = models.CharField(max_length=20) comment_status = models.CharField(max_length=20) ping_status = models.CharField(max_length=20) post_password = models.CharField(max_length=255) post_name = models.CharField(max_length=200) to_ping = models.TextField() pinged = models.TextField() post_modified = models.DateTimeField() post_modified_gmt = models.DateTimeField() post_content_filtered = models.TextField() post_parent = models.PositiveBigIntegerField() … -
Cannot run django migrations
I have a mysql database. On this database, I have tried to create an account and then grant that account permissions to create a test database and standard database. To look at permissions, I use the following: SHOW GRANTS FOR 'broker_admin'@'localhost'; This then produces an output similar to: 'GRANT USAGE ON *.* TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `dbbrokerdata`.`dbbrokerdata` TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `test_dbbrokerdata`.`test_dbbrokerdata` TO 'broker_admin'@'localhost' When I try to run the django app that uses this database, I get the following errors: django.db.utils.OperationalError: (1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'") django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'")) Watching for file changes with StatReloader Performing system checks... What do I need to do to the user permissions to get django migrations to work properly ? -
Is there way to confirm user email when user change his email - django
i have option that allow user to change email in his profile but without confirm new email so when he enter new email i want activate email to save it in his profile , how to add confirm i am using UserCreationForm models.py : from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() my code | forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), ] html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" … -
'bytes' object has no attribute 'encode' django web app on Azure
/tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in dispatch response = super().dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/utils.py in post return super().post(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in post return self.render_next_step(form) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in render_next_step return super().render_next_step(form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render_next_step return self.render(new_form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render context = self.get_context_data(form=form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in get_context_data rawkey = unhexlify(key.decode('ascii')) im getting this error and i dont know what exactly should i do, i already tried to change rawkey = unhexlify(key.decode('ascii')) to rawkey = unhexlify(key.encode('ascii')) and im still getting the same exact error. im … -
django-rest-framework "This field is required" on POST
Whenever I POST to my django-rest-framework (DRF) endpoints, I keep receiving a "HTTP 400 Bad Request" {"offeror_organization":["This field is required."]} response. But, given the curl example below, I'm clearly specifying a value. This happens regardless of the Content-Type (application/json, application/x-www-form-urlencoded, multipart/form-data). The only time it works is when I submit using the "HTML form" (vs. the "Raw Data") tab on the DRF web interface. There's a few similar SO posts (like this and this), but none of the solutions seem to be working for me. Model: class OrganizationManager(models.Manager): def get_by_natural_key(self, offeror_organization): return self.get(offeror_organization=offeror_organization) class Organization(models.Model): idorganization = models.AutoField(primary_key=True) offeror_organization = models.CharField(max_length=250, null=False, blank=False, verbose_name='Offeror Organization') created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) objects = OrganizationManager() def natural_key(self): return "%s" % (self.offeror_organization) def __str__(self): return self.offeror_organization Serializer: class OrganizationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Organization fields = ['offeror_organization'] # I've tried both with and without a create function def create(self, validated_data): organization_data = validated_data.pop('offeror_organization', None) if organization_data: organization = Organization.objects.get_or_create(**organization_data)[0] validated_data['offeror_organization'] = organization Curl Command: curl -X POST -H 'Content-Type: application/json' -d '{"offeror_organization":"Test2"}' 10.101.10.228:29000/webapp/api/organization/ -
Problem while building path to page with detailed news view
I want it to output all the news when I click on one url, but I can also specify an optional parametric, which, if it exists, will only output the specific news. I can do it. But my navbar in header complains about it. my url: url(r'^news/(?P<year>)',FindNewsView.as_view(), name="news"), error: NoReverseMatch at /news/ Reverse for 'news' with no arguments not found. 1 pattern(s) tried: ['news/(?P<year>)'] <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'news' %}">Новости</a> </div> How do I correct this error? So if I comment out this line, everything will work. I will receive all news or specific news. -
Images and CSS are not being loaded, requires random amount of refresh to load
The problem My company's Django project, running with Nginx and gunicorn, started presenting this issue in the development server. Basically, if I access the app with empty cache, styling files and images are not being loaded at all. Chrome throws the error net::ERR_HTTP2_PROTOCOL_ERROR 200, Safari throws kCFErrorDomainCFNetwork error 303, and Firefox does not throw and error (in fact it gives a 200 for both images and css) but says Stylesheet could not be loaded. However, if I refresh many times the browsers (it could be two times as well as twenty, or more) the images and styles are loaded correctly (one at a time). There are times where some of the images load on first GET request, but it is not a guarantee that those images will be loaded again if I empty cache and refresh. Same setup, different result The funny thing is that on the production server we DO NOT have this problem while both Django settings are the same. The ONLY difference is which DB the apps are pointing to. Both environments have DEBUG set to True. I don't know why prod server has DEBUG set to True, but since it is an app to be used … -
Json in forms.HiddenInput
In project I have a problem with adding json to hiddeninput. When I retrieve a map data in json. I want pass the json to input the form. Works it, when input is visible but I wish it was hidden. I added a widget in form. Unfortunately show me error. | (Hidden field geolokalizacja) This field is required. | forms.py class MapaForm(forms.ModelForm): class Meta: model = Mapa fields = ('geolokalizacja',) widgets = {'geolokalizacja': forms.HiddenInput()} html <form action='.' method='post' enctype='multipart/form-data'> {{ create_form.as_p }} {{ point }} {% csrf_token %} <p><input type="submit" value="Dodaj obiekt"></p> </form> <div id="map" style="height: 512px; width: 512px;"></div> js var popup = L.popup(); function onMapClick(e) { popup.setLatLng(e.latlng).setContent( e.latlng.toString()).openOn(map); var json = {'type': 'Point', 'coordinates': [e.latlng.lng, e.latlng.lat]}; var txt = document.getElementById('id_geolokalizacja'); txt.innerHTML = JSON.stringify(json) } In DOM and Style Inspector appeared to me: <input type="hidden" name="geolokalizacja" value="null" id="id_geolokalizacja"> {"type":"Point","coordinates":[21.91454887390137,52.018592439773414]} </input> It looks like an ale has adopted. Please help