Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Mysql Error no such table: auth_user
i add mysql to django. i install pymysql on venv and after i add this code to settings.py when i make migration everything goes on mysql database and even when i crate superuser it was created on plesk database server PHPmyadmin. but when i want login to admin which is created in mysql database. i'm getting error Exception Value: no such table: auth_user Exception Location: /var/www/vhosts/domain/httpdocs/python-app-venv/lib/python3.6/site- packages/django/db/backends/sqlite3/base.py, line 413, in execute import os from pathlib import Path import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': 'localhost', 'PORT': '3306', } } -
django runserver command erro
OS: Windows 10 Now, for the project where the runserver command works I get this: Here is my project structure. i have install all the requirements for this project but still getting this error. I've found something where there were errors with the run server command, but none were satisfying. If this is a duplicate, I do apologies, but I'm pretty sure it isn't. If there's a need for other files and snippets of code, I'll put here everything. Thank you so much. D:. | main.py | | README.md | +---BLL | | asgi.py | | requirements.txt | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-37.pyc | settings.cpython-39.pyc | urls.cpython-37.pyc | urls.cpython-39.pyc | __init__.cpython-37.pyc | __init__.cpython-39.pyc | +---DAL | | db.sqlite3 | | __init__.py | | | +---account | | | admin.py | | | apps.py | | | forms.py | | | models.py | | | tests.py | | | views.py | | | __init__.py | | | | | +---migrations | | | | 0001_initial.py | | | | __init__.py | | | | | | | \---__pycache__ | | | 0001_initial.cpython-38.pyc | | | __init__.cpython-38.pyc | | | … -
Page not found (404) Request Method: GET ....... the current path, blog/blogpost, didn't match any of these
Hi i am trying to make blog website but while i fetch model with blogpost function in views.py its shows error that 404 page not found like ||Using the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ [name='BlogHome'] blog The current path, blog/blogpost, didn't match any of these. || -until i don't create model it works fine but after creating model and trying to fetch articles through post_id it throws error as page not found! -what am i missing? -Here is the codes i am using. code of blog/views.py -> enter image description here code of blog/urls.py -> enter image description here code of mac/views.py -> enter image description here code of blog/adminpy -> enter image description here code of blog/models.py -> enter image description here terminal error while loading blogpost page -> enter image description here -
Unable to understand the django-quickbook webco
I am working on a Django web application and I want to push data to Quickbook Desktop. So i was following this link. https://github.com/ricardosasilva/django-to-quickbooks-connector#readme I mean How to use it? there is no documentation -
Django ORM Need help speeding up query, connected to additional tables
Running Django 1.6.5 (very old i know but can't upgrade at the moment since this is production). I'm working on a view where I need to perform a query and get data from a couple other tables which have the same field on it (though on the other tables the ord_num key may exist multiple times, they are not foreign keys). When I attempt to render this queryset into the view, it takes a very long time. Any idea how i can speed this up? view queryset: qs = Outordhdr.objects.filter( status__in=[10, 81], ti_type='@' ).exclude( ord_num__in=Shipclosewq.objects.values('ord_num') ).filter( ord_num__in=Pickconhdr.objects.values_list('ord_num', flat=True) ).order_by( 'sch_shp_dt', 'wave_num', 'shp_dock_num' ) Models file: class Outordhdr(models.Model): ord_num = models.CharField(max_length=13, primary_key=True) def get_conts_loaded(self): return self.pickcons.filter(cont_dvrt_flg__in=['C', 'R']).aggregate( conts_loaded=models.Count('ord_num'), last_conts_loaded=models.Max('cont_scan_dt') ) @property def conts_left(self): return self.pickcons.exclude(cont_dvrt_flg__in=['C', 'R']).aggregate( conts_left=models.Count('ord_num')).values()[0] @property def last_conts_loaded(self): return self.get_conts_loaded().get('last_conts_loaded', 0) @property def conts_loaded(self): return self.get_conts_loaded().get('conts_loaded', 0) @property def tot_conts(self): return self.conts_loaded + self.conts_left @property def minutes_since_last_load(self): if self.last_conts_loaded: return round((get_db_current_datetime() - self.last_conts_loaded).total_seconds() / 60) class Meta: db_table = u'outordhdr' class Pickconhdr(models.Model): ord_num = models.ForeignKey(Outordhdr, db_column='ord_num', max_length=13, related_name='pickcons') cont_num = models.CharField(max_length=20, primary_key=True) class Meta: db_table = u'pickconhdr' -
message sent from contact page dont reflect on the django admin database
am working on contact me page where if a message/feedback is sent, it reflects in django admin database, the page seems to be working fine, however, when the message is sent, it does not show up in admin database below is my models.py from django.db import models # Create your models here. class Contacts(models.Model): name = models.CharField(max_length=20 , null=True, editable=False, help_text="Name of sender") email = models.EmailField(max_length=50 , null=True, editable=False) subject = models.CharField(max_length=100 , null=True, editable=False) message = models.TextField(null=True, editable=False) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Feedback" def __str__(self): return self.name + "" + self.email views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Contacts #from django.core.mail import send_mail, BadHeaderError #from django.conf import settings from django.contrib import messages # Create your views here. def Contacts(request): if request.method == 'POST': messages.add_message(request, messages.INFO, 'Feedback Submitted.') return redirect('Feedback') return render(request, 'Contacts/index.html', {}) def Feedback(request): return HttpResponse("Thank you for the feedback, a response will be sent to you shortly!") admin.py from django.contrib import admin from .models import Contacts # Register your models here. class ContactsAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'subject','date',) search_fields = ('name', 'email',) date_hierarchy = 'date' admin.site.register(Contacts, ContactsAdmin) -
trying to host on pythonanywhere but getting errors
There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception -
Is there a way in algolia to do some like this:
I have a query string "hello how are". I want results which contain : 'hello how are', 'hello how', 'how are', 'hello', 'how', 'are' And i'm using **Algolia**, django, React InstantSearch . It is related to algolia and instantserach. -
Is there is any way to use explainx library in django? [closed]
Can Anyone please help me. I want to use explainx library in django/(django rest framework) please help me ho to implement this library in django -
Django - What is faster between Filter() and All()
I have two queries: query1 = MyObject.objects.all() query2 = MyObject.objects.filter(my_filter=my_value) What is faster between query1 and query2, and why ? Also I am using PostgreSQL for my database. -
python create dictionary from two list
In my code i am getting values like this keys = request.POST.get('keys') KeysList = json.loads(keys) values = request.POST.get('values') valuesList = json.loads(values) After print statement i am getting values in list like : keys = ['A', 'B', 'C', 'D'] Values = ['true', 'false', 'true', 'true'] but what i exactly want is like i want a dictionary in this way : updateObj = { 'A' : 'true', 'B' : 'false', 'C' : 'true', 'D' : 'true', } how can i achieve this can any one please suggest me for this ?? i am stuck here thanks in advance -
particular id record as a first record when i select all record
I want a list of all records, but i want that particular primary key id ( ex: 55) return as a first row in my selected records. in FE one of the page has all records as well as a single record in same page, now if user enter any known number in URL or they redirect from email then detail is opened for that particular record but record not display into the all record list due to pagination, so i want that i get that id which user is trying to open so i can return that particular id record as a first record in the list. i want this with Django rest framework. -
How to make only 1 refresh on multiple clicks python/django
I have a site using GCP python API, which is quite slow at making pull requests. So I have cached the area of the template using this data, and in the view I check if the cache is still active before making any more requests (not a copy n pasted code so if theres any typos ignore em :) ) def gcpProjectsView(request): gcpprojects = None cached_time = None if cache.get(make_template_fragment_key('gcp')) is None: cached_time=timezone.now() gcpprojects = get_gcp_projects() return render (request , 'gcp/gcpprojects.html', {'gcpprojects':gcpprojects,'last_update':cache_time}) To manually update the data, I have a refresh button that points to this view: def refresh_gcp(request): cache.delete(make_template_fragment_key('gcp')) return redirect('gcpProjectsView') The problem is that if the user clicks the refresh button 5 times the view makes 5 GCP Api calls, it needs to only do 1. How do I resolve this issue? -
Comment is not adding after Click but after Refresh
I am building a BlogApp . I am using - Django , Ajax. AND i built a Comment Reply system. Everything is working ( First omment adding is working fine , showing replies is working fine ) BUT when i click on Comment Button for reply the Comment then nothing happens BUT when i refresh the browser page then One reply add . It supposed to add comment right after click on Reply Comment ( without refresh ). BUT it is not working. detail.html {% for comment in comments %} <div class="comment"> <p class="info"> {{ comment.created_at|naturaltime }} Commented by :- <a href="{% url 'mains:show_profile' user_id=comment.commented_by.id %}"> {{ comment.commented_by }}</a> {{ topic.post_owner }} </p> {{ comment.comment_body|linebreaks }} <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#commentReadMore{{comment.id}}').click(function (event) { event.preventDefault() $('#commentDescription{{comment.id}}').html( `{{comment.description}}`) }) }) }) </script> <a class="btn btn-info btn-circle" href="#" id="addReply{{comment.id}}"><span class="glyphicon glyphicon-share-alt"></span> Reply</a> <a class="btn btn-warning btn-circle" data-toggle="collapse" href="#replyOne" id="showReplies{{comment.id}}"><span class="glyphicon glyphicon-comment"></span>{{comment.reply_set.count}} Replies</a> <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#showReplies{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyList{{comment.id}}').slideToggle() }) $('#replyForm{{comment.id}}').slideToggle() $('#addReply{{comment.id}}').click(function (event) { event.preventDefault(); $('#replyForm{{comment.id}}').slideToggle() $('#showReplies{{comment.id}}').click() }) $('#cancelCommentReply{{comment.id}}').click(function (event) { event.preventDefault; $('#replyForm{{comment.id}}').toggle(); $('#commentReplyInput{{comment.id}}').val('') }) $('#replyForm{{comment.id}}').submit(function (event) { event.preventDefault(); $.ajax({ url: "{% url 'mains:create_reply' comment.id %}", data: { 'description': $( '#commentReplyInput{{comment.id}}' … -
Firebase pyfcm send push notification with an action buttons how?
so this the code which triggered the push notification with Image but need Action as Share any help? push_service.notify_single_device( registration_id='', message_title=title, message_body=messageBody, content_available=True, extra_kwargs=extra_kwargs, click_action=enter code here, extra_notification_kwargs=extra_notification_kwargs) thanks -
Duplicated code in create and update methods inside ModelSerializer in DRF
I have created a ModelSerializer where I override default create and update methods and found the code to be pretty much the same. It is responsible for saving Images (connected via FK) and matching PaymentMethods (connected via M2M) in case of creating and replace Images and PaymentMethods in case of updating but the main validation and creation logic is the same. Is there any way to shorten this? I haven't found so far any resources for this possibility. class TruckSerializer(serializers.ModelSerializer): location = LocationSerializer(read_only=True,) owner = serializers.PrimaryKeyRelatedField(read_only=True,) class Meta: model = Truck fields = "__all__" def create(self, validated_data): data = self.context.get("view").request.data if data.get("payment"): new_payments = [] payments = data.get("payment") for payment in payments.split(", "): try: filtered_payment = PaymentMethod.objects.get( payment_name__iexact=payment).id except PaymentMethod.DoesNotExist: raise serializers.ValidationError( 'Given payment method does not match') new_payments.append(filtered_payment) truck = Truck.objects.create(**validated_data) <---- valid only in create truck.payment_methods.add(*new_payments) if data.get("image"): for image_data in data.getlist("image"): TruckImage.objects.create(truck=truck, image=image_data) return truck def update(self, instance, validated_data): data = self.context.get("view").request.data if data.get("payment"): new_payments = [] payments = data.get("payment") for payment in payments.split(", "): try: filtered_payment = PaymentMethod.objects.get( payment_name__iexact=payment).id except PaymentMethod.DoesNotExist: raise serializers.ValidationError( 'Given payment method does not match') new_payments.append(filtered_payment) instance.payment_methods.clear() <---- valid only in update instance.payment_methods.add(*new_payments) if data.get("image"): images = instance.images.all() if images.exists(): <---- valid … -
After the added product is updated and edited, another new detail page will be generated, but the original modified page was not updated
Python 3.8.3 Django 2.2 asgiref 3.3.1 djangorestframework 3.11.1 Pillow 7.2.0 pip 19.2.3 psycopg2 2.8.6 pytz 2020.1 setuptools 41.2.0 sqlparse 0.3.1 May I ask the great god, The newly added product object needs to be edited, but after editing it becomes another addition. For example: Enter the item 3 product, edit the content and click "Confirm Edit". The original item is the item number 3 and instantly becomes the item item No. 4. After each edit or update, it will become a new product page. What is the program part? Is there a mistake? Add again: Originally wanted to edit this page http://127.0.0.1:8001/store/107/(id=107), After editing and archiving, the page that pops up is a new id=111 page. http://127.0.0.1:8001/store/111/ (id=111) But I enter admin http://127.0.0.1:8001/admin/store/product/111/change/ After the change, there is no problem, and you can edit it. This error only appears on the screen of my newly created form. Find a solution: There is a similar "editing" program on the Internet. The writing method is similar to what I wrote, but I cannot edit the product with id=107. How can I solve it? urls.py path('<int:id>/edit/', views.productUpdate, name='edit'), views.py def productUpdate(request, id=None): # basic use permissions 基本使用權限 if not request.user.is_staff or not request.user.is_superuser: … -
Deploying Django app to Heroku: Exception in worker process
I'm trying to deploy my Django website to Heroku. I've followed all the steps as well as I could. I created my Procfile, created the Heroku app, set the git remote, and pushed the local changes to the Heroku app. Seeing my app logs, I saw this error: 2021-01-22T10:44:54.000000+00:00 app[api]: Build started by user hassanaziz0012@gmail.com 2021-01-22T10:45:32.301870+00:00 heroku[web.1]: State changed from crashed to starting 2021-01-22T10:45:32.103906+00:00 app[api]: Release v21 created by user hassanaziz0012@gmail.com 2021-01-22T10:45:32.103906+00:00 app[api]: Deploy af87d85b by user hassanaziz0012@gmail.com 2021-01-22T10:45:36.986469+00:00 heroku[web.1]: Starting process with command `gunicorn lessonswithanative.wsgi` 2021-01-22T10:45:39.934947+00:00 heroku[web.1]: State changed from starting to up 2021-01-22T10:45:39.576978+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-01-22T10:45:39.577706+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Listening at: http://0.0.0.0:48170 (4) 2021-01-22T10:45:39.577813+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [4] [INFO] Using worker: sync 2021-01-22T10:45:39.584050+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [10] [INFO] Booting worker with pid: 10 2021-01-22T10:45:39.595125+00:00 app[web.1]: [2021-01-22 10:45:39 +0000] [11] [INFO] Booting worker with pid: 11 2021-01-22T10:45:40.972008+00:00 app[web.1]: [2021-01-22 10:45:40 +0000] [10] [ERROR] Exception in worker process 2021-01-22T10:45:40.972058+00:00 app[web.1]: Traceback (most recent call last): 2021-01-22T10:45:40.972060+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-01-22T10:45:40.972061+00:00 app[web.1]: worker.init_process() 2021-01-22T10:45:40.972061+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-01-22T10:45:40.972061+00:00 app[web.1]: self.load_wsgi() 2021-01-22T10:45:40.972062+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-01-22T10:45:40.972062+00:00 app[web.1]: self.wsgi … -
Can't open zip file created with python and Django
I create a set of pdf files and whant to add them to zip archive. Everything seems fine, but when I download my zip file It can't be open. So I create pdf with create_pdf function ef create_pdf(child): buffer = io.BytesIO() canvas = Canvas(buffer, pagesize=A4) p = staticfiles_storage.path('TNR.ttf') pdfmetrics.registerFont(TTFont('TNR', p)) canvas.setFont('TNR', 14) t = canvas.beginText(-1 * cm, 29.7 * cm - 1 * cm) t.textLines(create_text(child), trim=0) canvas.drawText(t) canvas.save() pdf = buffer.getvalue() return pdf Then I create zip file and pack it to response def create_zip(pdfs): mem_zip = io.BytesIO() i = 0 with zipfile.ZipFile(mem_zip, mode='w', compression=zipfile.ZIP_DEFLATED)\ as zf: for f in pdfs: i += 1 zf.writestr(f'{str(i)}.pdf', f) return mem_zip.getvalue() def get_files(request, children): pdfs = [] for child in children: pdfs.append(create_pdf(child)) zip = create_zip(pdfs) response = FileResponse(zip, content_type='application/zip', filename='zayavleniya.zip') response['Content-Disposition'] = 'attachment; filename=files.zip' return response Please help to find where I am wrong. -
Django Template Syntax error: Could not pass the remainder
I am working on a Django project and I am relatively new to the Django framework. After running the application using python3 manage.py runserver I am getting an error like django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['role']' from 'session['role']'. This is the particular html file to which the error is pointing. base.html {% block body %} <body> <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#"><img src="{% static 'img/logo.png' %} "id="icon" alt="User Icon" width="30" > {{ application.name }}</a> {% if session['role'] == "manager" %} # rest of code How do I get this done with? please help -
how to copy elements instead of moving Jquery Nestable List
I am developing app in django. I am trying to create nested list using jQuery Nestable. I would like to have two list. One, where I create my structure and second, where I store elements to use. But I would like to use one element more than ones. Is it possible to copy items from a list instead of moving them? A working demo by the author: here. An example of what I want to do: And one more question, is it possible to move items only from list A to list B (from B to A is disabled)? If not in this version then maybe in the other version of this plugin link? Best regards! -
Customize the style of a django.forms.BooleanField() containing a django.forms.CheckboxInput()
I included a contact-form on my webpage which looks like so: I would like to style the "CC myself" - checkbox in the following ways: The text "CC myself" is centered vertically within its box. The checkbox should be right next to the text "CC myself". The "forward"-symbol should be between text and checkbox, but directly next to the text and with more horizontal distance to the checkbox (on its right-hand side). This is how I defined the contact form in forms.py: from django import forms class ContactForm(forms.Form): # * Sender from_email = forms.EmailField( required=True, label='Your Email', widget=forms.TextInput(attrs={'placeholder': 'jsmith@example.com'})) # * Optional CC to sender cc_myself = forms.BooleanField( required=False, label='CC myself', widget=forms.CheckboxInput(attrs={'class': 'fa fa-share'})) # * Subject subject = forms.CharField(required=True, label='Subject') # * Message message = forms.CharField( widget=forms.Textarea(attrs={'placeholder': 'Dear Andreas ..'}), required=True, label='Message') In the home.html template then, the form is displayed like so: <form style="margin-left: auto;margin-right: 0;" method="post" action="{% url 'contact' %}"> {% csrf_token %} <!-- * Neat autoformatting of the django-form via "pip install django-widget-tweaks" Docs: https://simpleisbetterthancomplex.com/2015/12/04/package-of-the-week-django-widget-tweaks.html --> {% for hidden in sendemail_form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in sendemail_form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field|add_class:'form-control' }} {% … -
Random password generation when admin creates employees in admin site
I have inherited three users from the User model, namely the Admin, Employee, and Relative. models.py config = RawConfigParser() config.read('config.cfg') class UserManager( BaseUserManager): def _create_user(self, PAN_ID, password=None, **extra_fields): """ Creates and saves a User with the given email, date of birth and password. """ if not PAN_ID: raise ValueError('Users must have a PAN_ID') extra_fields['email'] = self.normalize_email(extra_fields["email"]) user = self.model(PAN_ID=PAN_ID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(PAN_ID, password, **extra_fields) def create_superuser(self, PAN_ID, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(PAN_ID, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): PAN_ID = models.CharField(max_length=100, unique=True) password = models.CharField(_('password'), max_length=128, null=False, blank=True) email = models.EmailField(max_length=100, unique=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) name = models.CharField( max_length=60, blank=True) address = models.CharField(max_length=70, null=True, blank=True) holding = models.CharField(max_length=100, null=True, blank=True) is_staff = models.BooleanField( _('staff status'), default=True, help_text=_( 'Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) objects = UserManager() USERNAME_FIELD = "PAN_ID" EMAIL_FIELD = "email" REQUIRED_FIELDS = ['email', … -
How to disable default Django Template/Skin
is there a way to disable Django View for users? I want to get all the data per API as Json, not from View. I tried to delete Template in Django Setting, it was okay... But after that, I couldn't access to Admin Panel. To be more clear, I mean these Templates: Thanks -
NOT NULL constraint failed: auth_user.password
Django inbuild authentication using time I'm faced this error ! ! NOT NULL constraint failed: auth_user.password Views.py from django.shortcuts import render from django.views.generic import TemplateView, FormView from .forms import UserRegistrationForm from django.contrib.auth.models import User class RegisterView(FormView): template_name = "registration/register.html" form_class = UserRegistrationForm success_url = '/' def form_valid(slef, form): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = User.objects.create(username=username, email=email, password=password) user.save() return super().form_valid(form) Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm, forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')```