Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit a datetimefield by adding/substracting time through django-rest-framework?
I'm creating a small application where Users have their own time that counts down. An admin should be able to add or substract time from the users time. And i need an API endpoint for that. I have the models, the user model has a datetime field, i have the Viewsets to get the time, but i need some way for the admin endpoint to add time. With that question i have more than one problem: where do i write a method that takes the current time of the user, adds the sent and then saves it? in the view or in the model? how do i create a POST-endpoint that calls this method? what is the best format for the time addition? The user model looks like this: class TN(models.Model): name = models.CharField(max_length=100, unique=True) time = models.DateTimeField() def __str__(self): return self.name Serializer: class TNSerializer(serializers.ModelSerializer): class Meta: model = TN fields = ['id', 'name', 'time'] View for GET: class TNViewSet(viewsets.ReadOnlyModelViewSet): queryset = TN.objects.all() serializer_class = TNSerializer filter_backends = (NameFilter,) -
How to make materialize cards line up in django?
So I am creating a website with django and I'm using the materialize framework. I am using the cards to show Q&As, and the questions and answers are all of different lengths. I was wondering if there was a way to make them line up so that there are not gaps in the columns.Cards not lining up picture I did see this code, and I rearranged my html to match it (I did move the for loop to the right spot), then pasted the css at the bottom of the css file, but this caused the cards to display in one long column. Here is my code: <div class="row"> {% for q in faqs %} <div class="col s12 m6 l4 cards-container"> <div class="card blue-grey darken-2"> <div class="card-content white-text"> <span class="card-title">{{q.question}}</span> </div> <div class="card-action white-text"> <p><i>{{q.answer}}</i></p> </div> </div> </div> {% endfor %} </div> If anyone knows a way to fix this, I would appreciate it very much. -
How do you group the values of a column and find the maximum value of a group in Django?
Let's say I have a column named item_type which contains values such as jeans, trousers, t-shirts etc. How can I group the count of values of this column and find the maximum value out of the groups? I am running the below query get the groupings Item.objects.values('item_type').annotate(total = Count('item_type')).order_by('item_type') where Item is my model name. However, this returns the grouped lists as a dictionary of lists, but I need the maximum count out of these groupings. This is what is returned through my HTML template: {'item_type': 'jeans', 'total': 250} {'item_type': 'shirts', 'total': 350} {'item_type': 'track-pants', 'total': 502} {'item_type': 'trousers', 'total': 136} {'item_type': 'tshirts', 'total': 450} How do I retrieve just this: {'item_type': 'track-pants', 'total': 502} -
Save ImageField in UpdateView Django
I have an image field in profile model. I am not able to save the image from template. Tried saving image using django admin, it successfully saves the image and display the image in the update view. How do I save the image from frontend not from django admin? Models class Profile(models.Model): image = models.ImageField(upload_to='profile_images', null=True, blank=True) profile_email = models.CharField(max_length=30, null=True, blank=True) biography = models.CharField(max_length=700, null=True, blank=True) View class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.object.id,)) Template {% if object.image %} <a href=""><img style="border-radius:50%; text-align:center; margin-bottom: 20px; border: 2px solid #00a6eb;" class="center" src="{{ object.image.url }}"alt=""></a> {% endif %} <label style="display: inline-block" for="file-upload" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i> Upload Photo </label> <input id="file-upload" name="name" onchange="this.form.submit()" type="file"/> Urls urlpatterns = [ path('users/', include('users.urls', namespace='users')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
Automatically filled field in model
I have some model where are date field and CharField with choices New or Done, and I want to show some message for this model objects in my API views if 2 conditions are met, date is past and status is NEW, but I really don't know how I should reslove this, I was thinking that maybe is option to make some field in model that have choices and set suitable choice if conditions are fullfilled but I didn't find any informations if something like this is possible so maybe someone have idea how resolve this? -
Django form: reference fields from foreign key
I'm making a task tracker webapp and I have a database structure where each task has a title, a description, and some number of instances, that can each be marked incomplete/incomplete: class Task(models.Model): title = OneLineTextField() description = models.TextField(blank=True) class TaskInstance(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) is_complete = models.BooleanField() The task and the instances can be shared separately, although access to the instance should imply read access to the task. This is intended for classroom situations, where the teacher creates a task and assigns it to their students. class TaskPermission(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='permissions') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='task_permissions_granted') shared_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='task_permissions_granting') can_edit = models.BooleanField(default=False) class Meta: unique_together = 'task', 'user', 'shared_by', class TaskInstancePermission(models.Model): task_instance = models.ForeignKey(TaskInstance, on_delete=models.CASCADE, related_name='permissions') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='task_instance_permissions_granted') shared_by = models.ForeignKey(User, on_delete=models.PROTECT, null=True, related_name='task_instance_permissions_granting') can_edit = models.BooleanField(default=False) class Meta: unique_together = 'task_instance', 'user', 'shared_by', My question is how to create a form for TaskInstances with fields for its is_complete, as well as its Task's title and description. Would something like this work? Or would I need to implement my own save and clean methods? class TaskForm(ModelForm): class Meta: model = TaskInstance fields = ('is_complete', 'task__title', 'task__description') -
Count number of instances of a City object in a model syntax Django Python
I will briefly explain what I am trying to do. A user will sign up with email, first and last name, and then select a city (handled by the model called Waitlist). I am using django_cities_light for city selection. I want to define a queryset that counts the number of times a specific city has been selected and then output that number onto my template_name page. Ex) 3 users sign up, 2 people select London as their city, thus there are 2 instances of the London city object in my Waitlist model. I want to be able to do this easily for multiple cities. I want to then render this 2 out using {{ for London in waitlist.qs }} for example (I'm not sure of the syntax hence why I'm asking). I will show what I have done so far and if someone could explain to me how to define the queryset properly, I would appreciate it! views.py class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request, *args, **kwargs): london = Waitlist.objects.get(??) context = { 'london': london, } return render(request, self.template_name, context) models.py class Waitlist(models.Model): first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.CharField(max_length=40, null=True) city = models.ForeignKey(City, null=True, … -
(1054, "Unknown column 'user_id' in 'field list'")
I got an error when I want to add a user in the admin section. My models.py is from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) # user = models.ManyToManyField(User) description = models.CharField(max_length=100,default='') city = models.CharField(max_length=100,default='') website = models.URLField(default='') phone = models.IntegerField(default=0) def create_profile(sender,**kwargs): if kwargs['created']: user_profile=UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) My admin.py is from django.contrib import admin from learning.models import UserProfile # Register your models here. admin.site.register(UserProfile) How to get rid of this problem? -
How to correctly set Allow header for a HTTP_405_METHOD_NOT_ALLOWED status code in Django REST framework
I'm currently looking to disable certain methods for an API endpoint - as added security. I'm using the status code that DRF suggests to use, that is for my case, "HTTP_405_METHOD_NOT_ALLOWED" - however, it looks to me that although this is working, the headers still say that the method is in Allow. See screenshot below: As you can see, I am performing a GET request - but the Allow header is saying it's fine - even tho the status code is being applied correctly. Stripped back example code: class TokenValidateView(APIView): def get(self, request, format=None): return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, headers=?) I believe I would need to set something in the headers dictionary (I've added ? where I'm not quite sure what needs to be done) as one of the arguments in the Response() function, but I'm not sure if this is a bug in DRF itself? Surely when that status code is passed it should be set in the headers accordingly? N.B. I've also tried adding headers = { 'Allow': 'POST' } to the Response() argument, but that doesn't seem to work... -
Anyone can suggest how to send email with send_mail? It's not working
When user registers is_active is False by default. I want the user get email notification when the admin activates the user. But send_mail is not sending email. I have created a function in my views.py: def send_mail(request): if user.is_active == True: send_mail(request, subject='subject', message='message', from_email='hekevintran_test@webfaction.com', recipient_list=['recipient@yahoo.com'], fail_silently=False) Also I have written down these things in my settings.py: EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'ualmaz' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 25 EMAIL_USE_TLS = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'apps', 'emails') Here is my views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.core.mail import send_mail from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import CreateView, DetailView, ListView, UpdateView, DeleteView from .forms import UserCreationModelForm, UserUpdateForm, ProfileUpdateForm from .models import User, Post, Profile class UserRegistrationView(CreateView): form_class = UserCreationModelForm user = User success_url = reverse_lazy('login') template_name = 'users/registration.html' def send_mail(request): user = User if user.is_active == True: send_mail(request, subject='subject', message='message', from_email='hekevintran_test@webfaction.com', recipient_list=['recipient@yahoo.com'], fail_silently=False) Here is my User model in models.py: class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="Last name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) access_challenge = models.BooleanField(default=False) is_active = models.BooleanField(default=False) def __str__(self): … -
Django. How to make a search?
I want to make it so that, when selecting a region, only those cities that are included in this area are displayed, and when selecting a city, so that only those areas that belong to this city are displayed? It's main Model class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риелтор') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') district = models.ForeignKey(District, on_delete=models.CASCADE, verbose_name='Район') And others class Region(models.Model): name = models.CharField(max_length=100, verbose_name='Название области') def __str__(self): return self.name class Meta: verbose_name = 'Область' verbose_name_plural = 'Области' class City(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name='Область') name = models.CharField(max_length=100, verbose_name='Название города') def __str__(self): return self.name class Meta: verbose_name = 'Город' verbose_name_plural = 'Города' class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Город') name = models.CharField(max_length=100, verbose_name='Название района') def __str__(self): return self.name class Meta: verbose_name = 'Район' verbose_name_plural = 'Районы' Template <div class="form-row"> <div class="col-md-4 mb-3"> <label class="sr-only">Region</label> <select name="region" class="form-control"> <option selected="true" disabled="disabled">Region</option> <option value=""></option> </select> </div> <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <select name="city" class="form-control"> <option selected="true" disabled="disabled">City</option> <option value=""></option> </select> </div> <div class="col-md-4 mb-3"> <label class="sr-only">District</label> <select name="district" class="form-control"> <option selected="true" disabled="disabled">District</option> <option value=""></option> </select> </div> </div> View.py def search(request): queryset_list = Listing.objects.order_by('-list_date') # Stage if 'stage' in request.GET: stage … -
Python Generate average for ratings in Django models and return with other model
I'm working on a project using Python(3.7) and Django(2.1) in which I'm trying to implement a rating system. Note: I have searched a lot and taken a look at various related questions but couldn't find any solution to my specific problem, so don't mark this as duplicated, please! I have two models as: From models.py: class Gig(models.Model): CATEGORY_CHOICES = ( ('GD', 'Graphic & Design'), ('DM', 'Digital Marketing'), ('WT', 'Writing & Translation'), ('VA', 'Video & Animation'), ('MA', 'Music & Audio'), ('PT', 'Programming & Tech'), ('FL', 'Fun & Lifestyle'), ) title = models.CharField(max_length=500) category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) description = models.CharField(max_length=1000) price = models.IntegerField(blank=False) photo = models.FileField(upload_to='gigs') status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class GigReview(models.Model): RATING_RANGE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) user = models.ForeignKey(User, on_delete=models.CASCADE) gig = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='rates') order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) rating = models.IntegerField(choices=RATING_RANGE,) content = models.CharField(max_length=500) def __str__(self): return self.content From views.py: def home(request): gigs = Gig.objects.filter(status=True) return render(request, 'home.html', {'gigs': gigs}) So, every Gig has many reviews and I want to return the average rating for each gig to the template, how Can I achieve that? -
how to create an admin user when writing a django app
using docs.djangoproject.com "Writing your first Django app part 2", and for some reason, at the Introducing the Django Admin section, it won't let me enter any characters in the password field. Any errors that could cause this? I've tried starting over and following the instructions again, but get the the same results.screenshot of what I see -
Django Celery worker has no connection to a db
I need to delay task which creates object. Example: from celery import shared_task from .models import Keys @shared_task def generate_keys(id): keys = Keys.objects.get(id=id) arr = keys.title.split() keys_arr = [] for i in range(len(arr)): for j in range(i, len(arr)): s = [] for k in range(i, j + 1): s.append(arr[k]) keys_arr.append(' '.join(s)) keys.keys = keys_arr keys.save() But, when I call generate_keys.delay(id), I have this error: django.db.utils.OperationalError: could not connect to server: No such file or directory. Please, help me. -
Django - upsampling a queryset with zero values
I am working a django application that needs to compute the performance of an investment.For that calculation every time-interval needs to be the same. I currently have a model with cashflows (which occur on irregular intervals). So if I need to upfill a queryset with zero values. This to have a cashflow on every day of the interval (i.e. most of them will be zero) I know you can do this with pandas data frame (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html), but am wondering how to do this with django query sets. Anyone? below an example of my cashflowmodel: Class CashFlow(models.Model): date = models.DateField(auto_now=False, auto_now_add=False, blank=False,default = '2019-01-01') amount = models.DecimalField(max_digits=20, decimal_places=2, default='1') def __str__ (self): return self.date -
Django Listview - Filter and Pagination
I'm new to django. I'm trying to create two table, first one with the lastest added products filter by publication_date and second one with the upcoming products filter by release_date. Here my homepage.html code : ... {% for prodotto in products %} <tr> <td>{{ prodotto.title }}</td> <td>{{ prodotto.description }}</td> <td>{{ prodotto.publication_date|date:"d/m/Y" }}</td> <td>{{ prodotto.release_date|date:"d/m/Y" }}</td> </tr> {% endfor %} ... ... {% for prodotto in products %} <tr> <td>{{ prodotto.title }}</td> <td>{{ prodotto.description }}</td> <td>{{ prodotto.publication_date|date:"d/m/Y" }}</td> <td>{{ prodotto.release_date|date:"d/m/Y" }}</td> </tr> {% endfor %} here my model.py : class Products(models.Model): ... title = models.CharField(max_length=100) publication_date = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=1000) slug = models.SlugField(unique=True) release_date = models.DateTimeField() ... here my view.py : class home(ListView): queryset = Products.objects.all() template_name = 'homepage.html' context_object_name = "products" Currently i'm able to only show all the products without filtering. I'm trying to also add pagination only in the first table,but I don't have an idea how to filter and add pagination in my homepage.html. I've tried adding pagination by adding paginate_by = 5 into view.py but with this method,it's adding pagination in both tables. -
Django package that does DRY/encapsulates creating view that periodically checks a celery task till completion
Typically I am looking for a decorator or some outer function that I can pass a standard Template view to - and also pass a reference to a Async task result When the async task is complete, it will render the template given the async result, while it is not complete, it will show a "Busy" sign and try to check every 10 seconds Looking to see if there is a package in Django / python that does this automatically -
Plotly lines in Django
I have a problem displaying the line graph on the plot. I've tried using explicit values and it goes well. When I extracted data from a dataframe and replace the explicit values, the lines are no longer appearing. Columns have values as I extracted them... def graphView(request): proj = Project.objects.first() df = pd.read_csv(proj.base_file) array = df.values _x = 'Avg. Area Income' _y = 'Price' x = df[[_x]].values y = df[[_y]].values trace1 = Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': 10}, mode="lines", name='1st Trace') data=Data([trace1]) layout=Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'}) figure=Figure(data=data,layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') context = { 'graph': div } return render(request, 'projects/plotly.html', context) The line graph based from the column values are not displaying... -
How to fix OSError (invalid argument) error in django
I get this error at django. OSError at /dog_list/ [Errno 22] Invalid argument: "C:\Users\Kanan\Desktop\blank\cv\templates\" My views.py file is like this from django.shortcuts import render from django.http import HttpResponse from django.template import loader from dog.models import User, Dog from django.http import Http404 # Create your views here. def dog(request): context = { "dog_list": Dog.objects.all() } return render('dog.html', request, context=context) And my html file is like this <html> <head> <title> Welcome to Dog sharing platform</title> </head> <body> <h2> Dog types </h2> <li> {% for dog in dog_list %} <ul>{{dog.dog_list}}</ul> {% endfor %} </li> </body> My models.py file is given below class User(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username class Dog(models.Model): breed = models.CharField(max_length=100) name = models.CharField(max_length=100) age = models.FloatField(default=0.5) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.breed How can I fix this? -
Changes values by default after UpdateView
First of all, my apologize for mistakes in English. I have three Models: Books (General Model), BookInfo (Information about book), Location (Position in Library) with Foreign Key. models.py class Location(models.Model): room = models.PositiveIntegerField() bookcase = models.PositiveIntegerField() shelf = models.PositiveIntegerField() class BookInfo(models.Model): title = models.CharField(max_length=120) author = models.CharField(max_length=150) published = models.CharField(max_length=4) position = models.ForeignKey(Location, on_delete = models.CASCADE, related_name = 'position_information') def __str__(self): return self.title class Meta: ordering = ['-id'] unique_together = ['title', 'author'] class Books(models.Model): ON_HANDS = 1 IN_LIBRARY = 0 ALARM = -1 STATUS = ( (ON_HANDS, 'The book is on hands'), (IN_LIBRARY, 'The book is in library'), (ALARM, 'Need to return the book') ) book = models.ForeignKey('BookInfo', on_delete = models.CASCADE, related_name = 'book_information') date_of_issue = models.DateField(blank= True, default=timezone.now) date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14)) status_of_book = models.IntegerField(choices = STATUS, default = 0) def __str__(self): return self.book.title class Meta: ordering = ['-id'] forms.py class BookFormUpdate(forms.ModelForm): class Meta: model = Books fields = ['book','date_of_issue','date_of_return','status_of_book'] widgets = { 'date_of_issue': forms.DateInput(format=('%Y-%m-%d'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}), 'date_of_return': forms.DateInput(format=('%Y-%m-%d'), attrs={'class':'form-control', 'placeholder':'Select a date', 'type':'date'}) } When I use Update Form for Books and change status of book to 1 or -1, I want automatically change the position of Book to (0,0,0). I overwrite … -
How to do a post request (with data) from Ionic 4 to djangorestframework
I'm trying to do a post request from my ionic 4 projects to the Django backend website. Here is my code Django code models.py This is the class i need to post data to class Item(models.Model): item_title = models.CharField(max_length=80) item_description = models.TextField(max_length=600) item_price = models.IntegerField(default=1, blank=True, null=True) item_price_later = models.BooleanField(default=False) item_action = models.ForeignKey(Action, on_delete=DO_NOTHING) item_color = models.CharField(max_length=25) item_category = models.ForeignKey(Category, on_delete=CASCADE) item_type = models.ForeignKey(Type, on_delete=DO_NOTHING) item_size = models.ForeignKey(Size, on_delete=DO_NOTHING) item_city = models.ForeignKey(City, on_delete=DO_NOTHING) item_phone = models.IntegerField() item_image_1 = ProcessedImageField(upload_to='media/', processors=[ResizeToFill(1200, 1485)], format='JPEG', options={'quality': 60}) item_image_2 = ProcessedImageField(upload_to='media/', processors=[ResizeToFill(1200, 1485)], format='JPEG', options={'quality': 60}, blank=True) item_image_3 = ProcessedImageField(upload_to='media/', processors=[ResizeToFill(1200, 1485)], format='JPEG', options={'quality': 60}, blank=True) created_by = models.ForeignKey(User, on_delete=CASCADE) created_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=False) is_delete = models.BooleanField(default=False) serializers.py and here is the serializer I use for the API: class CreateItemSerializer(serializers.ModelSerializer): class Meta: model = models.Item fields = ( 'id', 'item_title', 'item_description', 'item_price', 'item_price_later', 'item_action', 'item_color', 'item_category', 'item_type', 'item_size', 'item_city', 'item_phone', 'item_image_1', 'item_image_2', 'item_image_3', 'created_by', 'created_at', 'is_active', 'is_delete', ) def create(self, validated_data): item_title = validated_data.get('user') item_description = validated_data.get('item_description') item_price = validated_data.get('item_price') item_action = validated_data.get('item_action') item_color = validated_data.get('item_color') item_category = validated_data.get('item_category') item_type = validated_data.get('item_type') item_size = validated_data.get('item_size') item_city = validated_data.get('item_city') item_image_1 = validated_data.get('item_image_1') item = model.Item.objects.create(self,item_title=item_title, item_description=item_description,item_price=item_price, item_action=item_action,item_color=item_color, item_category=item_category,item_type=item_type, item_size=item_size,item_city=item_city,item_image_1=item_image_1) item.save() return item This … -
django autocomplete_fields doesn't work in TabularInline (but works in StackedInline)
I'm trying to use autocomplete-fields in TabularInine Below my code : class PersonInstitutionsInline(admin.TabularInline): autocomplete_fields = ['institution'] model = PersonInstitution extra = 0 When rendering the dropdown is simply empty with no error (javacsript or python) If I use the same with StackedInline it works correctly While checking the templates, I'm suspecting that it has to with the fact that stacked.html uses {% include "admin/includes/fieldset.html" %} but tabular.html uses {{ field.field }} Also on another note, if I try to use django-autocomplete-light form in any inline inlines.js:20 Uncaught TypeError: Cannot read property 'fn' of undefined at inlines.js:20 at inlines.js:298 with in python the error MediaOrderConflictWarning: Detected duplicate Media files in an opposite order: admin/js/autocomplete.js admin/js/admin/DateTimeShortcuts.js MediaOrderConflictWarning, I'm using Django version 2.1.7 Anyone had a similar issue or is there a fix for it ? Currently the workaround I'm using is StackedInline, and putting them all in the same fieldset...but i think there should be a better solution for it. Thanks -
How to display data in a new page from the database after doing some postprocessing on the new data
Django newbie here, I created a few forms which correctly stores them in the database, and then used django signals to do some post-processing on the latest data. Now I want to display that data on a new page, so how do I go about that ? Consider my django app takes in the weight,height, lifestyle habits of patients, and then on the next page, show that data in a tabular form, but also displays how close they are to healthy eating habits, their BMI, fat percentage etc. -
Django command - No module named 'scrapy_spider'
I'm trying to run spiders from Django management command. It works but it doesn't use settings from scrapy project. django_project/ django_project/ app1/ scraping/ # This is app but it has scrapy project inside too scrapy_spider/ settings.py spiders/ When I try to specify settings inside the command, it returns: ModuleNotFoundError: No module named 'scrapy_spider' COMMAND import os from django.core.management.base import BaseCommand from scrapy.utils.project import get_project_settings from twisted.internet import reactor, defer from scrapy.crawler import CrawlerRunner from scraping.scrapy_spider.spiders.autoscrape_index_spider import AutoScrapeIndexSpider from scraping.scrapy_spider.spiders.autoscrape_spider import AutoScrapeSpider class Command(BaseCommand): def handle(self, *args, **options): os.environ['SCRAPY_SETTINGS_MODULE'] = 'scraping.scrapy_spider.settings' runner = CrawlerRunner(settings=get_project_settings()) @defer.inlineCallbacks def crawl(): yield runner.crawl(AutoScrapeIndexSpider) yield runner.crawl(AutoScrapeSpider) reactor.stop() crawl() reactor.run() Do you know how to make it work? -
how to design Inventory model for Purchase Stock Sell in django
I am developing an inventory app in django which have Purchase, Stock and sell model. Where do I need to improve my model to update stock quantity when sell an item and also repurchase an item. This is for tracking purchase, sell history. I have tried many to many example by django Group Member example but unable to update stock when sell and purchase. class Item(models.Model): name = models.CharField(max_length=30) category = models.ForeignKey(Category) class Purchase(models.Model): invoice = models.CharField(null=False) invoice_date = models.DateField() seller = models.CharField(max_length=50) item = models.ManyToManyField(Item) perform_by = models.ForeignKey(User) # Authenticated user class Stock(models.Model): item = models.ForeignKey(Item) quantity = models.PositiveSmallIntegerField() class Sale(models.Model): invoice = models.CharField(max_length=12) invoice_date = models.DateField() item = models.ManyToManyField(Item) quantity = models.PositiveSmallIntegerField() I expected stock value Item type quantity A Red 20 A Green 15 B Red 10 and also update stock value when sell and purchase an item. But could not find the stock value. What thing I need to update. Thank in advance