Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: '<' not supported between instances of 'User' and 'User'
When I do: qs1 = User.objects.filter(first_name__icontains=search).filter(is_superuser=False) qs2 = User.objects.filter(last_name__icontains=search).filter(is_superuser=False) users = sorted(set(chain(qs1, qs2))) I get this error: '<' not supported between instances of 'User' and 'User' -
redirect to a different model in django
in my project after updating and submitting the File, I want to redirect to associated object in Content how I could do it? If I want to use def get_absolute_url in File model, how I can use it to redirect to 'content.detail' which is defined in urls.py I tried this: def get_absolute_url(self): return reverse('content.detail', args=[str(self.id)]) and it returns the content object that has same id as File, for example if we have a File id=5 that is associated to content by id=74, by get_absolute_url function, it returns a content id=5, however I want it to return content id=74. models.py class File(models.Model): history = AuditlogHistoryField() extension = models.CharField(max_length=20, default='html') base64encoded = models.BooleanField(default=False) compressed = models.BooleanField(default=False) data = models.TextField() class Content(models.Model): history = AuditlogHistoryField() name = models.CharField(max_length=120, unique=True) sorry_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='first_file') busy_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='second_file') emergency_content_file = models.ForeignKey( File, on_delete=models.CASCADE, null=False, related_name='last_file') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) view.py class FilesUpdateView(generic.UpdateView): model = File fields = ['data'] file_form.html {% block content %} <form method="POST" class="user"> <div class="row"> <div class="col-lg-8"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{% trans 'Details' %}</h6> </div> <div class="card-body"> {% csrf_token %} {% for field in form.visible_fields %} … -
why am I getting "TypeError" while creating super user in Django?
I am woking on a project where I need to have Django custom model. Based on the documents available I came up with the below code base: from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ class AccountManager(BaseUserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', 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(email, password, **extra_fields) def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) if not email: raise ValueError(_('Enter the email before proceeding')) email = self.normalize_email(email) user = self.model(email=email, password=password, **extra_fields) user.set_password(password) user.save() return user class NewEmployeeProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) employee_code = models.IntegerField() contact = models.CharField(max_length=10) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'contact'] def __str__(self): return str(self.email) I migrated the model without any hiccups. However, when I am trying to create super user, I am getting below error: 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 "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Show only the user profile of the logged in user to the logged in user
I hope somebody can help me with this. When a user logs in they se their user profile page, but if the user guesses another users profile URL they can view other peoples profiles I have tryed to use the get_object_or_404 method to restrict the access but cant tweak for user with genreric detail view. Is it possible to user get_object or do you recommend another approach? My user Class class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "pk" slug_url_kwarg = "pk" Get object or 404 method def user_detail(request, user_id): user = get_object_or_404(User, user_id=user_id, is_active=True) return render (request, 'users/user_detail_2.html',{'users':users}) -
Django bulk_create with get_or_create() on m2m field
I want to create a lot of Product objects with bulk_create. The problem is one of the fields which is m2m type. I need to extract ids from comma separated string. I do it using get_or_create() but bulk_create does not work then. I know I should think about using through but I do not really know how, especially together with get_or_create(). My code example: def create_objs(row_iter): objs = [dict( name=row['name'], type=row['type'], my_m2m_field=self.get_m2m_ids(row['m2m']), ) for index, row in row_iter] products = Product.objects.bulk_create( [Product(**params) for params in objs] ) return products def get_m2m_ids(data): m2m_ids = [] if data: for i in data.split(', '): m2m_ids.append(MyM2mModel.objects.get_or_create(title=i)[0].pk) return m2m_ids Structure example: name type m2m 'n1' 't1' 'm11, m12, m13' 'n2' 't2' 'm21' 'n3' 't3' 'm31, m32' (...) How am I going to do it the proper way? -
Sending sms in django for free
I have tried using "Twilio" but it only gives sending for one user. Can anyone tell me how can I send bulk SMS for free using Django? -
How to search for a name field contains utf8 characters in django REST?
I have 2 models Watch and Product. A Product can have multiple Watch. The code for 2 models like below class Product(models.Model): id = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Watch(models.Model): ACTIVE = 1 DEACTIVATE = 2 FINISH = 3 STATUS_CHOICES = [(ACTIVE, 'Active'), (DEACTIVATE, 'Deactivate'), (FINISH, 'Finish')] product = models.ForeignKey( Product, related_name='watches', on_delete=models.CASCADE, ) status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=ACTIVE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I'm implementing a searching feature to get the list of watches based on the name of the product. Currently, like so class WatchList(generics.ListCreateAPIView): serializer_class = WatchSerializer permission_classes = (IsAuthenticated,) name = 'watch-list' filter_fields = ('status', 'owner') search_fields = ('^product__name',) ordering_fields = ('-updated_at') ordering = ('-updated_at') But when I try to call the API and search with a string contains utf8 characters (the string is nồi chiên không dầu), I got nothing back. I try a search pattern with only n character. Then it works. So I think the problem is utf8 in my first search pattern. How do I solve that problem? -
Annotate JSONField on-the-fly and retrieve keys via values
I annotate a JSONField on-the-fly like this. Since this is not a field of a model I think the model is not relevant. This example should be valid for any queryset. >>> from django.db.models import F, Func, JSONField, Value >>> queryset = queryset.annotate( json=Func(Value("foo"), Value("bar"), function="jsonb_build_object", output_field=JSONField()) ) >>> queryset.first().json {'foo': 'bar'} Now, when I want to retrieve a value of the annotated JSONField by calling values, I receive an error: >>> queryset.values("json__foo") Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 841, in values clone = self._values(*fields, **expressions) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 836, in _values clone.query.set_values(fields) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 2174, in set_values self.add_fields(field_names, True) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1863, in add_fields join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1565, in setup_joins path, final_field, targets, rest = self.names_to_path( File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'json' into field. Choices are: <other fields> Annotating a field by retrieving it from the previously annotated JSONField also does not work: >>> queryset.annotate(foo=F("json__foo")) Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1116, in annotate clone.query.add_annotation(annotation, alias, is_summary=False) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1018, in … -
Cropper.js giving an error: Uncaught TypeError: $image.cropper is not a function
I've been following this tutorial to the dot: pyplane - how to crop images in Django with Javascript But whenever I try it out, I get the error: This is the code for the webpage: (I put the js in the same file to help with debugging) {% extends 'base.html' %} {% load static %} {% block styles %} <script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css"> {% endblock %} {% block content %} <div class="text-center" style="padding-top: 76px"> <h1 >Profile picture</h1> <div id="alert-box"></div> <div id="image-box" class="mb-3"></div> <form action="" id="image-form"> {% csrf_token %} {{form.as_p}} </form> <button class="btn btn-primary mt-3" disabled id="confirm-btn">confirm</button> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script defer> const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const imageForm = document.getElementById('image-form') const confirmBtn = document.getElementById('confirm-btn') const input = document.getElementById('id_photo') const csrf = document.getElementsByName('csrfmiddlewaretoken') input.addEventListener('change', ()=>{ alertBox.innerHTML = "" confirmBtn.disabled = false; const img_data = input.files[0] const url = URL.createObjectURL(img_data) imageBox.innerHTML = `<img src="${url}" id="image" width="500px">` var $image = $('#image') console.log($image) $image.cropper({ aspectRatio: 16 / 9, crop: function(event) { console.log(event.detail.x); console.log(event.detail.y); console.log(event.detail.width); console.log(event.detail.height); console.log(event.detail.rotate); console.log(event.detail.scaleX); console.log(event.detail.scaleY); } }); var cropper = $image.data('cropper'); confirmBtn.addEventListener('click', ()=>{ cropper.getCroppedCanvas().toBlob((blob) => { console.log('confirmed') const fd = new FormData(); fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('file', blob, 'my-image.png'); $.ajax({ type:'POST', url: imageForm.action, enctype: 'multipart/form-data', data: fd, success: function(response){ … -
How to print the hardware information of the client PC on the web?
I want to create a site that shows the specifications of the client pc without complicated installation. -
I'm Using Tradezero.co Frontend design end
https://i.stack.imgur.com/m3w0w.png hey, I'm using Tradezero.co Website's front-end design, How Can i Remove the 24/7 Live Chat Option In My Website Please Help -
Update creation and update time pragmatically vs via database trigger
I want to add creation and update timestamps to several models in my django app. And I wonder what way is the best practice? I found that it can be done with auto_now and auto_now_add (or preferably via custom save() method). I call this programmatic way. Another way that comes to mind is defining a trigger function and assigning it to multiple database tables on the level of database (postgresql). So what is the best practice of doing things like that? (This may include total price calculations and any other column info that is calculated using other column data). Triggers or code? Note: This might be an opinion-based question. If so, Let me know in the comment, I will delete the question after I hear one or two opinions of an experienced developer. -
Django Inline for admin panel in foreign relationship with admin.TabularInline
models.py class Parent (models.Model): id = ...... name = ... address = ... class Child (models.Model): id= ... parent = models.ForeignField(Parent) Here in this schema, is it possible to bring Parent form inside Child schema to make editable by admin.Tabularline ? I know it is possible to bring Child Schema into parents schema and make editable. But I am looking for vice versa. Is it possible? -
Django settings: DATABASE_URL is not working
I just created a test application in Heroku so that I can stay in the same Django project, but quickly switch back and forth between connecting to my production database and my testing app database. I created an environment variable on my laptop using export:TEST_DATABASE_URL="...", but even with this below code I am still connected to my production database when I run my Django project on localhost. Does anyone know how i can accomplish this? # ~~~ PROD SETTINGS ~~~ # DATABASE_URL = os.environ['DATABASE_URL'] # DEBUG = 'False' # ~~~ TEST SETTINGS ~~~ DATABASE_URL = os.environ['TEST_DATABASE_URL'] DEBUG = 'True' # tried commenting this code out so it doesn't use the local sqlite file # DATABASES = { # Use this to use local test DB # todo: prod doesn't havea access to django_session... # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } -
Django: Bad request when sending request using reactJS
I am using django-rest-framework at backend and I am trying to post following data from react frontend. handleSubmit() { fetch('http://127.0.0.1:8000/api/debt/create',{ method: 'POST', headers: { Authorization: `Bearer ${localStorage.getItem('id_token')}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ user: '1', customer: '9', debtKey: 'b1d9ef1b-45ad-4dc5-80cc-95f7994c0aae', createduserKey: '0245abb9-2837-4f37-ae02-9be1b88887ef', totalDebt: 789, receivedAmount: 115, description: 'Debt description', paymentDate: '01.01.2019' }), }).then(response => { console.log(response); return response.json() }).then(json => { //this.setState({ // user:json //}); }); console.log("Form Sumbmssion"); } But I am getting "BAD REQUEST" error. What I am missing? Thanks -
Django forms.MultipleChoiceField with CheckboxSelectMultiple and Bootstrap custom-control-input is reset when form.is_bound
I have a form field: Forms.py colors = forms.MultipleChoiceField( required=True, widget=forms.CheckboxSelectMultiple, choices= [(1,'blue'),(2,'red'),(3,'green')] ) I can easily render this field like this: Template.html {{ form.colors }} And get something that looks like this: So the html code looks like that: <ul id="id_colors"> <li><label for="id_colors_0"><input type="checkbox" name="colors" value="1" id="id_colors_0" checked=""> blue</label> </li> <li><label for="id_colors_1"><input type="checkbox" name="colors" value="2" id="id_colors_1" checked=""> red</label> </li> <li><label for="id_colors_2"><input type="checkbox" name="colors" value="3" id="id_colors_2"> green</label> </li> </ul> This is really simple ! And it's working fine. Now, let's say I want to render this differently, exactly like this: With bootstrap custom-control-input. Bootstrap documentation show this code to achieve this: <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck" name="example1"> <label class="custom-control-label" for="customCheck">Check this custom checkbox</label> </div> So, in my template I did something like that: Template.html <div class="custom-checkbox"> <ul id="id_colors"> {% for key, value in colors %} <li> <input type="checkbox" class="custom-control-input" value="{{key}}" name="colors" id="id_colors_{{ forloop.counter0 }}"> <label class="custom-control-label" for="id_colors_{{ forloop.counter0 }}">{{value}}</label> </li> {% endfor %} </ul> </div> (Where "colors" is just my list that I pass to the template thru the view) With that template, the field looks exactly like I want. When rendered, the html looks like this: <ul id="id_colors"> <li> <input type="checkbox" class="custom-control-input" value="1" name="colors" id="id_colors_0"> <label class="custom-control-label" … -
How to update an Input file (image) in vueJS and Django rest?
Good morning, I'm currently working to the edit page for a blog using VueJS and Django Rest Framework. When I try to upload a photo I receive an error "the sended datas are not a file" and I' not currently able to select the current image (the default image is Null). The questions are how to make a working changing photo form and how to start with the image already charged in the JSon file. Thanks for all answers. Right now I have not made the admin system. VueJS <template> <h1>ARTICOLO</h1> <form @submit="onSubmit"> <input type="text" name="title" placeholder="Titolo" v-model="form.title"> <input type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> <input type="text" name="category" v-model="form.category"> <input type="file" name="image" @change="EditImage" > <input type="text" name="author" v-model="form.author"> <input type="text" name="author" v-model="form.slug"> <textarea name="text" v-model="form.text"></textarea> <button type="submit" @click= "editPost">Edit</button> </form> </template> <script> import axios from 'axios'; import { getAPI } from '../api' export default { data () { return{ Postslug: this.$route.params.Postslug, form: { title:"", desc:"", text:"", category:"", date:"", author:"", image:"", slug:"", }, selectedFile: null } }, methods: { // Form method onSubmit(event){ event.preventDefault(); axios.put(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, this.form).then(response => { this.form.title = response.data.title this.form.desc = response.data.desc this.form.text = response.data.text this.form.image = response.data.image this.form.category = response.data.category this.form.author = response.data.author this.form.slug = response.data.slug alert('Ok') }) .catch(err => … -
Display Database entry as option in a Django Form
I am trying to create an inventory app and one reservation app. I am trying to take entries from the inventory model and one can reserve it with the help of reservation app. What I am trying to achieve : The reservation app should take the entry of serial number from the inventory app serial number. It should either with the help of a drop down , which will show only the entry of specific serial number, so that random serial number should not be entered. ( I tried the concept of foreign key and many to many but I was unable to achieve it on the html page UI , but I achieved it on admin panel) Can you suggest what changes will be required ? For now, I am creating a form like this : But it is very poor method, because form is not getting validated, I am redirecting user to other web page where there are serial numbers present. I am trying to see how can we make the serial numbers available there itself as a drop down so that user can select which serial number to select. I am trying to add the slot field … -
Data getting printed in Network Response and not in HTML table in Django
I have a UI with two tables , so the second table is populated based on selection of checkbox from first table , but currently only first table data gets populated in UI and second table only in Network Console . I am new to this django concept and i don really know why this is happening . Currently on UI am able to retrieve data for First Table and in Network console , both table data's So the above is network console and printed is second table values , but this values are not getting printed in UI / HTML template . So here is my code : <div class="preview"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>ServerName</th> </tr> </thead> <tbody> {% for datas in customerserver %} <tr> <td> <div class="form-check form-switch"> <form method="post">{% csrf_token %} <input class="form-check-input" name="Servers" value="{{datas.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault"> </form> </div> </td> <td>{{datas.ServerName}}</td> </tr> {% endfor %} </tbody> </table> <table id="exampleSecond" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th></th> <th>ServerName</th> <th>Component</th> <th>PID</th> <th>State</th> </tr> </thead> <tbody> {% for datasno in ResultofRetrieve %} <tr> <td> <div class="form-check form-switch"> <form method="post">{% csrf_token %} <input class="form-check-input services" name="Services1[]" value="{{serv.ServerName}}" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label services" for="flexSwitchCheckDefault"> … -
Use Python Django inbuilt auth username as foreign key for separate app tables and cascade
I am creating a new separate user information table in Django. I want to use the inbuilt auth model. For that I need to have Foreign Key relation with username column in auth_user table. I want to use the Django inbuilt auth management; use auth_user's 'username' char column as foreign key in my apps new tables. Then whenever a user is deleted from Django's auth module, I want to cascade the changes and delete all records in the other tables. I think the foreign key relation is denoted here as OneToOneField. How do I design this model and relationship? mysql> show tables; +----------------------------+ | Tables_in_MYAPP_sqldb | +----------------------------+ | auth_group | | auth_group_permissions | | auth_permission | | auth_user | | auth_user_groups | | auth_user_user_permissions | | django_admin_log | | django_content_type | | django_migrations | | django_session | +----------------------------+ 10 rows in set (0.00 sec) mysql> describe auth_user; +--------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | password | varchar(128) | NO | | NULL | | | last_login | datetime(6) | YES | | NULL | | | is_superuser | … -
How to get column from DRF modal in get method?
How can I get the column in get method and return after doing some operation in DRF ? My model class is : class MQTTFeed(models.Model): sensor = models.ForeignKey( 'core.SensorDevice', on_delete=models.SET_NULL, null=True ) feed = models.TextField() created_at = models.DateTimeField(auto_now_add=True) And my view class is : class MQTTFeedListAPIViewWithMinValue(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,) serializer_class = serializers.MQTTFeedSerializer filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter,) filter_class = filters.MQTTFeedFilter search_fields = ('feed',) #queryset = models.MQTTFeed.objects.all() I have implemented something like that but I am getting error in views.py: def get_queryset(self): return self.queryset def get_object(self): feed = self.kwargs['feed'] print(feed) return feed How can I get the feed values in list so that i can manipulate and return value. -
I have installed pipenv and set the path variable to C:\~~Scripts also however ..when I run "docker build ." I get error at step 6 as follows:
Step 6/7 : RUN pip install pipenv | pipenv install --system ---> Running in 85fbae58695b pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:97 ... sPreference = 'SilentlyContinue'; pip install pipenv | pipenv install ... CategoryInfo : ObjectNotFound: (pipenv:String) [], ParentContai nsErrorRecordException FullyQualifiedErrorId : CommandNotFoundException The command 'powershell -Command $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; pip install pipenv | pipenv install --system' returned a non-zero code: 1 -
Django django.db.utils.IntegrityError: NOT NULL constraint failed: new__users_profile.location
I have the following model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(default=None, max_length=5) def __str__(self): return f'{self.user.username} Profile' I was testing some things out and put null=True for location. Then I changed it to default=None. After that when I tried to run makemigrations followed by migrate. I got the following error Full Traceback Traceback (most recent call last): File "C:\Users\uddin\project\trade\manage.py", line 22, in <module> main() File "C:\Users\uddin\project\trade\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\uddin\Envs\web\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\uddin\Envs\web\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\uddin\Envs\web\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\uddin\Envs\web\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\uddin\Envs\web\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\uddin\Envs\web\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\uddin\Envs\web\lib\site-packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Users\uddin\Envs\web\lib\site-packages\django\db\backends\base\schema.py", line 571, in alter_field … -
Trying to work on a project, python mysql not working on m1 chip?
I am trying to run a django project on M1chip with python 3.8, I got below at one point and it has been a road blocker for me how to tackle it. I tried to search for the problem but still not clear about the cause of issue. I checked for different answers online but nothing seems helping. Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so Expected in: flat namespace in /usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/usr/local/Caskroom/miniforge/base/lib/python3.8/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Caskroom/miniforge/base/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in … -
How do I preview a pdf file before saving it in Django?
How do I preview a pdf file before saving it in Django? I am trying to preview a pdf file before the user uploads it using the "pip install preview-generator" Link: https://pypi.org/project/preview-generator/ However the pdf file isn't loading up properly. I am not really sure what is pdf_or_odt_to_preview_path as the documentation wasn't clear. As such, I tried to use JS and jquery to send information from the front end to views.py, and subsequently use the tag to hold the pdf file. First Attempt which didnt work as the file didnt show: views.py @login_required def preview(request): if request.method == 'POST': body = json.loads(request.body) embedPDF = body['PDF'] print(PDF) cache_path = '/tmp/preview_cache' pdf_or_odt_to_preview_path = f'{PDF}' manager = PreviewManager(cache_path, create_folder= True) path_to_preview_image = manager.get_jpeg_preview(pdf_or_odt_to_preview_path) return JsonResponse({'status':200}) javascript: $('#testing-nia').on('change', function () { const file = this.files[0] reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function() { PDF = this.result var request = new Request( "{% url 'preview' %}", {headers: {'X-CSRFToken': '{{csrf_token}}'}} ) fetch(request, { method: 'POST', mode: 'same-origin', body: JSON.stringify({'PDF' : PDF, }) }) .then(response => response.json()) .then(data => console.log('finished if false')) }) }) 2nd Attempt which rendered a header i dont want: javascript: else if (file.name.endsWith('pdf')) { reader = new FileReader(); reader.readAsDataURL(file); $(reader).on('load', function () { …