Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Exclude field if select_related() gets used
I have a Job and Blob model like this: class Job(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) start_time = models.DateTimeField() input = models.ForeignKey('Blob') class DeferContentManager(models.Manager): use_for_related_fields = True def get_queryset(self, *args, **kwargs): return super(DeferContentManager, self).get_queryset(*args, **kwargs).defer('content') class Blob(models.Model): content = models.BinaryField() name = models.CharField(max_length=10000, default='') objects = DeferContentManager() Unfortunately there is an Django ORM query which does this: Job.objects.filter(....).select_related() This loads the BinaryFields of the jobs and we get a MemoryError. Is there a way to exclude the BinaryField content if I do a select_related() query like above? PS: I know that I could alter the query and use select_related('non_binary_field') but a general solution is needed here. I do not have access to the code which does call this line: Job.objects.filter(....).select_related() -
update two models in the same form error:'QuerySet' object has no attribute '_meta'
so i'm traying to update two models using UpdateView in single foms related with a foreign key for the images i'm using a formset to upload multiple images but i think i have more than not just with the instance any help will be usefull tnks :) models.py class Product (models.Model): User=models.ForeignKey( User, on_delete=models.CASCADE, ) Name=models.CharField(max_length=50,blank=True) Type=models.CharField(choices=Product_Type,max_length=50) Description=models.TextField(max_length=250,blank=True) Price=models.FloatField(default=0.0) def __str__(self): return self.Name def image(self): return self.images.all() class ImageModel(models.Model): product=models.ForeignKey(Product,default=None,related_name='images' ) Image = models.ImageField( upload_to='products_photos',blank=True,null= True) views.py class ProductUpdate(UpdateView): ImageFormSet = formset_factory( ImageForm, extra=3) model=Product form_class = ProductForm second_form_class = ImageFormSet template_name = 'store/product_update.html' def get_context_data(self, **kwargs): context = super(ProductUpdate, self).get_context_data(**kwargs) produit=Product.objects.filter(User=self.request.user) context['form'] = self.form_class(self.request.GET, instance=produit) context['form2'] =self.second_form_class(self.request.GET,instance=ImageModel.objects.filter(product=produit)) return context def get_success_url(self): return reverse('my_products',kwargs={'pk':self.object.pk}) my_products.html <a href="{% url 'product_update' pr.pk %}" class="btn btn-primary"> <i class="fa fa-pencil fa-fw"></i> edit </a> -
Django JsonField to forms
I have searched for a couple days to try to find a DRY way to create dynamic forms from a JsonField using django's built in validation and form rendering. I have yet to find a solution that will incorporate django's validation and rendering so I would like to create a module for this but I am having a hard time figuring out how the classes work. I have tried a couple different things such as the following: models.py from django.contrib.postgres.fields import JSONField from django.db import models class Model(models.Model) name = models.CharField(max_length=50) json_fields = JSONField() forms.py from django import forms from .models import Model fields_dict = { 'name': forms.CharField(max_length=25), 'number': forms.IntegerField() class ModelForm(forms.ModelForm) class Meta: model = Model exclude = ['json_fields'] class DynamicForm(forms.Form, attrs=fields_dict) pass This is the error I get: Error TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases It looks like forms.Form subclasses forms.BaseForm and forms.DeclaritaveFieldsMetaclass but I can'f figure out how to subclass forms.Form to pass in dynamic fields from a dictionary. I have also tried the following: views.py from django import forms from django.shortcuts import render from .forms import fields_dict def dynamic_form(request): class NewForm(forms.BaseForm, … -
How to receive a request from HTML and process it on my view and model side
I'm new on sofware dev, please be pacient. I'm trying to receive a request from my html code and get the shift Code value, this can be Shift1, Shift2 or Shift3. I'm using read-only oracle db, that's why i'm using raw query. Basically, I want to filter my table results in html code, through the "Shift" result according the user selection, now I'm showing the all shifts results, how to filter it? Please, tell me how to do it on my views.py and models.py Html code: <div id="page-content-wrapper"> <div class="container-fluid"> <a href="#menu-toggle" class="btn btn-secondary" id="menu-toggle"><< Menu</a> <h4 align="right" >{{ date|date:'Y-m-d H:i' }} </h4> <h1>SMD/PBA System Management</h1> <div class="container-fluid"> Select the shift <form action="{ %url 'show_list' %}" method="post"> <div class="form-row align-items-center"> <div class="col-auto my-1"> <select class="custom-select mr-sm-2" id="inlineFormCustomSelect" name="shift"> <option selected>Shift 1</option> <option value="1">Shift 1</option> <option value="2">Shift 2</option> <option value="3">Shift 3</option> <option value="ALL">ALL</option> </select> </div> <button type="submit" value="Submit" class="btn btn-info">Search</button> </div> </form> <br> <h4>Retest IM</h4> <table align="left" border="2" class="table table-dark"> <tr bgcolor="#0080ff"> <td align="center">Date</td> <td align="center">Shift</td> <td align="center">Line</td> <td align="center">Model</td> <td align="center">Insp QTY</td> <td align="center">Retest QTY</td> <td align="center">Index PPM</td> {% for instance in query %} {% if instance.DEF_INDEX_PPM > 5000 %} <tr bgcolor="#ff4d4d"> {% else %} <tr> {% endif %} <td … -
Django Admin: adding an icon with assigned JS above the textarea
I'd like to add a couple of icons (or buttons) with simple JS functionality (e.g. wrapping selected text in HTML tags with particular class). Like this: Screenshot How can I accomplish this? -
Django formset view in template in reverse order
I am using modelformset_factory and view formset data in template. If you look at below image the template is showing data in 1st image. But i want to view the formset in reverse order like in 2nd image. First i will have new data enter textbox. Then the old data will be listed in reverse order like it is done in 2nd image. My model is : class AssistantNotes(BaseModel): categories = models.CharField(choices=CATEGORIES, max_length=100, verbose_name=_("Kategori")) dailynote = models.TextField(null=True, blank=True, verbose_name=_("Not Ekle")) def __unicode__(self): return "%s / %s" % (self.dailynote, self.categories) class Meta: ordering = ['dailynote'] Then i created below view. def create_assistant_notes(request): if request.method == 'GET': if AssistantNotes.objects.count() == 0: file_write("get000") AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',)) else: file_write("get111") AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',), can_delete=True) formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.all()) helper = TableInlineHelper() return render(request, 'create-assistant-notes.html', {'formset': formset, 'helper': helper}) elif request.method == 'POST': if AssistantNotes.objects.count() == 0: AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',)) else: AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('categories', 'dailynote',), can_delete=True) formset = AssistantNotesFormsetFactory(request.POST) if formset.is_valid(): formset.save() else: helper = TableInlineHelper() return render(request, 'create-assistant-notes.html', {'formset': formset, 'helper': helper}) return redirect(reverse('create-assistant-notes')) My template html file is; {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}{% trans "Notes" %}{% endblock title %} {% block … -
Django make sertain fields readonly for a sertain element of a Model
My model looks like that class Article(models.Model): title = models.CharField(blank=False, null=False, max_length=200, verbose_name="title") description = RichTextUploadingField(blank=False, null=False, verbose_name="description") is it possible 1st To create by default article with title='Terms and conditions' which is going to be readonly in the django-admin and description that can be modified in the django-admin OR If I already have it created to go like python manage.py shell from articles.models import Article terms = Article.object.get(title='Terms and conditions') terms.title.readonly = True this option throws an error AttributeError: 'str' object has no attribute 'readonly' -
Django Database structure, How to handle slug from two different models like Facebook does?
I have a project that publishes job offers, a job seeker can create a profile on the website and his profile page will have URL like: www.domain_name.com/slug An institution publishing job offers can also create an account.The person actually creates the institution account will be considered as the administrator of the institution page, so he will have an account (*instance of UserProfile() and can add other members (Users on the platform not affected to any institutions) to that institution. Institution profile URL will be www.domain_name.com/institution_slug Members will have their own UserProfile instance linked to that institution, and once connected, only the institution page data/functionalities will be visible, they will work as the institution. So What is the best way to have these 2 models and handle the URL pattern properly? like urls.py path("<slug:slug>",profile,name='profile') views.py def profile(request,slug): user = UserProfile.objects.get(slug=slug) #get_object_or_404 inst = Institution.objects.get(slug=slug) #get_object_or_404 In above example, I don’t want to have to query twice in two different models. Is there another way to do it? Or If I need to re-design the database structure, let me know! models.py UserProfile(models): # info_about_user sug = models.SlugField() institution = models.ForeignKey(Institution) Institution(models.Model): # info_about_instituion slug = models.SlugField() Note that both may publish job … -
How can I use the Model's function?
I have a TypeModel model, and in it there is a : class TypeModel(models.Model): name = models.CharField(max_length=22) type = models.CharField(max_length=12) ch = models.CharField(max_length=44, null=True) def print(self, name, type): t = TypeModel.objects.create(name=name, type=type) print('success - ' + t.name) I want to invoke the print method like this: class TypeModelCreateAPIView(APIView): permission_classes = [AllowAny] def post(self, request): TypeModel.print() # Can I invoke like this return Response(status=HTTP_200_OK, data='') Whether I can invoke the function of model like this? if not, how to realize the Class method of model? -
Django: Updateview inlineformset error - (Hidden field id) This field is required
I am trying to edit an updateview in django that has an inlineformset. Below are the model.py, forms.py, views.py, and the template files. The form is not saving, so I placed a print(actor_form) in the post method in the views.py to see what was happening. I got the following html code: <input type="hidden" name="actor-TOTAL_FORMS" value="1" id="id_actor-TOTAL_FORMS" /><input type="hidden" name="actor-INITIAL_FORMS" value="1" id="id_actor-INITIAL_FORMS" /><input type="hidden" name="actor-MIN_NUM_FORMS" value="0" id="id_actor-MIN_NUM_FORMS" /><input type="hidden" name="actor-MAX_NUM_FORMS" value="1000" id="id_actor-MAX_NUM_FORMS" /> <tr><td colspan="2"><ul class="errorlist nonfield"><li>(Hidden field id) This field is required.</li></ul></td></tr> <tr><th><label for="id_actor-0-actorName">ActorName:</label></th><td><input type="text" name="actor-0-actorName" value="www" maxlength="50" id="id_actor-0-actorName" /></td></tr> <tr><th><label for="id_actor-0-DELETE">Delete:</label></th><td><label for="id_actor-0-DELETE" class="checkbox-inline"><input type="checkbox" name="actor-0-DELETE" id="id_actor-0-DELETE" /> </label><input type="hidden" name="actor-0-id" id="id_actor-0-id" /><input type="hidden" name="actor-0-useCase" id="id_actor-0-useCase" /></td></tr> In the second line above, you can see - (Hidden field id) This field is required. I believe this is cause the inline to not save, but I do not know how to fix it. Here is the models.py class Profile(models.Model): profileName = models.CharField(max_length=50) profileBoundary = models.CharField(max_length=3, choices = BOUNDARY_CHOICES) class Actor(models.Model): profile= models.ForeignKey(UseCaseProfile, on_delete=models.CASCADE , null=True, blank=True) actorName=models.CharField(max_length=50) here is the forms.py class ProfileForm(ModelForm): class Meta: model=Profile exclude = ('project',) class ActorForm(ModelForm): class Meta: model=Actor fields ='__all__' views.py class ProUpdateView(UpdateView): template_name = 'Update.html' model = Profile form_class = ProfileForm def get_success_url(self): self.success_url … -
Serializing QuerySet with marshmallow
I am trying to serialize an object with nested objects (which in turn has nested objects, which in turn... you get the idea). I have ModelA and ModelB. ModelA has many ModelB, so the serialization schema would be: class ModelBSchema(marshmallow.Schema): pass class ModelASchema(marshmallow.Schema): modelbs = fields.Nested(ModelBSchema, many=True) Except this of course does not work because ModelA has no modelbs attributes, so marshmallow doesn't know how to build the data. They have the data_key for situations like this but only when the source data attribute name is different. But in my case the schema attribute should be fed with a return value: modela.modelb_set.all(). The module has decorators to process data pre and post dump and load. But they don't seem to have anything like that to feed data to the schema. Adding a modelsb property in ModelA would be a solution, but a bad one, because I would be coupling these components. ModelA should remain completely separate from the serialization process. There's fields.Method: class ModelASchema(marshmallow.Schema): modelbs = fields.Method('get_modelbs') def get_modelbs(self, obj): return obj.modelb_set.all() But then I lose all the features of a Nested field. I could also declare an intermediary class ModelAData with all data that needs to be passed to … -
Types of error_messages in Django-rest-framework
I'm implementing custom error messages for my serializer. Various sources I found that to implement custom error messages inside a serializer: class MySerializer(serializer.ModelSerializer): ... Meta: model = MyModel fields = ['username'] extra_kwargs = { 'username': {"error_messages":{ "required": "username is required", "blank": "username cannot be blank", "invalid": "username is invalid", } }, } So instead of raising username: This field is required. it raises username: username is required. I have one such error_message on a field and these don't work on that field i.e, I was unable to guess its error_message type. But I was wondering what other types of error_messages are there other than blank, required and invalid? -
uWSGI performace tunning (nginx, django, uwsgi)
I need some guidance to optimize the capacity of our web servers. We are running our python web app on AWS EC2 instances behind an ALB. The servers are running Ubuntu 16.04, uWSGI 2.0.17, python 3.5.1, nginx 1.10.3. At peek times about we have ~ 6k requests/min on our app and our ALB sometimes marks one of the servers as unhealthy as it gets a 502 error. After reading documentation and a lot of posts we have tried a lot of changes into our uwsgi config but we can not decide what are the best settings and how we can make sure the clients don't get 502 errors. We have tried running the servers in ASG with smaller servers but we got a lot of problems with 502 errors and we blaimed the uwsgi connections ( nr of processes and threads available where full before the new servers where up to take some load ). We have tried to benchmark our app with different uwsgi settings and running uwsgitop but we failed to determine the best config for us. We have 8 cpu's and 16GB of RAM on our 2 servers and the curent uwsgi config is: [uwsgi] autoload = … -
Django ORM (1.11): How to get the first element of a list of related objects that matches a criteria, within an annotation
I have the following annotation: name=Case( When( related_model__confirmed=F("confirmed"), then=F("related_model__name") ), default=None, output_field=CharField() ) It has an obvious problem: it increases the size of the queryset. Not only that, I want the annotation to be set to either rel_model_a__model_b__name (the first time the condition is met), or None if the condition is never met. Any way I can do this? -
Browser push notifications with Django
I'm working on a web app with Django (Python3), and I need to make a push notification system that notify a specific user even if his browser is closed. So I need some advice to know how and where to begin, thanks. -
Serializing QuerySet with marshmallow
I am trying to serialize an object with nested objects (which in turn has nested objects, which in turn... you get the idea). I have ModelA and ModelB. ModelA has many ModelB, so the serialization schema would be: class ModelBSchema(marshmallow.Schema): pass class ModelASchema(marshmallow.Schema): modelbs = fields.Nested(ModelBSchema, many=True) Except this of course does not work because ModelA has no modelbs attributes, so marshmallow doesn't know how to build the data. They have the data_key for situations like this but only when the source data attribute name is different. But in my case the schema attribute should be fed with a return value: modela.modelb_set.all(). The module has decorators to process data pre and post dump and load. But they don't seem to have anything like that to feed data to the schema. Adding a modelsb property in ModelA would be a solution, but a bad one, because I would be coupling these components. ModelA should remain completely separate from the serialization process. So what can I do? -
Refreshing a Post's Cache Using Django
I have a forum where users can write posts and others can then comment on these posts. I decided to use Django's caching framework to speed up my site, so I naively cached my entire site using the documentation. Now when a user comments on a post, it doesn't show up until after 600 seconds which is how long I cache each page for. Is there a way to "refresh" a post's cache when a user comments on it? Thanks for any help, Jack -
psycopg2.ProgrammingError: permission denied for relation django_migrations
(django-test) riya@bounce:~/Project/myproject$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f904ad9a598> Traceback (most recent call last): File "/home/riya/.virtualenvs/django-test/lib/python3.4/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: permission denied for relation django_migrations I am trying to run the server and geeting this type of Error.The error says permission denied for relation django_migration. -
Saving serialized data in the database
I need to save the state of some data for a rollback feature and for that I am using serialization/deserialization. Serialized data will take the form of a dictionary, which can be transformed into a JSON string. I need to make a choice: store the JSON string directly as text store it using a JSONField which I am not sure how it is stored, the docs do not say it store it as blob or binary data for which there seems to be a BinaryField, although I have never used it before What are the pros and cons of each? Which one should I use? -
Django SendGrid not sending email when attaching a template to email
When I send an email with no template I receive the email just fine. When I add an id for the template I don't get any errors but don't receive the email either. The template is set to active. I have my SENDGRID_API_KEY in my settings file. I know it must be something really stupid but cant seem to get it working. Any help would be greatly appreciated. Template id in the code below is masked so not what the actual code looks like. from django.views.generic import TemplateView from django.shortcuts import render from django.conf import settings from django.core.mail import send_mail from django.core.mail import EmailMultiAlternatives def emailSendGrid(self): mail = EmailMultiAlternatives( subject="Your Subject from sendGrid", body="SendGrid sent This is a simple text email body.", from_email="m@test.com", to=["martin@test.com"], headers={"Reply-To": "m@test.com"} ) # Add template mail.template_id = '##############################' # Replace substitutions in sendgrid template # mail.ad = {'testTag': 'Test email sent from sendgrid with new content'} mail.send() -
Filtered list in URL for hierarchical data with Django Rest Framework
Viewsets in Django Rest Framework keep my code very clean: I can define a model and then a viewset to go along with it. However, how do I best deal with models which are hierarchically under another one? For example: I have a Project which has many Files and want this API: GET /api/files: get all files across all projects GET /api/files/:id: detail a particular file GET /api/projects/:id/files: list all files in a project The following code almost works, except that the URL for 3. comes out as api/files/projects/:id: class FileViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = File.objects.all() serializer_class = FileSerializer @action(methods=["get"], url_path="projects/(?P<project_id>[^/.]+)", detail=False) def list_for_project(self, request, project_id): project = Project.objects.get(id=project_id) # ... list only Files for this Project I have looked in to a few solutions such as writing custom routers, using more than one viewset or view, or custom packages; but I'm surprised that it isn't easy to do with DRF out-of-the-box within one Viewset. Am I missing a trick? What do people usually do in this scenario? -
tracking opened email via django
Hi all I tried to track the opened mails with PHP but google's new image proxy thing now not allowing to execute php scripts via mail(May be my imagination if someone had a working script pls point me there I tried this one https://github.com/brampauwelyn/php-email-tracker). So I'm trying that in Django with this post https://www.pythoncircle.com/post/626/how-to-track-email-opens-sent-from-django-app/ But it seems like it's working but I can't figure out how to implement it. He skipped some of the part it. It is so confusing. Right now I have urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from mailer import views urlpatterns = [ url(r'^image_load/$', views.image_load, name='image_load'), path('admin/', admin.site.urls), ] views.py def image_load(request): print("\nImage Loaded\n") red = Image.new('RGB', (1, 1)) response = HttpResponse(content_type="image/png") red.save(response, "PNG") return response I'm getting error at when I do this text_content = '<h1>This is an image message.</h1>' tracker = '<img src="{{image_url}}" alt="" width="1" height="1" border="0">' text_content += tracker text_content["image_url"] = HttpRequest.build_absolute_uri(reverse("image_load")) print(context_data) On the 4th line says tracker['image_url'] = request.path('image_load') TypeError: 'str' object is not callable Please help get through this. -
Trouble installing Django 2.x in Ubuntu 18
I am trying to install the latest Django in Ubuntu 18, But I am facing some weird troubles. I came across 2 ways to install it. Method 1: If I use below command then the previous version of Django is getting installed $ sudo apt-get install python3-django $ django-admin --version 1.11.11 Method 2: If I install it using pip then on checking the version I see an error as it's not installed though I can remove it successfully $ pip3 install Django==2.1.2 $ django-admin --version Cannot find installed version of python-django or python3-django. Can anybody help me It's very frustrating, ThankYou -
Combine User registration with a custom adhoc form (django-fobi)
I've a user registration form defined as a Class UserCreationForm(forms.UserCreationForm) and I've a custom form defined in the admin of Django-fobi. I would like to create a Django-fobi wizard where the UserCreating form (registration) and the Django-fobi form (adhoc questions) are combined. Any ideas? -
Django admin hide fields and block edit/delete data
In my django project i have to achieve 3 tasks in my admin section: Remove 2 fields in add template Remove the possibility to Delete a record Remove the possibility to Edit a record My model: class suite_libs(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True) descr = models.TextField(null=True, blank=True) docs = models.TextField(null=True, blank=True) lib_name = models.CharField(max_length=255, blank=True) status = models.CharField(max_length=10, default='APPROVAL') f_lib = models.FileField(upload_to='libs/', blank=True) notes = models.TextField(null=True, blank=True) class Meta: verbose_name = 'LIBRARIES' verbose_name_plural = 'LIBRARIES' ordering = ('name', 'lib_name', 'status',) def __str__(self): return '%s -> %s (%s)' % ( str(self.name), str(self.lib_name), str(self.status)) I try this in admin.py: class suite_libsAdmin(admin.ModelAdmin): #1-For hide two fields in add def get_form(self, request, obj=None, **kwargs): if obj.type == "1": self.exclude = ("status", "docs" ) form = super(suite_libsAdmin, self).get_form(request, obj, **kwargs) return form #2-For block deletion get_actions(self, request): actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions #3-For block editing def change_view(self, request, obj=None): from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect return HttpResponseRedirect(reverse('admin:myapp_mymodel_changelist')) ..but nothing appen! No fields hidden, deletion and modification always active. How can i achieve my 3 goals? thanks in advance