Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the difference between Django socket.io and Django channels?
What should I use to add a chat option on my website?. And what is the easiest to learn?. Can I learn it in 3 to 4 days. -
Is there an Visual Studio Code extension for formatting Django template tasg in Javascript?
I have a piece of code here I want to format <script> objectArray = [] {% for object in allObject %} myObject = { title: "{{object.title}}", number: parseFloat("{{object.number}}"), dateCreated : "{{object.dateCreated}}", } objectArray.push(myObject) {%endfor%} </script> After I "Shirt" + "Alt" + "F" to format it with Beautifier extension, it becomes this <script> objectArray = [] { % for object in allObject % } myObject = { title: "{{object.title}}", number: parseFloat("{{object.number}}"), dateCreated: "{{object.dateCreated}}", } objectArray.push(myObject) { % endfor % } </script> Beautifier can format Django template tags in HTML but it becomes strange when it's in Javascript I think a lot of people have the same problem. It would be great if you guys share your solution -
Django form.is_valid() is False, but not hitting the else statement?
I am working on something that should be pretty simple, but running into a very odd form issue. @csrf_protect def employee_create(request, company_id): template_name = 'business/employee-create.html' data = dict() company = Company.objects.get(id=company_id) if request.method == 'POST': employee_form = EmployeeForm(request.POST) if employee_form.is_valid(): logger.debug('Valid') emp = employee_form.save(commit=False) emp.company = venue emp.user = request.user emp.save() return redirect('comp_detail', company_id=company_id) else: logger.debug('Error') else: employee_form = EmployeeForm() data['html_form'] = render_to_string( template_name, {'form': employee_form, 'company_id': company.id}, request=request, ) return JsonResponse(data) The GET request is just a popup bootstrap form. But my odd situation is happening in the POST request. I am sending an invalid form that is completely empty(in the form modal I get djangos built in form errors popping up) , but the else statement never gets hit, that is supposed to print Error in my django logger. The form is invalid, but is also not invalid? There has to be something that I am missing here?? Thanks in advance for anyone that takes a glance! -
Django: Template statement to check if the user has liked the post or not
Hi Im trying to show a like button with some html class on it if the post is already liked else a button without the html class, I have the following model and I wanna check if the request.user has liked the picture or not on my template. Here's my model: class post(models.Model): user = models.ForeignKey(User, related_name='has_liked', on_delete=models.CASCADE) caption = models.CharField(max_length=100) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User, null=True, blank=True, default='') def __str__(self): return self.caption def total_likes(self): return self.like.count() Here's my view: @login_required def like_post(request): Post = get_object_or_404(post, id=request.GET.get('post_id')) cssClass = 'colorRed' if Post.like.filter(id=request.user.id).exists(): Post.like.remove(request.user) else: Post.like.add(request.user) count = Post.like.count() users = Post.like.all() user = [] for i in users: user.append((i.username)) response = { 'count':count, 'users':user, 'cssClass':cssClass, } return JsonResponse(response) The condition: {% if i.like %} <button id="likeBtn{{ i.id }}" class="likeClassBtn"> <i class="fas fa-heart"></i> </button> {% else %} hello {% endif %} I wanna check the condition on the template Although my view just works perfectly fine. -
404 Not Found error on Django deployment with Apache2 Web Server
I rent a VPS and deployed my Django project to it. And placed my project under /var/www/html which is the accessible directory for Apache2. I get 404 Not Found error. I think apache2 is looking for HTML files under the directory but I look lots of tutorials to make this configuration true. Here is my configuration. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/SistemDedektifi/SistemDedektifi # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or … -
How to pass multiple attributes in error logs as a simple parameter in django?
class Request(APIView): @api_view(['GET']) def test_api_method(self): print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__,'method_name':sys._getframe().f_code.co_name, 'module_name':__package__,'ip_address': socket.gethostbyname(socket.gethostname())}) return Response({'data': True}, status=status.HTTP_200_OK) I have given multiple attributes inside extra={......}. This has become quite lengthy. How to give this as a single parameter, so that I can use that parameter in other classes and methods for logging? -
Stuck at Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
Upgraded pip command still having this message. I am trying to install django-allauth. The following error is generated while using pip install django-allauth (venv) C:\Users\Tubai\PycharmProjects\food>pip install django-allauth Collecting django-allauth Using cached https://files.pythonhosted.org/packages/70/8c/18e9fd164b0e1e578995cf916da49a074b22a629a71c6017455d1ba151e1/django-allauth-0.44.0.tar.gz Requirement already satisfied: Django>=2.0 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from django-allauth) (3.1.7) Collecting python3-openid>=3.0.8 (from django-allauth) Using cached https://files.pythonhosted.org/packages/e0/a5/c6ba13860bdf5525f1ab01e01cc667578d6f1efc8a1dba355700fb04c29b/python3_openid-3.2.0-py3-none-any.whl Collecting requests-oauthlib>=0.3.0 (from django-allauth) Using cached https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl Collecting requests (from django-allauth) Using cached https://files.pythonhosted.org/packages/29/c1/24814557f1d22c56d50280771a17307e6bf87b70727d975fd6b2ce6b014a/requests-2.25.1-py2.py3-none-any.whl Collecting pyjwt[crypto]>=1.7 (from django-allauth) Using cached https://files.pythonhosted.org/packages/3f/32/d5d3cab27fee7f6b22d7cd7507547ae45d52e26030fa77d1f83d0526c6e5/PyJWT-2.1.0-py3-none-any.whl Requirement already satisfied: asgiref<4,>=3.2.10 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (3.3.1) Requirement already satisfied: pytz in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (2021.1) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\tubai\documents\pycharmprojects\ldjangocrash\venv\lib\site-packages (from Django>=2.0->django-allauth) (0.4.1) Collecting defusedxml (from python3-openid>=3.0.8->django-allauth) Using cached https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl Collecting oauthlib>=3.0.0 (from requests-oauthlib>=0.3.0->django-allauth) Using cached https://files.pythonhosted.org/packages/05/57/ce2e7a8fa7c0afb54a0581b14a65b56e62b5759dbc98e80627142b8a3704/oauthlib-3.1.0-py2.py3-none-any.whl Collecting chardet<5,>=3.0.2 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/19/c7/fa589626997dd07bd87d9269342ccb74b1720384a4d739a1872bd84fbe68/chardet-4.0.0-py2.py3-none-any.whl Collecting urllib3<1.27,>=1.21.1 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/0c/cd/1e2ec680ec7b09846dc6e605f5a7709dfb9d7128e51a026e7154e18a234e/urllib3-1.26.5-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/5e/a0/5f06e1e1d463903cf0c0eebeb751791119ed7a4b3737fdc9a77f1cdfb51f/certifi-2020.12.5-py2.py3-none-any.whl Collecting idna<3,>=2.5 (from requests->django-allauth) Using cached https://files.pythonhosted.org/packages/a2/38/928ddce2273eaa564f6f50de919327bf3a00f091b5baba8dfa9460f3a8a8/idna-2.10-py2.py3-none-any.whl Collecting cryptography<4.0.0,>=3.3.1; extra == "crypto" (from pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/9b/77/461087a514d2e8ece1c975d8216bc03f7048e6090c5166bc34115afdaa53/cryptography-3.4.7.tar.gz Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Collecting cffi>=1.12 (from cryptography<4.0.0,>=3.3.1; extra == "crypto"->pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/c6/92/9188a1dff4934d0bd18df7f92dc481324b3342814cea34849b393ea2d232/cffi-1.14.5-cp37-cp37m-win_amd64.whl Collecting pycparser (from cffi>=1.12->cryptography<4.0.0,>=3.3.1; extra == "crypto"->pyjwt[crypto]>=1.7->django-allauth) Using cached https://files.pythonhosted.org/packages/ae/e7/d9c3a176ca4b02024debf82342dab36efadfc5776f9c8db077e8f6e71821/pycparser-2.20-py2.py3-none-any.whl Building wheels for collected packages: cryptography Building wheel for cryptography (PEP 517) ... error Complete … -
Django all-auth Slack: Redirect URL as https instead of http and Social Network Login Failure
Hi I am using django all-auth with Slack. However, I have 2 problems. 1st: the redirect URL always goes to HTTP instead of HTTPS. E.g. I click on ***.ngrok.io/accounts/slack/login and then get redirected to https://***.slack.com/oauth?client_id=1737791866593.2107881969061&scope=identify&user_scope=&redirect_uri=http%3A%2F%2F***.ngrok.io%2Faccounts%2Fslack%2Flogin%2Fcallback%2F&state=ANmZKE1CMWq7&granular_bot_scope=0&single_channel=0&install_redirect=&tracked=1&response_type=code&team= as you can see the redirect_uri is HTTP. How can I change this in django all-auth? 2nd: After manually changing it I am still not able to login as I get the error below (see picture): e.g. https://django-allauth.readthedocs.io/en/latest/providers.html#slack -
Django: "AttributeError: type object 'AutoField' has no attribute 'rsplit'" after adding "DEFAULT_AUTO_FIELD" to settings.py
I just updated my Django project from 3.1.6 to 3.2.3. After running python manage.py runserver, the server ran with these warnings: core.CoreUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the CoreConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. Then I remembered that I need to add a DEFAULT_AUTO_FIELD setting to settings.py after updating a project to Django from version < 3.2 to version >= 3.2, so I did: # settings.py DEFAULT_AUTO_FIELD = django.db.models.AutoField Then I tried python manage.py runserver again, but this time I got a different warning: (venv) C:\Users\Chris\my_project>python manage.py runserver Traceback (most recent call last): ... (truncated for brevity) File "C:\Users\Chris\my_project\venv\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: type object 'AutoField' has no attribute 'rsplit' I thought that something about my migrations or database was causing the issue, so I deleted db.sqlite3 and all of the app's migrations. Then I ran a fresh python manage.py makemigrations, except that caused the same error: AttributeError: type object 'AutoField' has no attribute 'rsplit' Any ideas why this might be happening? -
DJANGO Paginated ajax results not working
I have a table for tracking job applications and im trying to implement a filter feature. I want to display the results with pagination. However, I am getting errors when trying to do so and can't seem to find my way out of it. Would be glad if someone can help Thank youu Here is my code: template file <ul id="filter_list" class="dropdown-menu"> <li><a href="#">Alphabetical Order (A-Z)</a></li> <li><a href="#">Application Date (Ascending)</a></li> <li><a href="#">Application Date (Descending)</a></li> <li><a href="#">Closing Date</a></li> </ul> <div id="table_results"> <div> <script> $(".dropdown-menu a").click(function(){ var selected_filter = $(this).text(); $.ajax({ url:'{% url "stu_filter_applications" %}', data:{ "filter_category": selected_filter, }, dataType:'json', success: function (response) { $("#table_results").html(''); #to test if its working }, error: function (response) { console.log(response.errors); }, }); }); </script> views.py: def stu_filter_applications(request): if request.is_ajax(): filter_cat = request.GET.get("filter_category", None) student = StudentUser.objects.get(user=request.user) int_apps = InternshipApplication.objects.filter(student=student) int_app = [] applications = [] for app in int_apps: #for each application, grab the internship and the recruiter if filter_cat == "Alphabetical Order (A-Z)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('internship.internship_title') if filter_cat == "Application Date (Ascending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('application_date') if filter_cat == "Application Date (Descending)": internship = Internship.objects.get(id=app.internship.id) int_applications = InternshipApplication.objects.filter(student=student).values(). order_by('-application_date') recruiter = Recruiter.objects.get(id=internship.recruiter.id) int_app.append((internship,recruiter,int_applications)) applications = int_app.copy() paginator = … -
PDF output using django-weasyprint not using css files
I am trying to output PDF using the django-weasyprint package. When opening my detail view, I manage to create the html I wanted. When I want to download it, it looks like messy and doesn`t match the html file. Here is my views file. How can I add a css file to the DownloadPDF function. views.py class InvoiceView(DetailView): # vanilla Django DetailView model = Invoice template_name = 'accounting/invoices/invoice_pdf.html' class CustomWeasyTemplateResponse(WeasyTemplateResponse): # customized response class to change the default URL fetcher def get_url_fetcher(self): # disable host and certificate check context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE return functools.partial(django_url_fetcher, ssl_context=context) class InvoicePrintView(WeasyTemplateResponseMixin, InvoiceView): # output of MyModelView rendered as PDF with hardcoded CSS pdf_stylesheets = [ settings.STATIC_URL + 'core/static/assets/css/pages/invoice.css', ] # show pdf in-line (default: True, show download dialog) pdf_attachment = False # custom response class to configure url-fetcher response_class = CustomWeasyTemplateResponse class InvoiceDownloadView(WeasyTemplateResponseMixin, InvoiceView): # suggested filename (is required for attachment/download!) pdf_filename = 'invoice.pdf' class InvoiceImageView(WeasyTemplateResponseMixin, InvoiceView): # generate a PNG image instead content_type = CONTENT_TYPE_PNG # dynamically generate filename def get_pdf_filename(self): return 'foo-{at}.pdf'.format( at=timezone.now().strftime('%Y%m%d-%H%M'), ) Many Thanks, -
I'm facing some problem in this code. I want to access the value of time1 in variable t but i don't know how?
def python_view(request): global time1 time1=datetime.datetime.now() mcq=Pythonmcq.objects.all() paginator=Paginator(mcq,1) page_number=request.GET.get('page') try: mcq=paginator.page(page_number) except PageNotAnInteger: mcq=paginator.page(1) except EmptyPage: mcq=paginator.page(page.num_pages) return render(request,'testApp/pythonexam.html',{'mcq':mcq,'time1':time1}) def result_view(request): t=python_view(time1) return render(request, 'testApp/result.html',{'time':t}) -
Passing JsonResponse data (from Django views) as a url parameter in Javascript is not working
I am making a website in django that has paypal client side payment integration. My payment works fine but after payment is completed, i send the delivery data to a django views function using fetch API and views function returns me a JsonResponse. I am trying to pass data from that response as a url parameter to another django view which will render a success page about the order with a few details in it. The problem I encounter is as follows: NoReverseMatch at /product-details/payment Reverse for 'order_successful' with keyword arguments '{'DATA': ''}' not found. 1 pattern(s) tried: ['order_successful/(?P[^/]+)$'] here is code for checkout.html which is calling paymentComplete.views <script> function completeOrder(){ var url = "{% url 'paymentComplete' %}" fetch(url, { method: 'POST', headers:{ 'Content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'prodID': prodId, 'quantity': quantityBought, 'bill': total, 'fName': fName, 'lName': lName, 'apt': apt, 'street': street, 'city': city, 'state': state, 'zipcode': zipcode, 'country': country, 'email': email, 'phone': phone}) }) .then(response => response.json()) .then((data) => { console.log('Success ', data); console.log(typeof data); alert('Transaction Completed'); window.location.href = "{% url 'order_successful' DATA=data %}" }) } </script> following is code for paymentComplete.views def paymentComplete(request): body = json.loads(request.body) prod_ID = int(body['prodID']) prod_Qt_bought = int(body['quantity']) bill_paid = str(body['bill']) #loading product from … -
django templates {{form.errors}} not showing
I have a problem my website. Please help me. This is my template folder. {% extends "layout.html" %} {% block head %} <title>Login</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } .login_btn:focus { box-shadow: none !important; outline: 0px !important; } .login_container { padding: 0 2rem; } .input-group-text { background: #f7ba5b !important; color: white !important; border: 0 !important; border-radius: 0.25rem 0 0 0.25rem !important; } .input_user, .input_pass:focus { box-shadow: none !important; outline: 0px !important; } </style> {% endblock %} {% block body %} <div class="container h-100"> <div class="d-flex justify-content-center … -
Problem with decimal field in django v3.2
After upgrading from version 3.1 to version 3.2, I found precision problem in using decimal field. Following example is a small code which could regenerate problem. from django.db import models class Foo(models.Model): amount = models.DecimalField( null=False, decimal_places=18, max_digits=44) # A simple insertion example from api.models import Foo from django.db.models import F from decimal import Decimal f = Foo.objects.create(amount=Decimal('0.5')) f.amount = F('amount') - Decimal('0.4') f.save(update_fields=['amount', ]) f.refresh_from_db() print(f.amount) This code generates 0.099999999999999980 but same code in previous version generate expected result 0.01. By checking mysql query generated for update query, I found that in new version number has sent using a quotation but in previous one there were no quotation. i.e in new version we have something like this UPDATE `api_foo` SET `amount` = (`api_foo`.`amount` - '0.4') WHERE `api_foo`.`id` = 1 but in previous one we had UPDATE `api_foo` SET `amount` = (`api_foo`.`amount` - 0.4) WHERE `api_foo`.`id` = 1. Also I must mention that this happens just in mysql driver not in sqllite. I know this seems like a bug, but I guessed that I am missing something trivial. I am using mysql-8.0.19 and I got the same value in versions 3.2 and 3.2.3 of django. -
How do i restrict adding a new record?
I want to use a table as options table by id = 1. Is that a good practice? How do i NOT let adding new records via admin panel? Thank you! -
cannot load library 'C:\Program Files\R\R-4.1.in': error 0x7e
I am getting a exception in thread django-main-thread error. when referencing ffi.dlopen('C:\Program Files\R\R-4.1.0\bin'). The error is "cannot load library 'C:\Program Files\R\R-4.1.in': error 0x7e" I don't understand why it changes "bin" to "in". any help would be appreciated. I am new to Django so it could be a super simple problem. Thanks -
AttributeError 'str' object has no attribute 'add'
I am working on a project which has multiple types of users. Such as students, teachers, staff, etc, I use Django AbstractBaseUser to define my own fields. Problem: At the time that I save a user as a student; in addition to email and password, I also want to save some more information about the student user, such as profile info. The same pattern should be applied to other types of users as well. I tested various ways which came appropriate for this problem but none of them work. accounts/models.py objects = UserManager() username = models.CharField(max_length=255, null=True, blank=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) student = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] students/models.py class Student(models.Model): first_name = models.CharField(max_length=200) father_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) ... accounts/form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.db import transaction from django.forms import formsets from django.forms.forms import Form from .models import CustomUser from students.models import Student, InterestTopic class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(max_length=200, required=True) class Meta(UserCreationForm.Meta): model = CustomUser fields = ['email', 'password1', 'password2'] @transaction.atomic def save(self): user = super().save(commit=False) user.student = True user.save() student = Student.objects.create( user=user, ) student.first_name.add(*self.cleaned_data.get('first_name')) return … -
Type Error: expected string or bytes-like object in python
I am facing an error that occurs whenever I try to python manage.py migrate. It says: Apply all migrations: admin, aufgabenzettel, auth, contenttypes, sessions Running migrations: Applying aufgabenzettel.0005_auto_20210526_1527...Traceback (most recent call last): File "C:\Users\adam_\Documents\Coding\My_First\Aufgabenliste\manage.py", line 22, in <module> main() File "C:\Users\adam_\Documents\Coding\My_First\Aufgabenliste\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self._remake_table(model, create_field=field) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in _remake_table self.effective_default(create_field) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 303, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 823, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1378, in get_db_prep_value value = self.get_prep_value(value) File "C:\Users\adam_\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value value = … -
Graphene Subscription error (has no attribute 'execute')
I am trying to make subscriptions work in my Django application. I have have followed the tutorial on the apollo client subscriptions part (https://www.apollographql.com/docs/react/data/subscriptions/): For the backend I have used this plugin (https://pypi.org/project/graphene-subscriptions/) and followed the instructions step by step as well, installing Django channels and setting the channel layers adding the query in the schema etc. However, I get an error when I try to 'do' the subscription and I believe it's a more general problem than one caused by the plugin I used. I was hoping one of you might have an idea what I did wrong. This is some of the relevant code: const httpLink = new HttpLink({ uri: "http://localhost:8000/graphql/", // use https for secure endpoint }); // Create a WebSocket link: const wsLink = new WebSocketLink({ uri: "ws://localhost:8000/graphql/", // use wss for a secure endpoint options: { reconnect: true } }); // using the ability to split links, you can send data to each link // depending on what kind of operation is being sent const link = split( // split based on operation type ({ query }) => { const { kind, operation } = getMainDefinition(query); return kind === 'OperationDefinition' && operation === 'subscription'; }, … -
Custom Id in Django Models
In my model I need an ID field that is different from the default ID given by Django. I need my IDs in the following format: [year][ascending number] Example: 2021001,2021002,2021003 The IDs shall not be editable but model entries shall take the year for the ID from a DateTimeField in the model. I am unsure if I use a normal Django ID and also create some kind of additional ID for the model or if I replace the normal Django ID with a Custom ID. -
The boolen field is not editable in django admin error
there is a error like this <class 'shop.admin.ProductAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'available', which is not a callable, an attribute of 'ProductAdmin', or an attribute or method on 'shop.Product'. class Product(models.Model): .... availabel=models.BooleanField(default=True) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'slug', 'price','available', 'created', 'updated') list_editable = ('price', 'available') list_filter = ('available', 'created', 'updated') prepopulated_fields = {'slug': ('name',)} -
How to identify if a field's choices have changed in django model?
I have a model like this: class MyModel(models.Model): status_choices = ( ('in_progress', 'In Progress'), ('in_review', 'In Review'), ('active', 'Active'), ) # I want to detect when these choices are changed and trigger a function status = models.CharField(choices=status_choices, max_length=20, blank=True) # other model fields Here the status choices can be changed, and I want to detect if the choices have changed and then trigger a function call. I know there is post_init listener, but how can I compare my cuurent choices with the previous choices when initializing the model? -
How to solve ATTRIBUTE ERROR: 'function' object has no attribute 'get_host'
When ever i run my server i get this error ATTRIBUTE ERROR: 'function' object has no attribute 'get_host' in my context_proccessors.py file please how do I solve this?? Here is my full code __author__ = 'derek' from chat.settings import VALIDATION_IS_OK, API_ADDRESS_PATTERN, JS_CONSOLE_LOGS def add_user_name(request): """ Adds commons template variables tornado url, authorized, username, success constant """ return { # "wss://%s:PORT/" % domain, 'apiUrl': API_ADDRESS_PATTERN % request.get_host().split(':')[0], 'successResponse': VALIDATION_IS_OK, 'username': request.user.username if request.user.is_authenticated() else '', 'userid': request.user.id if request.user.is_authenticated() else 0, 'logs': request.user.userprofile.logs if request.user.is_authenticated() else JS_CONSOLE_LOGS } Thanks in advance -
How to prevent a new line character (\n) of a string from being the part of the string and not doing its job in python?
Looking for help solving an issue. I have stored a public key in .env file, public key is having \n in it and for .env i have used python dcouple but when I am using the environment variable in a function then \n is not doing its job but it is becoming the part of the string. .env KEY=-----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n utility.py var = data(KEY=config('KEY')) print(config('KEY')) #it is not giving the desired result its printing below result -----BEGIN PUBLIC KEY-----\nAp4k567H7J7\nG2rtJH\nLok1FG3\n-----END PUBLIC KEY-----\n but i need this string to be like this when used in utility.py -----BEGIN PUBLIC KEY----- Ap4k567H7J7 G2rtJH Lok1FG3 -----END PUBLIC KEY-----