Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoCMS cant find templates - TemplateDoesNotExist at /admin/djangocms_blog/post/add/
I installed djangoCMS and djangocms-blog and tried to create my first blog post, but it seems the engine can't render the template for whatever reason. It seems it can't render {{ field.field }} ? Additionally, when trying ot create a new blog post, I can't select any app.config. I did then just click on save and continuing editing what throws the below error. Error log: Error during template rendering In template C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 cms/plugins/widgets/ckeditor.html 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> … -
Postresql Unique constrain isnt triggert
Iam using Django with Postresql. I am trying to create a model with 6 Constrains and 5 of them are working but the UNIQUE constrain somehow dosent get triggert.I looked into the generated Database but to my Eye it looks as intendet... dose some one spot my mistake? Here is the genearted Table: -- auto-generated definition create table permissionentry ( id serial not null constraint permissionentry_pkey primary key, permission_type smallint not null, source_group_id integer constraint permissionentr_source_group_id_19769394_fk_usc references group deferrable initially deferred, source_profile_id integer constraint permissionentr_source_profile_id_54191816_fk_usc references profile deferrable initially deferred, target_group_id integer constraint permissionentr_target_group_id_bb111301_fk_usc references group deferrable initially deferred, target_profile_id integer constraint permissionentr_target_profile_id_e97cadb4_fk_usc references profile deferrable initially deferred, constraint "constrainError.permissionExists" unique (source_profile_id, source_group_id, target_profile_id, target_group_id), constraint "constrainError.onlyOneSource" check (((source_group_id IS NOT NULL) AND (source_profile_id IS NULL)) OR ((source_group_id IS NULL) AND (source_profile_id IS NOT NULL))), constraint "constrainError.onlyOneTarget" check (((target_group_id IS NOT NULL) AND (target_profile_id IS NULL)) OR ((target_group_id IS NULL) AND (target_profile_id IS NOT NULL))), constraint "constrainError.groupsCantBeSupervisor" check ((source_group_id IS NULL) OR ((permission_type > 1) AND (source_group_id IS NOT NULL))) ); alter table permissionentry owner to alamanda; create index permissionentry_source_group_id_19769394 on permissionentry (source_group_id); create index permissionentry_source_profile_id_54191816 on permissionentry (source_profile_id); create index permissionentry_target_group_id_bb111301 on permissionentry (target_group_id); create index permissionentry_target_profile_id_e97cadb4 on permissionentry … -
get total count of each record from another table
hi I have 2 tables like this class Category(models.Model): typeName= models.CharField(max_length=50 , null=False, blank=False ,choices=typeChoice ) typeImage =models.ImageField( blank=True, null=True , upload_to='ActivityType') class Products(Activity): activity = CharField(max_length=50 , null=False, blank=False) typeofproduct = models.ForeignKey(Category , on_delete=models.CASCADE) Now in templates I want to get count of how many total Products are against each Category like I did Category.objects.all() . now for each category how many count for each product in Product table. -
How can I increase or decrease "quantity" of products inside the cart of a ecommerce website in django?
By adding quantity I meant, to increase or decrease the count on the same product, for example, adding 1 cola drink= 50$ and 1 pizza =100$ than adding the same item twice and thrice respectively, the total price will be 2*50 + 3*100 = 400. I haven't applied this logic that I want to have to the backend yet. And I want to be able to save the quantity at the database as well. I tried by adding a cartItem model which you can see commented in models.py section as well. But that too didn't work. Here is my code. Views.py def cart_detail_api_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) products = [{ "id": x.id, "url": x.get_absolute_url(), "name": x.name, "price": x.price, # "image": json.dumps(x.image) } for x in cart_obj.products.all()] cart_data = {"products": products, "subtotal": cart_obj.subtotal, "total": cart_obj.total, "delivery_cost": cart_obj.delivery_cost} return JsonResponse(cart_data) def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added = False else: cart_obj.products.add(product_obj) # cart_obj.products.add(product_id) added = True request.session['cart_items'] = cart_obj.products.count() # return redirect(product_obj.get_absolute_url()) if … -
Heroku Django static files not found
I am getting errors with a Django app on Heroku when referencing static files (e.g. CSS). The files are found when running the site on my local Linux machine, but not when it is deployed on Heroku. I have looked at the Django documentationrelating to static files, but I do not understand what I am doing wrong. django.contrib.staticfiles is included in my INSTALLED_APPS. In my_site/settings.py I have STATIC_URL = '/static/'. In my HTML template I have {% load static %} The result is that the CSS file is found when running locally, but not on Heroku. How can I fix this? I want the simplest possible solution - this is a very small site. # Log message when running the app on the local machine: it is found and has not changed (correct) [13/May/2020 15:02:52] "GET /static/reco/style.css HTTP/1.1" 304 0 # Log message when running the app on Heroku: not found. Why? 2020-05-13T20:09:20.327218+00:00 app[web.1]: Not Found: /static/reco/style.css -
How to format numbers from 1000 to 1k in django
I am working on a project in Django, i have created a template_tags.py files in my project. How do i format numbers from 1000 to 1k, 2000 to 2k, 1000000 to 1m and so on. But i am having an issue with my code, instead of getting 1000 to 1k, i got 1000 to 1.0k. What am i missing in my code? from django import template register = template.Library() @register.filter def shrink_num(value): """ Shrinks number rounding 123456 > 123,5K 123579 > 123,6K 1234567 > 1,2M """ value = str(value) if value.isdigit(): value_int = int(value) if value_int > 1000000: value = "%.1f%s" % (value_int/1000000.00, 'M') else: if value_int > 1000: value = "%.1f%s" % (value_int/1000.0, 'k') return value -
How to "log-maxsize" the uWSGI vassal logger?
i am started uWSGI via supervisord in Emperor Mode to deploy multiple Django Apps in near future. So far i only deployed one App for testing purposes. I would like to seperate the emperor logs from my vassals. So far the loggers work. Except that i can not apply log-maxsize to my vassals logger - thats also applies to my vassals req-logger. [uwsgi] [program:uwsgi] command=uwsgi --master --emperor %(ENV_HOME)s/etc/uwsgi/vassals --logto %(ENV_HOME)s/logs/uwsgi/emperor/emperor.log --log-maxsize 20 --enable-threads --log-master <...autostart etc...> [garden_app] - vassal <...> ; --------- ; # Logger # ; --------- ; diable default req log and set request Log req-logger = file:%(var_logs)/vassal_garden/garden_request.log disable-logging = true log-4xx = true log-5xx = true log-maxsize = 20 ; set app / error Log logger = file:%(var_logs)/vassal_garden/garden_app.log log-maxsize = 20 <...> As you can see i set the log-maxsize very low to see the effects immediately. First of all - all logs working separately. However, while my emperor creates new files (emperor.log.122568) after reaching the log-maxsize my Vassal files still growing above the log-maxsize or in other words nothing happens they don´t create garden_app.log.56513. So my Question is: How to set log-maxsize for my vassals loggers? Applies log-maxsize only to logto? I also tried logto or … -
Best way to make a table with many to many tags in wagtail
I'm recreating a website in wagtail, that has different models like AnimalDetailPage and PlantDetailPage , both share the same field, "needed supply", since some supplies are needed by both. Admin-user must be able to go to "table" page settings and change "store link" for each "needed supply", but I'd also like the admin-user to be able to add New supplies (along with the store so the table is updated automatically) when adding an animal or a plant, but for such field to be as functional and pretty as regular wagtail tag field. I don't know if that's possible, so maybe there's other way to create a comfortably-admined table like on the picture ? THIS and THIS is my related questions. -
Can We create Micro-services in Django like Spring boot?
Hi I'm new to Django . I want to create a website using Django(Backend) that can service my Website, Android/IOS and other platform as well . I just want to Know is there any way i can create a website backend like Micro-services architecture in Spring boot Rest. If Yes, please also provide the tools for creating that will be very helpful and really appreciated . If No , Please enlighten me little bit how to create in Django or how people usually create in Django. Thank you in advance , For your response -
Django Grapelli datepicker with JQMigrate error
I have a Django APP with Grapelli for the backend UI. The datepicker widget sudenly stopped working correctly. It displays everything but when I choose a date I get the following error in the console: jquery-migrate-3.0.1.min.js:140 Uncaught TypeError: e.event.addProp is not a function at Object.e.event.fix (jquery-migrate-3.0.1.min.js:140) at HTMLDivElement.dispatch (jquery.min.js:3) at HTMLDivElement.r.handle (jquery.min.js:3) e.event.fix @ jquery-migrate-3.0.1.min.js:140 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3 Searching a bit I found some related isuse being solved downgrading JQMigrate to verión 1.4: https://github.com/jquery/jquery-migrate/issues/266 How can I change the used version in Django Grapelli? Or any other suggestion? Thanks in advance. -
Split payment among multiple users in a subscription with Stripe
I am trying to develop a Subscription Box website where the user can split the cost of subscription with their friends. For example: User A adds subscription box to cart, and is given the total amount (e.g. $20). They then are asked how many people they want to split the cost with (e.g. split with 2 more people) They enter their card details / bank details or perhaps initialize a direct debit They are then given a link to share with their friends that want to split the payment with them. User B clicks this link and enters their details User C clicks this link and enters their details too Now that two more people have joined and agreed to share the cost, they are each charged ~$6.66 per month ($20 / 3 ) Stripe does not offer this solution natively, which is why I want to custom build it. Has anyone seen anything similar to this, or seen a library which implements anything of the kind? I am aware Paypal has a Split function for some websites but this does not seem to be available by an API I am planning to build the system within Django but that … -
Django Rest Framework+React JS ,unable to implement form parser (error: The submitted data was not a file. Check the encoding type on the form.)
When I submit a form from react frontend with images server responds "The submitted data was not a file. Check the encoding type on the form.". When I use Django RF browsable API I can successfully add images. Will this be a problem from frontend then ? VIEWS.PY class PostListCreateview(generics.ListCreateAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] parser_class = (FileUploadParser,) def perform_create(self, serializer): serializer.save(author=self.request.user) The Post model accepts title,body and pic as parameters from the form POST methods. REACT FRONTEND const [image,setImage] = useState(null) const handlesubmit =()=>{ let endpoint = `/api/post/`; apiService(endpoint,'POST',{title:title,body:body,pic:image}).then(data=> console.log(data))}; return (<input type="file" onChange={(e)=>setImage(e.target.files[0])}/> <Button onClick={handlesubmit} >Upload</Button>) -
signin to access GMAIL API with Django
I´m trying to buil a Django app where I download all E-Mails in a specific GMAIL Account. If I execute with python I dont have any issues, but when I implement it in my Django Project it Fails with the following exception: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/communication/mailingsystem/ Django Version: 3.0.4 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scraper', 'mailingsystem', 'reports'] Installed 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'] Traceback (most recent call last): File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\usr\PycharmProjects\isd\InfoSys-Dev\mailingsystem\views.py", line 21, in mailList service = logon() File "C:\Users\usr\PycharmProjects\isd\InfoSys-Dev\mailingsystem\mailCoresystem.py", line 33, in logon flow = InstalledAppFlow.from_client_secrets_file(static('credentials.json'), SCOPES) File "C:\Program Files\Python38\lib\site-packages\google_auth_oauthlib\flow.py", line 196, in from_client_secrets_file with open(client_secrets_file, 'r') as json_file: Exception Type: TypeError at /communication/mailingsystem/ Exception Value: expected str, bytes or os.PathLike object, not dict The Thing is that I Need to pass the json file with the credentials but it Fails due to the fact its a dict my view:` def mailList(httprequest, *args, **kwargs): service = logon() messages = ListMessagesMatchingQuery(service, 'me', query='after:1504748301 from:-me') allMails = … -
Like button by Django + Ajax
''' views.py, This is for simple like/dislike. How can i make it without loading. ''' def like_post(request, slug): like = get_object_or_404(BlogSlider, slug=slug) print(like) if like.likes.filter(id=request.user.id).exists(): like.likes.remove(request.user) else: like.likes.add(request.user) return redirect('blog-details', slug=slug) ''' html ''' <form method="POST" action="{{ detail.get_like_url }}"> {% csrf_token %} <button type="submit"><span class="align-middle mr-2"><i class="ti-heart"></i></span></button> </form> -
Getting django.db.utils.OperationalError: sub-select returns 11 columns - expected 1 when trying to add an object to a m2m field
I am new to django rest framework, and I am trying to build api for a todo app using which i can add collaborator to a todo my todo model is as follows: class Todo(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) collaborators = models.ManyToManyField(User,related_name='collaborators') def __str__(self): return self.title Serializer.py class TodoCreateSerializer(serializers.ModelSerializer): def save(self, **kwargs): data = self.validated_data user = self.context['request'].user title = data['title'] todo = Todo.objects.create(creator=user, title=title) return todo class Meta: model = Todo fields = ('id', 'title',) class UserObjectSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class TodoSerializer(serializers.ModelSerializer): collaborators = UserObjectSerializer(many=True, required = False) class Meta: model = Todo fields = ['id', 'title', 'collaborators'] class CollaboratorSerializer(serializers.ModelSerializer): collaborators = UserObjectSerializer(many=True) class Meta: model = Todo fields = ['collaborators'] and when i try to add collaborator object to my collaborator field using the following method in the viewset class CollaboratorViewSet(viewsets.ModelViewSet): serializer_class = CollaboratorSerializer queryset=Todo.objects.all() @action(methods=['put'], detail=True, permission_classes=[permissions.IsAuthenticated, ], url_path='add-collaborator', url_name='add_collaborator') def add_collaborator(self, request, pk=None): try: todo = Todo.objects.get(pk=pk) except Exception: return Response({'Error':'Invalid Id'}) else: if request.user == todo.creator: try: collborators = request.data["collaborators"] except KeyError: return Response({'Error':'Collaborator field not specified in request'}, status = status.HTTP_400_BAD_REQUEST) else: collab_list = [] for collab in collborators: try: collab_name = collab['username'] except KeyError: return … -
Django-Rest | Create a new object and immediately assign it to parent object's M2M field
Not sure if Django-Rest is the best way to do this, though I have two models: class Client(models.Model): name = models.CharField(max_length=500) userassigned = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) property = models.ManyToManyField('Property', blank=True) def __str__(self): return self.name class Property(models.Model): address = models.CharField(max_length=500, blank = True) I want to create a Property object through a POST method through the ID of a Client object. So for instance, if I have the ID number of Client "Amazon", I want to use that ID number to first create that new Property object, then assign it to the "Amazon" property M2M field. Is this possible? How would I go about doing this with one POST method? Thanks in advance! -
Card() got an unexpected keyword argument 'initial'
I'm putting together a CRUD interface without using the admin app, still pretty new to Python and Django, but when I go to create an entry, it throws out the error in my title. here's the target page: <form method="post"> {% csrf_token %} Card Name:<br> <input type="text" name="name"><br> Mana Cost:<br> <input type="text" name="mana_cost"><br> Supertype:<br> <input type="text" name="supertype"><br> Keyword 1:<br> <input type="text" name="keyword_1"><br> Keyword 2:<br> <input type="text" name="keyword_2"><br> Keyword 3:<br> <input type="text" name="keyword_3"><br> Rules Text:<br> <input type="text" name="rules_text"><br> Power & Toughness:<br> <input type="text" name="power_toughness"><br> <input type="submit" value="Add Card"><br> {% endblock %} my views.py: from task99_app import forms from django.views.generic import ListView from django.views.generic import DetailView from django.views.generic.edit import CreateView from django.views.generic.edit import UpdateView from django.views.generic.edit import DeleteView from .models import Card # Create your views here. def home(request): return render(request, 'home.html') class CardList(ListView): model = Card class CardCreate(CreateView): form_class = Card class CardDetail(DetailView): model = Card class CardUpdate(UpdateView): model = Card class CardDelete(DeleteView): model = Card my forms.py: from django import forms class CardForm(forms.ModelForm): name = forms.CharField(max_length=80) mana_cost = forms.CharField(max_length=12) supertype = forms.CharField(max_length=30) keyword_1 = forms.CharField(max_length=20) keyword_2 = forms.CharField(max_length=20) keyword_3 = forms.CharField(max_length=20) rules_text = forms.CharField(max_length=500) power_toughness = forms.CharField(max_length=10) and my models.py: from django import forms class CardForm(forms.ModelForm): name = forms.CharField(max_length=80) mana_cost … -
Django print runserver log to a file
I'm running a django application inside a container using supervisord. But sometimes i need to view the log to fix some errors and i could'nt find a way to do it. I tried to add an stdout_logfile and stderr_logfile but always the err logfile is empty this is my supervisor.conf [supervisord] loglevel=info logfile=/tmp/supervisord.log [program:myapp] command = python3 -u /usr/src/app/manage.py runserver 0.0.0.0:8000 stdout_logfile=/usr/src/app/out.log stderr_logfile=/usr/src/app/err.log And always the same result, the out.log file will contain the lines before the exception happen and the err.log won't be created This is the output that i get when i run docker compose 2020-05-13 17:33:44,140 INFO supervisord started with pid 1 2020-05-13 17:33:45,144 INFO spawned: 'myapp' with pid 9 2020-05-13 17:33:46,201 INFO success: myapp entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) -
'NoneType' object has no attribute 'price'
class ShopCart(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Food = models.ForeignKey(food, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() def __str__(self): return self.Food @property def amount(self): return (self.quantity * self.Food.price) #adminde göstermek için tutar @property def price(self): return (self.Food.price) models.py class food(models.Model): STATUS = ( ('True', 'Evet'), ('False', 'Hayır'), ) category = models.ForeignKey(Category, on_delete=models.CASCADE) #Category modeli ile ilişkili title = models.CharField(max_length=150) keywords = models.CharField(blank=True,max_length=255) description = models.CharField(blank=True,max_length=255) image = models.ImageField(blank=True, upload_to='images/') price = models.FloatField() amount = models.IntegerField() #miktar detail = RichTextUploadingField() slug = models.SlugField(null=False, unique=True) status = models.CharField(max_length=10, choices=STATUS) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title admin.py class ShopCartAdmin(admin.ModelAdmin): list_display = ['user','Food','price','quantity','amount'] list_filter = ['user'] admin.site.register(ShopCart,ShopCartAdmin) I got the error when try to entering admin.py. You guys can you help me please? -
Send a notification to my users from Django admin panel
i'm working on a Django project as a backend for a mobile app, I've a requirement that the admin want to send app notification to selected users from the admin panel when the he create a notification object in the admin panel the admin select some users or all users and type the message , he want to send a notification to the selected users when he click on save. any help ? models.py class CustomNotification(models.Model): user = models.ManyToManyField('User', blank=True, null=True) title = models.CharField(max_length=200) text = models.TextField() def save(self, *args, **kwargs): super(CustomNotification, self).save(*args, **kwargs) from services.NotificationService import notify_multiple_users notify_multiple_users(sender, instance.user, "notification_type", instance.title, instance.body) firebaseNotification.py def notify_multiple_users(notifier, notified_qs, notification_type, title, body, object_id=None, is_read=False): how to get the current selected users and title and text and use them in def notify_multiple_users -
additional fields associated with wagtail tags?
I'm creating wagtail website that copies and adds to the functionality of old django website: there is a blog-like "animal-listing" and "plant-listing" pages with post-detail-like "animal detail" and "plant detail" pages. They share a common "need" tag via simple ManyToManyField, because animals and plants have some of the same needs (like water or hay). Need tags are displayed on the "needs page" table, which has columns like "store link". This original solution weren't as smooth as autocomplete tag fields in wagtail so I'm trying to recreate the same thing in wagtail, but I don't know how to link wagtail's TaggableManager/TagItemBase to a separate model and make it have fields like "item link". I also have no idea how to make wagtail tag field give user a popup every time a non-existing tag is added (this was old django implementation, see the picture below). Here's the original django models.py from django.db import models from django.contrib.auth.models import User class Animal(models.Model): name = models.CharField(max_length=100) picture = models.ImageField(upload_to='./media/pictures-animals/', null=True, blank=True, default=None) description = models.TextField(max_length=10000) adoption_reason = models.TextField(max_length=1000) needs = models.ManyToManyField('Need', related_name='animals') def __str__(self): return f'{self.name}' class Plant(models.Model): species = models.CharField(max_length=100) picture = models.ImageField(upload_to='./media/pictures-plants/', null=True, blank=True, default=None) description = models.TextField(max_length=10000) needs = models.ManyToManyField('Need', related_name='plants') entry_date … -
What would be the best way to achieve this end goal in Wagtail?
What I want to create is a website where I can transcribe my current grimoire. I want my friends/others to be able to create accounts and 'bookmark' favorite pages to personal lists [I already know how to do this part] The part I need direction on is that my grimoire is an ongoing project that I'm constantly adding new content to. It's organized into sections, and the sections have subsections, chapters, and subchapters. Entries can exist under any of these 4 areas. I want to be able to select where in the structure an entry goes when I am creating it. As for the frontend, I want to have a main 'Table of Contents' page that displays the hierarchy, with users being able to navigate to whatever information they want to see entries for, IE - if they click on "Section 3 - Correspondences", then I want to only show entries that fall under Section 3's subsections, chapters, and subchapters, and not show all content marked as a subchapter. I've looked at everything I can find regarding book models, categories, tags, 'topic'-style mp_nodes, and I keep ending up confused. I don't expect to find something that directly matches my needs, … -
Django model inheritance - How to set value for parent attribute
Having two models, parent and child, I want to set the value of one of the attributes the child inherits. For example, in the following code the color attribute would be set when creating a RedCat object. # Parent class class Cat(models.Model): name = models.CharField(max_length=10) color = models.CharField(max_length=10) # Child class class RedCat(Cat): color = 'red' # <-- Doesn't work! I'm considering either overriding the parent attribute or having the attribute only on the children, but I wonder, is there a right/better way to set a default value in a Django model for an inherited attribute? -
Setting up Virtual Environment for Django in python
enter image description here please help python3 -m venv venv -
Django slow performance on processing requests
I have a django platform and I've found a strange slow performance when the server tries to response some http requests. I've managed to isolate a little useless code that shows a strange delay, from which all the others can be derived. case 1) If I have this function: def get_n_events(request): a = request.user return HttpResponse("5") the response is very fast, as expected: Only 12.61ms, very fast, as expected. case 2) But if I have this function: def get_n_events(request): a = request.user.username return HttpResponse("5") the response: it takes more than 2 seconds! How can be this delay explained and how can I avoid this huge time when I need to access the data inside the request? (For example, in my case I need to know the request.user.group_name, but it takes too much tome to get a response.