Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access super model in Base Model django
I have a base model defined as follows: class BaseModel(models.Model): date_created = models.DateTimeField(editable=False) date_modified = models.DateTimeField(blank=True) id = models.CharField( max_length=11, unique=True, primary_key=True, blank=True, ) class Meta: abstract = True Now, I want to add a save method and in the save I want to filter through the super models table as follows: SUPER_MODEL.objects.filter(id=id) Where super model is the model that extends BaseModel. How would I access this super model? Does this make sense? Thanks! -
extending existing model with new fields
I have a django project, where I use a third-party extension that inserts its own models (something like ExtensionApp.Model1 and ExtensionApp.Model2). I need to make some adjustments (specifically add a couple new fields there). Right now what I do is OneToOne field in my own app model to ExtensionApp.Model1, and there I can add what I need. I just don't want to touch the core of this extension app. But I think whether it is the right way to do? Is there a way to add new fields to existing models of third-party app? I know there are proxy models (https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-models) but these allow to add new methods, not fields. -
How to create an app in a directory with the same name?
I would like to create a django app in a directory with the same name for example: ./manage.py startapp offer_place ./x/offer_place instead of creating the apps files into /x/offer_place destination. It treats offer_place as a python module an produces that error: CommandError: 'offer_place' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I also tried to delete offer_place foler, but it gave me an error that the folder does not exist! -
how to use django signals using singnals.py
the django signal is not working when am using signals.py but it works if i use the normal models.py accounts/signals.py from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from .models import Profile def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print("profile created") post_save.connect(create_profile, sender=User) def update_profile(sender, instance, created, **kwargs): if created == False: instance.profile.save() print('profile updated') post_save.connect(update_profile, sender=User) accounts/app.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' def ready(self): import accounts.signals accounts/settings.py INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', ] -
How to order_by calculated fields based on some other model? (Django)
For eg: Model Company has fields: companyName and stock_price Model Products has fields: product_price and company_name I want to do something like: Company.objects.order_by( stock_price / [divided by] Products.objects.filter(company_name = Company__companyName).aggregate(Sum('product_price')).get('product_price__sum')) Essentially, what I want to do is divide the stock price of company X by the aggregate of product_price of the products of company X and use the resulting calculation to order all the objects of Company. I just want to know if doing such a thing is possible in Django. Thanks! -
How to deal with sensitive user data in Django?
I am working on a project in django that collects sensitive data (medical data) about its users. I want to store this data and collect it to get stats on it. I want to know what precautions I need to take from a legal standpoint. Do I need to collect data with two databases: One that is used to display content on the website And anonymous version that I can use for stats Or do I not need to worry about anonymizing the data before I see it? Does this make sense? Thanks! -
inline formset only save the last form
i tried many ways and searched alot(googled) but no one worked for me . whenever i save my inlineformset it only save the last form , my models.py class Book(models.Model): book = models.CharField(max_length=20,unique=True) author = models.ForeignKey(Author,on_delete=models.CASCADE) class Author(models.Model): author = models.CharField(max_length=30,unique=True) count = models.IntegerField() this is my forms.py class AuthorForm(ModelForm): class Meta: model = Author fields = ['author','count'] class BookForm(ModelForm): class Meta: model = Book fields = ['book'] inlineformset_author = inlineformset_factory(Author,Book,form=AuthorForm,extra=1) this is my template class CreateBookView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Author form_class = AuthorForm def get_context_data(self,*args,**kwargs): context = super(CreateBookView,self).get_context_data(*args,**kwargs) if self.request.POST: context['book'] = inlineformset_author(self.request.POST) context['book'] = inlineformset_author() return context def form_valid(self,form): context = self.get_context_data() context = context['book'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateBookView,self).form_valid(form) and this is my template <form method="POST">{% csrf_token %} {{book.management_form}} {{form.author | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.count | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:count'}} <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> <div id="BOOK" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"><div class="modal-content"><div class="modal-header"> <h5 class="modal-title" id="my-modal-title">BOOK</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <div class="modal-body"> <button type="submit" class="btn btn-success">save</button></dic> </div> <div class='modal-footer'></form> <script> $(document).ready(function(){ $('#BOOKBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#count').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="BOOK'+justforName+'"').val()); } if(numOfContent!=numberOfInput){ … -
Load excel file to selected table name
Learning django and this might be a very basic question.. please excuse.. I have created a dropdown in my django app linked to a database model column that has list of table names in my database. I want to allow the user to select the table name in the drop down and then browse to an xlsx file and load the data to the table. Need your expert advise on the below.. Is it possible to create a view that can load excel data dynamically to the model based on table name selecred? Is it possible to validate the colmn names first before performing data load to avoid issues? Is it possible to perform truncate and load vs append data by allowing the user to choose the action. Thank you very much for your guidance and also appreciate if you can put me in the right direction with some samples, examples or documentation. Thank you. -
how to implement ajax into my django project
I currently have a takeout website that does everything I need it to do. However, whenever I add an item or change its quantitiy it refreshes the page causing the user to scroll back to wherever they were before if they wanted to add more items. I realize that this project requires an AJAX implementation to update the cart without refreshing the entire page. I've been trying my best to piece together everything I needed to get it running but im lacking the general direction of how to change my django code into something ajax could use. A snippet of my views.py where it handles adding a new item to the cart if latest_order.filter(order_name=menu_name): order_instance = latest_order.get(order_name=menu_name) order_instance.order_quantity = F('order_quantity') + 1 order_instance.order_individual_price = F('order_default_price') * order_instance.order_quantity order_instance.save() return redirect('shop-ordering') A snippet of my html that shows the menu and a "add to cart" button {% for menu_items in menu %} <tbody> <tr> {% if menu_items.Menu_name == 'KOREAN COFFEE' or menu_items.Menu_name == 'CITRON TEA' or menu_items.Menu_name == 'GINSENG TEA' or menu_items.Menu_name == 'PLUM TEA'%} <!--========================== HOT DRINKS ============================--> {% if menu_items.Menu_name == 'KOREAN COFFEE' %} <thead> <tr> <th></th> <th> <h1 class='one-line'>HOT DRINKS</h1> </th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> {% … -
How to send large table data using AJAX using GET/POST method in Django
I want to send my table data to the server using javascript(or ajax). How can I do this? There will be around 2k rows. The data is in a list of lists. How to send the data in lists? Here is what I did: JavaScript: $.ajax({ contentType: 'application/json; charset=utf-8', url:'/ccd/ajax/update-database', type: 'POST', data :{'headings':headings,'data_list':data_list,'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(data) { if(data.success) { console.log("success!"); } else { console.log("error!"); } } }); I'm not able to access this data in my views.py file. I'm getting None type of data. Views.py def ajax_update_database(request): data = dict() data['success']=False if request.is_ajax() and request.method=='POST': headings = request.POST.get('headings') print(headings) datalist = request.GET.get('data_list') print(headings) data['success']=True return JsonResponse(data) Any alternative will also be appreciated. -
DRF - Could not resolve URL for hyperlinked relationship using view name "matchteam-detail"
I know there are a lot of similar questions here, but I tried most of the answers and none worked so far... The error I get is: ImproperlyConfigured at /matches/1/ Could not resolve URL for hyperlinked relationship using view name "matchteam-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. However, matchteam-detail is in my urlpatterns: <URLPattern '^matchteams/(?P<pk>[^/.]+)/$' [name='matchteam-detail']>, <URLPattern '^matchteams/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='matchteam-detail']>, This error happens on a many-to-many relationships with a "through" model on Django REST Framework, when accessing a "Match" object on the API: models.py class MatchTeam(models.Model): team = models.ForeignKey("teams.Team", on_delete=models.CASCADE) match = models.ForeignKey("matches.Match", on_delete=models.CASCADE) score = models.PositiveSmallIntegerField(default=0) class Match(models.Model): teams = models.ManyToManyField("teams.Team", through='matches.MatchTeam') class Team(models.Model): matches = models.ManyToManyField("matches.Match", through='matches.MatchTeam') serializers.py class MatchTeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MatchTeam fields = ['id', 'team', 'match', 'score'] class MatchSerializer(serializers.HyperlinkedModelSerializer): teams = serializers.HyperlinkedRelatedField( read_only=True, view_name='matchteam-detail', ) class Meta: model = Match fields = ['id', 'teams'] class TeamSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Team fields = ['id', 'name'] urls.py router = DefaultRouter() router.register(r'teams', TeamViewSet) router.register(r'matches', MatchViewSet) router.register(r'matchteams', MatchTeamViewSet) urlpatterns = router.urls The views are defined with ModelViewSets. Any ideas why this might be happening? Thanks! -
load picture from static file django
Django is not loading my static files. I'm trying to load an image from the static folder, but it doesn't work. file.html <body> {% load static %} <img src="{% static "products/logo.jpg" %}" alt="My image"> </body> structure app |_______products |_________templates |_________file.html |_________models.py |_________ ... |______static |_________products |_________logo.jpg settings ... INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] ... STATIC_URL = '/static/' -
Django - DeleteView is missing a QuerySet
I have a model called Order. I want to delete a specific order with Class Based View (DeleteView) but is it is not working. Exception Type: ImproperlyConfigured Exception Value: DeleteView is missing a QuerySet. Define DeleteView.model, DeleteView.queryset, or override DeleteView.get_queryset(). model.py class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='orders') product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=200, null=True) view.py class OrderDeleteView(UserPassesTestMixin, DeleteView): model = Order template_name = 'accounts/delete.html' @method_decorator(login_required(login_url='login')) @method_decorator(allowed_users(allowed_roles=['admin'])) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def test_func(self): order = self.get_object() if order.customer.id == self.request.user.id: return True else: return False urls.py path('delete_order/<str:pk>', DeleteView.as_view(), name='delete_order'), What is the reason of this error -
how to use a forloop for my blog post to stand next to each other in django
actually my title might not be clear but let me explain,i have list of blogpost i want to use forloop to make each post stand next to each other,instead they all stood straight which i dont want here is the post this is how it is in picture , {this is how i want them to look like in a picture} blog.html <section class="ftco-section bg-light" id="blog-section"> <div class="container"> <div class="row justify-content-center mb-5 pb-5"> <div class="col-md-10 heading-section text-center ftco-animate"> <h2 class="mb-4">Gets Every Single Updates Here</h2> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p> </div> </div> <div class="row justify-content-center mb-5 pb-5"> <div class="col-md-4 ftco-animate"> {% for blog in blog_post %} <div class="blog-entry "> {% if not forloop.first and not forloop.last %} {% endif %} <a href="blog-single.html" class="block-20" style="background-image: url({{ blog.thumbnail.url }})"> </a> <div class="text d-block"> <div class="meta mb-3"> <div><a href="#">{{ blog.timestamp|timesince }} ago</a></div> <div><a href="#">{{ blog.user }}</a></div> <div><a href="#" class="meta-chat"><span class="icon-eye"></span>{{ blog.view_count }}</a></div> </div> <h3 class="heading"><a href="#">{{ blog.title }}</a></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="blog-single.html" class="btn btn-primary py-2 px-3">Read more</a></p> </div> {% endfor %} </div> </div> </div> </div> </section> -
Cannot run gunicorn with django-configurations raising ImproperlyConfigured
Building simple django application using django-configurations and gunicorn. If I run it with python manage.py runserver, it's ok. No errors, everybody's happy. But running gunicorn just by executing gunicorn config.wsgi:application raises an error with message: django.core.exceptions.ImproperlyConfigured: django-configurations settings importer wasn't correctly installed. HELP ME TO FIND THE MISTAKE, PLEASE! config/settings.py import os import dj_database_url from configurations import Configuration class BaseConfiguration(Configuration): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
Convert date string received through websockets using django channels to default django date display
So I am using django channels to send some updated field to my front end and update them when the underlying model changes. One of the field is a DateTimeField. Below is my signals.py: @receiver(post_save, sender=Job) def announce_new_user(sender, instance, created, **kwargs): channel_layer = get_channel_layer() group_name = 'job_%s' % instance.job_id message = { 'status': instance.status, 'job_completed_date': instance.job_completed_date.isoformat(), } async_to_sync(channel_layer.group_send)( group_name, { 'type': 'send_job_update', 'text': message } ) Initially when some one opens the page, the field will be displayed like "June 3, 2020, 9:40 a.m.". But since datetime.datetime is not serizable I am using the "isoformat()" to convert it. Now the this field is received in the front end like "2020-06-03T09:15:28+05:30". How can I can update my front end in the correct format. Should I use something other that "isoformat()" or can I do something using javascript to convert the date again? -
Django Admin: How to filter by custom list display field?
In the admin class, I have defined a custom list display as follows list_display = ('custom_display_method_name',) def custom_display_method_name(self, instance): #perform custom operation for list display which uses property of the model How do I write a filter which allows filtering by the custom display, or alternatively filtering by property of a model? I have trued writing a custom filter, but it comes down to queryset. Is there a way to simply filter by the custom display that I have written? -
How to delete a file on django
I am trying to add a view that deletes files(videos) but it seems that there is something wrong with my form because I am getting a ValueError("The view startup_home.views.delete_video didn't return an HttpResponse object. It returned None instead"). views.py def delete_video(request, pk): if request.method == 'POST': if form.is_valid: delete_v = Post.objects.get(pk=pk) delete_v.delete() return HttpResponseRedirect('/') else: return redirect('home') models.py class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) def delete(self, *args, **kwargs): self.text.delete() self.video.delete() super().delete(*args, **kwargs) urls.py urlpatterns = [ path('', views.home, name='home'), path('upload', views.upload, name='upload'), path('video/<int:pk>/', views.delete_video, name='delete_video'), ] home.html {% if content.video %} <div class="float-right"> <form action="{% url 'delete_video' content.pk %}" action="post"> <button type="submit">Delete</button> </form> </div> {% endif %} -
How to access objects created from Django Model Factory
I have populated a test database using Django Model Factory. Here is the model: class RecordType(factory.DjangoModelFactory): class Meta: model = models.RecordType class UserRecord(factory.DjangoModelFactory): user = factory.SubFactory(AccountUser) record_type = factory.SubFactory(RecordType) class Meta: model = models.UserRecord and here is the relevant part of the test: # Create record types for category in enums.Category: factory.RecordType( code=category.value, internal_code=internal_codes[category.value], ) # Add record to the user blind_record_type = factory.RecordType.objects.get(code="08") factory.UserRecord(user=user, record_type=blind_record_type) However, when running the test I am met with the error: E AttributeError: type object 'RecordType' has no attribute 'objects' Is it possible to access these objects? -
Django WritingYourFirstDjangoApp Part5
I was using the following tutorial website and although I had followed every instruction on the website, this error showed up... docs.djangoproject.com/en/3.0/intro/tutorial05/ (python shell) In [16]: response = Client.get(reverse('polls:index')) Internal Server Error: /polls/ Traceback (most recent call last): File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 470, in parse compile_func = self.tags[command] KeyError: 'ls' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/****/Desktop/Programming1/hello_django/django/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/****/Desktop/Programming1/hello_django/django/django/core/handlers/base.py", line 202, in _get_response response = response.render() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/loader.py", line 42, in select_template return engine.get_template(template_name) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/****u/Desktop/Programming1/hello_django/django/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/loaders/base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 155, in init self.nodelist = self.compile_nodelist() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 193, in compile_nodelist return parser.parse() File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 472, in parse self.invalid_block_tag(token, command, parse_until) File "/Users/****/Desktop/Programming1/hello_django/django/django/template/base.py", line 534, in invalid_block_tag "or load this tag?" % (token.lineno, command) django.template.exceptions.TemplateSyntaxError: Invalid block tag on line … -
how to add group field in django admin using custom user model
django custom user model i created a custom user model but if i open a user in the django admin, i cannot see the field to add the user to a group. what will i need to add to my custom user model code so i can see the field to mannually add a user to a group in the django admin? for example i know if i want to see permission fields, i will add to my class UserAdmin: fieldsets = ( ('Permissions', {'fields': ('admin', 'staff')}), ) -
Storing answers to questionnaire in Django model
I have a django model that should store users's answers to a questionnaire. There are many types of questionnaires, but one could be simple like this (many are more complicated though): What is your name? What is your age? What is your height? What is your age? I want to know how I could create a model to store the data that was submitted in the form. Right now, I am using a simple JSON field like this: from django.contrib.postgres.fields import JSONField data = JSONField(default=dict) This gets difficult however when the questionnaire get much longer. What would be the best way to do this? If a JSON field is the best way, how should I structure the json assuming there could be different types of questions (input field, multiple choice, etc.)? Thanks!! -
javascript для backend разработчика [closed]
Всех приветствую, сразу прошу прощения за расплывчатый вопрос. Хочу стать бекенд разработчиком, доучился до уровня кривого сайта на Django/Bootstrap. Перехожу к изучению Django Rest Framework ибо углубляться в стоковый Django можно очень долго, а на работу хочется скорее(DFR очень часто указан в требованиях). Вопрос: Какой уровень понимания javascript мне нужен? В коммерческой разработке каким будет мое взаимодействие с AJAX? По плану: DRF -> Docker -> идти собеседоваться Заранее благодарен, если кто-то поможет прояснить.Естественно понимаю, что в вакууме среди современных технологий нет тех, которые не стоит изучать, вопрос стоит в условиях сжатых сроков. -
Vue js downloaded excel file is corrupted
I have problem with excel file download in Vue. The url in the backend seeems to be ok: "file" parameter stores my url in the object this.scenario.file = "http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" downloadFile() { axios({ url: this.scenario.file, method: "GET", headers: {"Accept": "application/vnd.ms-excel"}, responseType: "blob" }).then(response => { const fileURL = window.URL.createObjectURL(new Blob([response.data])); const fileLink = document.createElement("a"); fileLink.href = fileURL; fileLink.setAttribute("download", "file.xlsx"); document.body.appendChild(fileLink); fileLink.click(); }); }, -
Django Admin has no style sheet
Good day everyone, I'enter image description herem new to Python and Django I started of with online tutorials and some books I just tried getting through and my Django admin page has no styling...... what really did miss?