Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
import datetime - Clarification
'''' from datetime import datetime now = datetime.now().time() print(now) o/p: 21:44:22.612870 '''' But, when i am trying: '''' import datetime now = datetime.now().time() print(now) '''' it give following error: Traceback (most recent call last): File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in now = datetime.now().time() # time object AttributeError: module 'datetime' has no attribute 'now' any one explain what is difference between both? -
Creating a Django form that allows "extra fields" on a "through" table to be edited
I have User, SocialNetwork, and UserSocialNetwork models in a Django 3.0.3 project. class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) middle_name = models.CharField(blank=True, max_length=255, unique=False) bio = models.TextField(blank=True, default='') … socialnetworks = models.ManyToManyField(SocialNetwork, through='UserSocialNetwork') updated_at = models.DateTimeField(auto_now=True) class SocialNetwork(models.Model): name = models.CharField(blank=False, max_length=255) description = models.TextField(blank=True, default='') url = models.URLField(blank=False, max_length=255) format = models.CharField(blank=False, max_length=8, choices=[('handle', 'handle'), ('url', 'url')]) base_url = models.URLField(blank=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __str__(self): return self.name class UserSocialNetwork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) socialnetwork = models.ForeignKey(SocialNetwork, on_delete=models.CASCADE) identifier = models.CharField(blank=False, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['socialnetwork', ] verbose_name = "User's Social Network" I'm using django-formtools to step through profile creation. One of the steps should be a page where the profile creator is presented with a list of SocialNetworks and given the opportunity to enter their identifier on those networks. I've been struggling with this. It was suggested I use formsets and I've got this class UserSocialNetworkForm(BaseModelForm): class Meta: model = UserSocialNetwork fields = [ 'socialnetwork', 'identifier', ] labels = { 'socialnetwork': _('Social Network'), } UserSocialNetworkFormSet = formset_factory(UserSocialNetworkForm, extra=SocialNetwork.objects.count()) which yields this but all I really want is one line per … -
How to get details of a nested object in a serializer in DRF
So I'm trying to create a serializer that would return a bunch of details of a 'Post' model in my project, but I want to get details of a nested object as well, the output of which I will show below: Post model: class Post(models.Model): # Base post attributes user = models.ForeignKey(UserOfApp, related_name="posts", on_delete=models.CASCADE) ... # Repost post attributes original_repost = models.ForeignKey( to="self", related_name="reposted_post", null=True, blank=True, on_delete=models.CASCADE, ) # Quote post attributes is_quote_post = models.BooleanField(default=False) quoted_post = models.ForeignKey( to="self", null=True, blank=True, on_delete=models.CASCADE ) ... My serializer, using 'depth': class HomeSerializer(serializers.ModelSerializer): id_str = serializers.ReadOnlyField() ... quoted_post_id_str = serializers.ReadOnlyField() class Meta: model = Post depth = 2 fields = "__all__" This yields me an output like, the problem being it returns all sensitive data from my user model as well, like 'password' etc: { "id": 16, ... "is_quote_post": false, "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, "username": "manas", "first_name": "Manas", "last_name": "Acharekar", "email": "manas.acharekar98@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2020-03-01T18:42:11Z", "dob": "1998-11-11", "gender": "M", "bio": "i own this place", "location": "", "website": "", "verified": true, "followers": [], "friends": [], "groups": [], "user_permissions": [] }, "original_repost": { "id": 1, ... "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, … -
How to implement Django Chained Drop Down using clever select
I'm using doing a small django project and using django-clever-select to created chained drop down select. I followed the exact instruction given in their installation useage guide at https://pypi.org/project/django-clever-selects/. But once i run the app in pycharm the dropdown doesn't show any data to be selected. models.py <pre> class Category(models.Model): mname = models.CharField(max_length=100, blank=False,unique=True) mdescription = models.CharField(max_length=255, blank=True) def __str__(self): return self.mname class Meta: ordering = ('mname',) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True, blank=True) scname = models.CharField (max_length=100, blank=False,unique=True) scdecription = models.CharField(max_length=255, blank=True) def __str__(self): return self.scname class Meta: ordering = ('scname',) class Deals(models.Model): vendor_deal = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null= True) description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateField(auto_now_add=True) expire_date = models.DateField(null=False) current_date = models.DateField(auto_now_add=True) def __str__(self): return self.description class Meta: ordering = ('description',) </pre> template file for the form ` {% extends 'base.html' %} {% load static %} {% block content %} </br></br></br></br> <div class="content"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-6"> <form id="post_from" method="post"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> </div> <div class="col-md-2"></div> </div> <div class="row"> </div> <div class="row"> </div> </div> {% endblock %} </pre></code> ` form.py file `<pre> … -
Create a subclass not to repeat matching fields
I created two class models in Django. Is there a way not to repeat the same matching fields storing them in a different class or variable? This is what i got: class Post(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title class Post2(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post2, self).save(*args, **kwargs) def __str__(self): return self.title -
prefetch_related on existing django instance
I have a prefetch_related defined on my ObjectManager - is it possible to get the prefetch_related functionality on an instance that wasn't retrieved by this manager? This would apply to something like a newly-created instance. class Foo(models.Model): objects = FooManager() class FooManager(models.Manager): return (...).prefetch_related("bars") fooA = Foo.objects.get(...).bars # prefetched + cached for later fooB = Foo.objects.create() fooB.bars # not prefetched fooB.bars # queries each time because not included in prefetch cache -
GeoDjango IntegrityError when following the Tutorial
I am precisely following the GeoDjango Tutorial: https://docs.djangoproject.com/en/3.0/ref/contrib/gis/tutorial/ and decided to use SpatiaLite instead of PostGIS as my db-Backend. In order to do that, i edited my projects settings.py-file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Following the Tutorial worked up to the Part "LayerMapping". When running $ python manage.py shell >>> from world import load >>> load.run() i get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: world_worldborder.fips What can I do to fix this Error? Thanks in Advance! -
ImportError: cannot import name 'forms' from 'basicapp'
form.py: from django import forms class FormName(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) views.py: from django.shortcuts import render from .forms import forms def index(request): return render(request,'basicapp/index.html') def form_page(request): Form = forms.FormName() return render(request,'basicapp/form_page.html',{'form':Form}) I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp' -
Django form with only one select field is passing the input tag value instead of the selected one
Django beginner here. I have a form which asks the user to select an answer to be set as the correct one. Now my form is the following: class SelectCorrectAnswer(forms.Form): def __init__(self, choices, *args, **kwargs): super(SelectCorrectAnswer, self).__init__(*args, **kwargs) self.fields['correct_answer'].choices = choices correct_answer = forms.ChoiceField(choices=(), required=True) As you can see the choices are added dynamically, in fact, they are correctly displayed in the template, which is the following: <!--Select the correct answer--> <form action="{% url 'create-assessment' %}" method="post"> {% csrf_token %} {{ select_correct_form.as_p }} <input type="submit" value="Select" name="select-correct-answer" > </form> And retrieved in the view as shown below: # Initialize select correct answer form. problem_answers = Answer.objects.filter(creator=current_user, question=problem_to_be_answered) choices = [] for answer in problem_answers: choices.append((answer.answer, answer.answer),) select_correct_form = SelectCorrectAnswer(choices) print(choices) The view tries to handle the POST request as follows: # Set answer as correct. if request.method == 'POST' and 'select-correct-answer' in request.POST: print(f'CODE REACHED HERE {request.POST}') select_correct_form = SelectCorrectAnswer(request.POST) if select_correct_form.is_valid(): selected_answer = select_correct_form.cleaned_data['correct_answer'] correct_answer = Answer.objetcs.get(id=selected_answer.id) correct_answer.is_correct_answer = True correct_answer.save() print(f'THIS IS THE CORRECT ANSWER {correct_answer}') From the print statements, I can see that the correct request is being processed but the value I select is not passed. In fact, as you can see from the printed output, … -
Django blocked the raw socket connection
I build a socket server on the python and it worked. And when i call it as thread from django server the connection is refuse. This is my server code on thread: def add_device_to(self): socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_server.bind((host, 5555)) socket_server.listen() while True: socket_c , address = socket_server.accept() print("ok") self.register(socket_c, address) This is my client code: socket_client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_client1.connect((host,5555)) The error on the client side is: socket_client2.connect((host, 5554)) ConnectionRefusedError: [Errno 111] Connection refused And when i tried that on windows it work fine. -
Use Django Queryset filter API on in-memory list of Model instances?
Is it possible to re-use the Django Queryset API when I've already retrieved a list of objects? i.e. foos = list(Foo.objects.filter(color="red")) large_foos = foos.filter(size="large") small_foos = foos.filter(size="small") I can of course iterate through my foos list, but it'd look cleaner to reuse the API. Use case is something like the color column being indexed but the result set small, and size isn't indexed (or size has high cardinality). -
render data with rest framework based on user input (Django)
I am struggling to modify this view so that a chart is generated based on user input. The underlying isssue is that I cannot find a way to make this with Django rest framework. Here is what I have been able to do so far: view.py: class forecast(APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_res', None) if query and request.method == 'GET': reference = Item.objects.filter(reference = query) forecast1 = Item.objects.filter(reference = query).values('demand_30_jours') forecast2 = Item.objects.filter(reference=query).values('Lt2') forecast3 = Item.objects.filter(reference=query).values('Lt3') data = {'reference': reference, 'forecastdata':[forecast1, forecast2, forecast3]} return Response(data) urls.py urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('items.html', ItemPage.as_view()), path('charts',TemplateView.as_view()), path('admin/', admin.site.urls), path('api/chart/data',ChartData.as_view()), path('api/chart/forecast',forecast.as_view()) items.html <form id="searchform" method="get" action="" accept-charset="utf-8"> Search <input id="searchbox" name="search_res" type="text" placeholder="Search"> <input type="submit" value="OK"> </form> <div class="col-lg-6"> <div class="card mb-4"> <div class="card-header"><i class="fas fa-chart-bar mr-1"></i>90 DAYS FORWARD FORECAST</div> <div class="card-body"><canvas id="myChart" width="150" height="116"></canvas></div> <div class="card-footer small text-muted">References</div> </div> </div> <script> $(document).ready(function() { var endpoint = '/api/chart/forecast' var forecastdata= [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { labels: reference, … -
How to make automatic anser to mattermost channel
I have a problem with automatic generator of response via mattermost. To simplify a question- I have some dedicated channel on mattermost and if a message send by me is correct I want to have automatic answer "OK" + my_message. Right now I am checking a message and if is good making: result = {"channel" = "@username", "text" = "OK" + my_message} return HttpResponse(result, status=200) but it doesn't work. Ideas? -
Django not working after switching from sqllite3 to postgresql
I'm getting the following error after making switch of database when trying to make migrations: django.db.utils.OperationalError No explanation at all following it. I change the base sqlite3 code in settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } My models.py: from django.db import models # Create your models here. class Company(models.Model): KIND = ( (0, "Corporate"), (1, "Start Up"), ) name = models.CharField(verbose_name="full company", max_length=50) address = models.CharField(max_length=100) kind = models.IntegerField(default=0) class Job(models.Model): name = models.CharField(max_length=50) salary = models.DecimalField(max_digits=8, decimal_places=2, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Any idea what is going on? I did makemigrations when using sqlite3, but I already deleted the database. Full traceback error here: Traceback (most recent call last): File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line … -
how can i pass my context variables to javascript in Django?
views.py context = {'select_company': select_company,} return render(request, 'invest/chart.html', context) html <option value="{{o}}">{{select_company}}</option>----------{{select_company}} can show its value <script> company = {{select_company|safe}}; ---------------js tell me undefined </script> django 2.2 python 3.7 how to solve the weird problem -
TypeError at /stock/delete sequence item 0: expected str instance, int found
I'm deleting multiple objects using checkboxes but I'm facing this error TypeError at /stock/delete sequence item 0: expected str instance, int found views.py class DeleteProducts(SuccessMessageMixin, View): success_url = reverse_lazy('stock:stock') success_message = "Products {} are deleted successfully." def post(self, request, *args, **kwargs): products = self.request.POST.getlist('product') products_deleted = Product.objects.filter(pk__in=products).delete() msg = self.success_message.format(', '.join(products_deleted)) messages.success(self.request, msg, extra_tags='alert-danger') return HttpResponseRedirect(self.success_url) urls.py path('delete', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'), -
Django & MongoDB has issue with default ID autoField on django models
I have Django 2 that the Rest Framework and Djongo is used in it. The Account can be created but when I try to see the list of created Accounts to updated or do any operation on them I can't actually I can't retrieve the list of Accounts and gives me error on ID field. I think this is an issue with MongoDB, so how I can fix this issue? Here is the error that I have that followed by my Account related codes MigrationError at /Accounts/account/ id Request Method: GET Request URL: http://localhost:8000/Accounts/account/ Django Version: 2.2.7 Exception Type: MigrationError Exception Value: id Exception Location: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\sql2mongo\query.py in _align_results, line 287 Python Executable: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.0 Python Path: ['E:\Project\accountingPy', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32', 'C:\Users\PC 001\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\lib\site-packages'] Server time: Mon, 6 Apr 2020 15:00:38 +0000 The record that stored in database // 1 { "_id": ObjectId("5e8b3a0c10fc9f40cdca44be"), "label": "Mapping", "owner": "Nasser", "balance_currency": "USD", "balance": "23.00", "desc": "This the Cash account that manage by cash payments", "status": true, "created_at": ISODate("2020-04-06T14:17:48.838Z"), "updated_at": ISODate("2020-04-06T14:17:48.838Z") } Account model class Account(models.Model): class Meta: db_table = 'account' def __str__(self): return self.label label = models.CharField(max_length=20,unique=True) owner = models.CharField(max_length=20) balance = … -
How to upgrade python version inside a virtual environment (in windows)
How to make my virtual environment use same version of python installed in my system. (see picture) -
How to create auto generate code in django
I have a company, department, and item list. in item list company and department are foreign keys. so when I add an item into the item list, item will generate a code for itself automatically like from company name's 3 alphabets, department name's 3 alphabets and 4 or 5 digits no. starting from 0001 and auto-increment. each company item will start from 0001. As an example: If a company is "ABCDE" and the department is "Finance" the code will be auto-generated like ABC-Fin-0001. is there any way to get these things done? Model_Class class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics'), ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) My_view def item_entry(request): title = 'Add Item' form = ItemForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/item_list') context = { "title": title, "form":form } return render(request,'item_entry.html', context) Form_View class ItemForm(forms.ModelForm): class Meta: model = Item fields = ("item_name","item_type", "code","company","department",) Template_view <table> <tr> <th>#</th> <th>Item Name</th> <th>Item Type</th> <th>Code</th> <th>Company</th> <th>Department</th> </tr> {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td><a href="{% … -
Django: How can i get multiple model class fields in one model with our without foregin key
Models.py I have a model like these. I'm trying to access 2 fields from all top 4 models into last model class(UserTimeZone) but im getting only one field from each models,anyone if anyone who can understand these problem,it will be a great help for me. class ControllerParameters(models.Model): ControllerName = models.CharField(max_length=50,null=True) ControllerID = models.IntegerField(null=True) . #multiple fields here.. def __str__(self): return self.ControllerName class DoorInfo(models.Model): DoorName = models.CharField(max_length=50, null=True) DoorSensor = models.CharField(max_length=10, choices=SensorChoice,default=True) . #multiple fields here.. In DoorInfo Table i have fixed 4 door records like,door1,door2,door3,door4 class Enrollment(models.Model): userid = models.CharField(max_length=15,blank=True,null=True) username =models.CharField(max_length=15,blank=True,null=True) . #multiple fields here.. class TimeZone(models.Model): timezoneid = models.CharField(max_length=50,choices=Timezone_Choices,blank=True, null=True) timezonename = models.CharField(max_length=100,db_column='TimeZone Name', blank=True, null=True) . #multiple fields here.. class UserTimezone(models.Model): employeeid = models.CharField(max_length=20, blank=True, null=True) employeename = models.ForeignKey(Enrollment, related_name="enrollment", on_delete=models.SET_NULL,null=True) controllerid = models.CharField(max_length=20, blank=True, null=True) controllername = models.ForeignKey(ControllerParameters, related_name="controlparameter", on_delete=models.SET_NULL,null=True) doornumber = models.IntegerField(blank=True, null=True) doorname = models.ForeignKey(DoorInfo,related_name="doorname", on_delete=models.SET_NULL,null=True) timezoneid = models.IntegerField(blank=True, null=True) timezonename = models.ForeignKey(TimeZone, related_name="timezone", on_delete=models.SET_NULL,null=True) views.py this code might be totally wrong as per my requirement so not understanding how can i do queryset, def usertimezone(request): timez = TimeZone.objects.all() text = DoorInfo.objects.all() enroll = Enrollment.objects.all() usertext = UserTimezone.objects.all() if request.method == "POST": userform = UserTimezoneForm(request.POST) if userform.is_valid(): userform.save() userform =UserTimezoneForm() context = {'userform':userform,'usertext':usertext, 'enroll':enroll,'text':text,'timez':timez, … -
How to redirect from one page to another in Django
I have created sign up Page and I want to redirect to login if the user is already registered. I am confused about how to do it in views I am also attaching views.py Thanks. def register(request): if request.method == 'POST': first_name = request.POST['Firstname'] last_name = request.POST['Lastname'] username = request.POST['Username'] password1 = request.POST['password'] password2 = request.POST['password1'] email = request.POST['email'] user = User.objects.create_user(username=username, password= password1, first_name=first_name, last_name=last_name, email=email) user.save() print('user Created') return redirect('/') else: return render(request, 'register.html') -
How to define django-imagekit ImageSpecFields in parent/mixin class?
I'm using django-imagekit to provide thumbnail versions of uploaded images on my Django models. I would like to define various thumbnail ImageSpecFields in a mixin that my models can then inherit. However, each model currently has a different name for the ImageField on which its ImageSpecFields would be based. I've tried this: from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFit class ThumbnailModelMixin(models.Model): IMAGE_SPEC_SOURCE_FIELD = None list_thumbnail = ImageSpecField( processors=[ResizeToFit((80, 160)], source=IMAGE_SPEC_SOURCE_FIELD, format="JPEG", options={"quality": 80} ) class Meta: abstract = True class Book(ThumbnailModelMixin): IMAGE_SPEC_SOURCE_FIELD = "cover" cover = models.ImageField(upload_to="books/") class Event(ThumbnailModelMixin): IMAGE_SPEC_SOURCE_FIELD = "ticket" ticket = models.ImageField(upload_to="events/") But, as expected, this fails with: Exception: ThumbnailModelMixin does not define any ImageFields, so your list_thumbnail ImageSpecField has no image to act on. Is there a way to get inheritance like this to work? There are at least two other solutions: Don't use a mixin/parent, and include the ImageSpecFields on each child class - a lot of duplicate code. Change the Book.cover and Event.ticket fields to have the same name, like image and use "image" for the ImageSpecField source parameter. The latter sounds best, but I'm still curious as to whether there's a way to get the inheritance working? -
How to display chosen poll option alongside overall results in Django
I'm new to Python & Django and I have been following the App tutorial that the Django Documentation has. I have made the routes and everything is working, the issue I am having is that I want to be able to show what poll option the user chose on the result page. (The result page currently only shows the overall result of the poll, which I do want to keep but I also want to display the selected choice in addition to that.) The user does not have to be logged in so I haven't created a foreign key to tie a user to their vote. I figured out a way to add the selected choice primary key to the URL but as i'm using class based views i'm not sure how to get that value in the result view. urls.py ... app_name = "polls" urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/<int:choice_id>', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] ... views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) ... #removed the test part else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id, selected_choice.id))) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' -
Upload Image Django and AJAX
I'm trying to upload an image using django and ajax, but it doesn’t load in the database. This appears: C:/fakepath/img.png. As far as I understand that the problem is in Ajax, it saves all the rest of the form data well, but it doesn’t work with photography, how to solve this problem? FORM: <div class="table-responsive"> <form id="addProduct" enctype="multipart/form-data" action=""> <div class="form-group"> <input class="form-control" type="text" name="sku" placeholder="sku" required> </div> <div class="form-group"> <input class="form-control" type="text" name="product_name" placeholder="name" required> </div> <div class="form-group"> <input class="form-control" type="number" name="price" placeholder="price" required> </div> <div class="form-group"> <input class="form-control" type="number" name="qty" placeholder="qty" required> </div> <div class="form-group"> <input class="form-control" type="file" name="picture" placeholder="PIC" required> </div> <button class="btn btn-primary form-control" type="submit">Save</button> </form> </div> JS: $("form#addProduct").submit(function() { var skuInput = $('input[name="sku"]').val().trim(); var nameInput = $('input[name="product_name"]').val().trim(); var priceInput = $('input[name="price"]').val().trim(); var qtyInput = $('input[name="qty"]').val().trim(); var pictureInput = $('input[name="picture"]').on('change', prepareUpload); function prepareUpload(event) { files = event.target.files; } if (skuInput && nameInput && priceInput && qtyInput && pictureInput) { // Create Ajax Call $.ajax({ url: '{% url "ajax_addown_offer" instance.id %}', data: { 'sku': skuInput, 'product_name': nameInput, 'price': priceInput, 'qty': qtyInput, 'picture': pictureInput }, dataType: 'json', success: function (data) { $('#order_item_container').html(data.result) } }); } else { alert("All fields must have a valid value."); } $('form#addProduct').trigger("reset"); return false; … -
trouble being spyed on [closed]
Ok Im brand new to all this and dont know the FIRST THING about coding, however EEXTREAMLY INTRIGUED since i believe that im being spyed on or hacked by my soon to be ex. It started 6 years ago and has BAFFELED ME TO NO END!!! Long story short,,, I finally figured out its GOTT BE CODING BEING SOMEHOW WRITTEN INTO ALREADY EXISTING PROGRAMS LIKE MICROSOFT, AND EVEN THE INTERNET ITSELF KEEPING ME FROM FINDING TRACES OF HIS CHEATING AND KEEPING AN EYE ON ME TO MAKE SURE I DONT CATCH HIM. My question is--AM I CCRAZY? OR IS THIS PISSIBLE? IF SO...HOIW DO I RECOGNIZE THE CHANGES IN WHAT IS SUPPOSED TO BE IN A ROOT FILE ANDBWHAT HAS BEEN CREATED TO DETER, SPY, OR FLAT OUT SCREW WITH MY HEAD?