Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count model field with multiple values divided by comma
I have a Django model with a TAG value, and I want to count how many types of tags my user has. My Content (with tags): class Content(models.Model): tags = models.CharField(max_length=1000, null=False) My Profile(user): class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) My User's interactions: class UserInteraction(models.Model): profile = models.ForeignKey(Profile) content = models.ForeignKey(Content) The final representation would be something like this: { "user": 1, "userinteraction_set": [ { "id": 1, "content": { "tags": "love, comedy", }, }, { "id": 2, "content": { "tags": "love, comedy", }, }, { "id": 3, "content": { "tags": "love, order, medical", }, } ] } And I want the result to be: {"love":"3","comedy":"2","order":"1","medical":"1"} My first idea was to make a function and iterate over the queryset, split the tags and then return the dictionary with the final result, but maybe there is something easier that could be done using the aggregations. Any help is appreciated. -
how can i add new field in model when i have datamigration befor django python?
I have a migrations come from the work of another person, and I'm in on a code base controlled by the version too. I created a migration file after adding a new field but the problem is in the data migration (0003_datamigration_initial_service_configuration.py)that is created before through the function get_or_create () is executed in the head of the list while my migration file data in the end I should not change a migration already developed this is my list of migration 0001_initial.py 0002_datamigration_initial_users_list.py 0003_datamigration_initial_service_configuration.py ... 0015.addnewfield 0003_datamigration_initial_service_configuration.py: from __future__ import unicode_literals from django.db import migrations from ..models import ServiceGlobalConfiguration ## Create initial service configuration def create_initial_configuration_forward(apps, schema_editor): current_product_type, created = ServiceGlobalConfiguration.objects.get_or_create() class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_datamigration_initial_users_list'), ] operations = [ migrations.RunPython(create_initial_configuration_forward), ] the error is no such columun named new_field how can i fixed the probleme without edit any datamigration ? -
I cant link my ccs to htlm
body{ background-image:url(honey.jpg); } ul{ margin:0px; padding:0px; } ul li a{ text-decoration:none; color:white; display: block; } ul li{ float:left; width: 150px; height: 40px; background-color: black; font-size:15px; line-height:40px; text-align: center; opacity: .7; border:1px solid #285189; } ul li a:hover{ background-color: orange; } ul li ul li{ display: none; } ul li:hover ul li{ display: block; } <!DOCTYPE html> <html lang="en"> <html> <head> <title></title> <link rel="stylesheet" href="css/style.css"> </head> <body> <div> <ul> <li><a href="#">Home</a></li> <li><a href="#">Pcelinje drustvo</a> <ul> </ul> </li> <li><a href="#">Tipovi kosnica</a><ul> <li><a href="#">Db</a></li> <ul> <li><a href="#">Lr</a></li> </ul> </ul> </li> <li><a href="#">Tehnike pcelarenja</a></li> </ul> </div> </body> </html> I tried many things by looking at this site, but I could not find one thing. When i try to use this code in my django project, django cant found css. I am new in this and I am very trying to do this right. I apologize for my bad English. Please help me. -
TypeError: expected string or bytes-like object User.id
I'm trying to register an new Transaction object on the DB using Django, but I'm having TypeError: expected string or bytes-like object when I try to do -
Wagtail template not loading
I'm trying to set up a small Wagtail blog, it's inside of an existing Django project. I've tried following the official wagtail documentation but I'm failing to view my template, instead I'm greeted with "Welcome to your new Wagtail site!" The tree for my blog app looks like this blog ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20171121_0949.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ ├── 0002_auto_20171121_0949.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ ├── models.cpython-36.pyc │ └── urls.cpython-36.pyc ├── templates │ └── blog │ └── blog_page.html ├── tests.py ├── urls.py └── views.py All the other files I refrence here are from this tree. The models.py looks like this from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class BlogPage(Page): intro = RichTextField(blank=True) body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ] urls.py from model app from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailcore import urls as wagtail_urls from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^cms/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), #from /blog is where our … -
Django Admin custom template, using change_list.html inside index.html
I am new in Django framework. In my customisation of Django admin templates. I need to use admin/change_list.html inside admin/index.html. When a particular model is clicked in admin/index.html instead of redirecting to admin/change_list.html it should appear inside index.html itself. As in the image. In this image. "Manage Category", "Manage Products" etc are models when user click on a particular model, on the right-hand side as shown in the image its rows should be displayed. Admin_image Please provide solutions. Thank you. -
'NoneType' object has no attribute 'has_header'
I try to redirect user after "Save" button is pressed on some model. I use this in admin.py: class ArticleAdmin(admin.ModelAdmin): def response_change(self, request, object, form_url=''): if(object.state == 1): return redirect('/admin/prj/data/add/?info_id=' + str(object.info_id)) else: return redirect('/admin/prj/article/') admin.site.register(Article, ArticleAdmin) But this returns 'NoneType' object has no attribute 'has_header', even first time - using only if(object.state == 1): worked. This isn't the case anymore, it doesn't work even without else condition. -
Why this viewset is instant while this one is very slow
My first viewset: class BienAll(generics.ListAPIView): queryset = FacebookBien.objects pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): requete = self.queryset.all() serializer = FacebookBienSerializer(requete, many=True) # noqa page = self.paginate_queryset(serializer.data) return self.get_paginated_response(page) My second viewset: class Test(generics.ListAPIView): queryset = FacebookBien.objects.all() pagination_class = SmallPagesPagination serializer_class = FacebookBienSerializer My second viewset is instant but my first is slow, i don't understand why. -
Django + Angular4?
I'm on a project where I have to combine Django (not DRF) and Angular4. I would like to know where I have to integrate my angular app into my django project and if I have to apply modifications ? And by the way is it possible to use Django with Angular4 without using an DRF API ? Thank you in advance. -
I am trying to install Django for python but it gives an error
Good morning! I am trying to install Django but it keeps appearing me an error like "Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [WinError 10013] Foi feita uma tentativa de acesso a uma socket de uma maneira que é proibida pelas permissões de acesso',)': /simple/django/ and then Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django Have some suggestion? -
UnicodeDecodeError in Django Project
I've imported Django Project from github and now I have a file db.sqlite with a stange coding: I've tried to delete this file and generate the new one using "python manage.py migrate" but new generated file has the same problem. I get UnicodeDecodeError. Rather that's why I can't open the server. I use PyCharm and Python 3.6.3. Thank you in advance for your help -
django - cannot login after create custom user model
I created my own user model and usermanager model. Then I tried to create a supersuser and get "Superuser created successfully." However, when i tried to login with all the info, it failed. Then I added a line of code to print my password while creating. The result matches my passwrod.I am pretty sure the server is using the custom model because: the required fields changes accroding to my code if I remove one necessary field from the required fields, I get an error about "TypeError: create_superuser() missing 1 required positional argument:" which is expected Here is my code: class UserManager(BaseUserManager): def create_user(self, username,email,password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.username = username user_obj.save(using=self.db) return user_obj def create_superuser(self, username, email, password): print("Super user created, with password" + password) return self.create_user( username=username, email=email, password=password, ) class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) email = models.EmailField(blank=True, unique=True) created_time = models.TimeField(auto_now=True) active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() I really appreciate if anybody can give me any idea. Totally get lost. -
Django rest framework - simple example of a view supporting all CRUD operations
I am a newbie to Django REST Framework. I would like to create a view which supports creating a new entity (POST), list all entities (GET), update an existing entity (PUT) and deleting an entity (DELETE). I already managed to create a working solution, but I feel that what I made is not a good practice. Therefore, I present a clean code (at least I hope so) which supports GET and POST and would like to ask you for help with extending it. serializers.py from rest_framework.serializers import ModelSerializer from app.models import Test class TestSerializer(ModelSerializer): class Meta: model = Test fields = "__all__" views.py from rest_framework.viewsets import ModelViewSet from app.models import Test from app.serializers import TestSerializer class TestViewSet(ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer urls.py from rest_framework.routers import DefaultRouter from app.views import TestViewSet router = DefaultRouter() router.register(r'test', TestViewSet, base_name='test') urlpatterns = [ url(r'^admin/', admin.site.urls), ] + router.urls -
"Not allowed to load local resource: file:///.." error after paste image from word into froala editor on chrome with django framework
When i paste froala editor copy image from word, chrome throw "Not allowed to load local resource: file:///.." error. But when i click this link, chrome can show image. my froala editor setting: width: '100%', height: '500px', saveInterval: 0, spellcheck: false, pasteAllowLocalImages: true, imagePaste: true, wordPasteModal: true, imagePasteProcess: true, toolbarButtons: ['fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', '|', 'fontFamily', 'fontSize', 'color', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', '|', 'emoticons', 'specialCharacters', 'insertHR', 'selectAll', 'clearFormatting', '|', 'print', 'help', 'html', '|', 'undo', 'redo'], pluginsEnabled: null, imageManagerPreloader: "{% static 'home/img/loader.gif' %}", imageManagerPageSize: 20, imageManagerScrollOffset: 10, imageManagerLoadURL: "{{ session.get_load_image_url }}", imageManagerLoadMethod: "GET", imageManagerDeleteURL: "{{ session.get_image_delete_url }}", imageManagerDeleteMethod: "POST" How to solve this problem ? -
Automatically assign User to user group after register/sign up form submission - Django
I am relatively new to Django, and web development in general. I'm trying to build a website with two types of users, customers, and suppliers. I need to be able to show these two types of customers different things on the website. For example, different links in the header section for the suppliers. I am under the impression the best way to do this is to create two user groups ('suppliers' and 'customers') in my /admin, create two different sign up forms (one for suppliers and one for customers), and send each to their respective user group on sign up form submission. From there I can decide what the user sees based on their user group. Correct? Unfortunately, I'm nearly at my wits end with this! I've created the user groups, created the different sign-up forms, but for the last 2 days I have been trying to figure out how to send the signups to their respective group and I just can't manage to do it! I've searched high and low and tried every suggested line of code I could find: no luck. Most of the stuff I have tried is along these lines: views.py from __future__ import unicode_literals from … -
filter in Json field
in my DB, I want to store IDs which are in an Array List. so I convert Array List as a String by using json.dumps(id_list). in retrieve, I send an ID, It should check this id exists in String which I converted from the array list. it should retrieve data if the only ID exists on String. Could anyone suggest any way to retrieve data filter by given ID -
compare two rows on the google spreadsheet django
I have a problem on right now.I have a google spreadsheet that is responses of the questionnaire.I want to count how many men score points(5,4,3,2,1 points) for the traffic of this place and so do women.like this. How can I do ?By the way I used google api on django #All responses save in data data = pd.DataFrame(sheet.get_all_records()) #get data of traffic data['trafic'] #['5','4','3','4','2'] #get data of gender data['gender'] #['woman','man','woman','woman','man'] -
How create queryset to custom fields?
I have 2 custom fields as in the picture below in my form. When user make GET request, in the right list I want to show user's permissions. In the left list I want to show available permissions which is not yet in right list. How to make correct queryset to my custom fields? I am confused. Thats how I think I need to take create queryset to available_permissions field. Pseudo-code: for available_permission in Permission.objects.all() if available_permission not in (QuerySet <user_permissions>) Create new QuerySet with available_permission 1) How to know User's permisssions? I think here I need to send user id from view to form. 2) How create Empty queryset and add objects to that queryset? forms.py: class UserEditForm(UserChangeForm): available_permissions = forms.ModelMultipleChoiceField( widget=forms.SelectMultiple, queryset=???, required=False, ) current_permissions = forms.ModelMultipleChoiceField( widget=forms.SelectMultiple, queryset=???, required=False, ) views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User def get(self, request, *args, **kwargs): user = User.objects.get(pk=self.kwargs['pk']) *** -
Multiple Choice ModelChoiceField
I need a ModelChoiceField where multiple choices can be selected. For example, Device x should be able to use Device y and Device z. my form: class DeviceForm(models.ModelForm): uses = forms.ModelChoiceField(queryset = Device.objects.none(), required = False) .... def __init__(self, *args, **kwargs): #if device is edited if kwargs["instance"]: self.fields['uses'].queryset = Device.objects.filter(used_in = None, trashed = None).exclude(pk = kwargs["instance"].id) #if device is created else: self.fields['uses'].queryset = Device.objects.filter(used_in = None, trashed = None) If I use the form like that, I am able to select multiple Devices via uses, but I can't unset them anymore. I think I need a field where it is possible to tick/untick the used Devices but I didn't find such a field anywhere... I already thought of using a simple ChoiceField, but much of my code is based on the assumption that this form gets a model object with a pk etc. -
Practice to call a function inside itself
I have parent/child relation with tables. Looks like this. class Person(models.Model): Name = models.CharField() class ParentChild(models.Model): child = models.ForeignKey('Person', related_name='child') parent = models.ForeignKey('Person', related_name='parent') validfrom = models.DateTimeField(blank=True, null=True) validto = models.DateTimeField(blank=True, null=True) I am trying to query a whole tree and create a json to send to template. So for each person I'm thinking of using a function to query the children, and for each children use same function to query if that child has any children. So this is my function def getChildren(parentID): try: children = Person.objects.filter(parent=parentID) addJson = 'children: [' for a in children: addJson = addJson + '{text: { name: "Child '+str(a.id)+'" }},' getChildren(str(a.id)) return addJson except: return addJson This only gets me one child then nothing more. So I'm guessing it's not possible to invoke itself, or maybe a function have to finish before being called again. I'm pretty stuck right now. Ideas are much welcome! -
Using formfield_overrides to change textarea size in admin.TabularInline Form in Django
TextField size is overridden using formfield_overrides: from django.forms import Textarea, TextInput formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':25})}, } This works on the parent form TextFields. Any related child model rendered using admin.TabularInline still shows TextArea with default size. Notes TextArea in main Model and Inline related Model Is there a way to change TextArea size of a model rendered using admin.TabularInline class? -
i am not able to use my models.py data in views.py that I want to display in as html
my models.py from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=1000) Status =models.CharField(max_length=1000,blank=True, null=True) def __str__(self): return self.name views.py from django.shortcuts import render from django.template.response import TemplateResponse from Core.models import Customer def user_profile(request): data = Customer.objects.all() return render_to_response(request,"templates/home.html", {"data": data}) home.html {% extends 'base.html' %} {% block title %}Video Page {% endblock %} {% block content %} {% for customer in data %} <h1> {{ customer.name}}</h1> {% endfor %} <h1>check</h1> {% endblock %} when I open the django app and view the site check is visible but nothing from my model is printed I want to display the data that I have stored in the customers model in the html file -
annotating a field from a related table based on another field on that table
let's say I have two tables "Publisher" and "Book". Book is related to Publisher via Foreign-Key. To be able to reach book from publisher there is a related_name="Book" in Book model. How could I annotate date of a particular book to my query of publisher based on another field such as price of book? What is in my mind is something like: Publisher.objects.annotate( particular_date = F('Book__date' for which the price=150$) ).all() I hope I was able to deliver the idea. -
Python Paypal REST SDK Integration issue
I am using Python 3.6 and Django 1.11 for a project. I am using paypalrestsdk 1.13.1(Paypal REST SDK) package for Paypal Integration. I have been following the steps provided in - https://github.com/paypal/PayPal-Python-SDK and https://developer.paypal.com/docs/api/quickstart/payments/ Following is my view.py def donateThroughPaypal(request): context = locals() approval_url = "" redirect_url = "" if request.method == 'POST': paypalrestsdk.configure({ 'mode': 'sandbox', #sandbox or live 'client_id': '<client_id>', 'client_secret': '<client_secret>' }) payment = Payment({"intent": "sale", # Set payment method "payer": {"payment_method": "paypal"}, # Set redirect urls "redirect_urls": {"return_url": "http://localhost:8000/Return.html", "cancel_url": "http://localhost:8000/Cancel.html"}, # Set transaction object "transactions": [{"amount": {"total": "10.00","currency": "USD"}, "description": "transaction payment description"}]}) if payment.create(): for link in payment.links: if link.rel == "approval_url": approval_url = str(link.href) if link.method == "REDIRECT": redirect_url = str(link.href) return HttpResponseRedirect(approval_url) else: print(payment.error) template = 'donate/donate.html' return render(request,template,context) So the line return HttpResponseRedirect(approval_url) redirects me to Paypal login page. However, when I login into sandbox with buyer account, Paypal responds with - Return to Merchant and this redirects to cancel_url. I am successfully getting the token=EC-XXXXXXXXXXXXXXXXX and payment_id=PAY-XXXXXXXXXXXXXXXXXXXXXXXX. Please assist. Let me know if I am missing any setup. -
Django REST Framework + Vue js session_key problems
Currently, i'm working om my web app, and i have two dev server separately; django is on localhost:8000, and vue is on localhost:8080. I'm using cors-headers for django to get axios-requests from Vue devserver. But i have a problem: it seems, that django session doesnt save a session key on vue dev server, so i literally cant login/get user info/etc on my vue js dev server. Is there any way how to solve the problem without merging both servers on django platform?