Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Make Iterator for do sum of a field from n number of objects
Lets say i have a model class Testmodel(): amount = models.IntegerField(null=True) contact = models.charfiled() Now I am making a query like: obj1 = Testmodel.objects.filter(contact = 123) and suppose its returning n number objects in any case like (obj1,obj2,obj3 ...) So, if I want to make the sum of amount from all the returning object (obj1,obj2,obj3 ...) then how to do by the best way. any help will be appreciated. -
Global queue on server side
Is there any way to create a global queue (A Data Structure) which hold the data and can be called with server-side frameworks such as django? -
ModuleNotFoundError with django
I want to use some fuctions from the other python files in my view context. In myapp I have created folder named "code" and inside this i have a file named "examplee.py". I try to import it like this views.py: views.py: from django.shortcuts import render from django.views import View # Create your views here. import sys sys.path.append('./code') import examplee as expl class CmtGraphTool(View): def get(self, request, *args, **kwargs): list = expl.test1() context = {list} return render(request, "cmtgraphtool.html", context) and the examplee.py contains a simple function that returns a list of elements. The problem is that when i try to import and use the fuction test1 in my view then Spyder(my development enviroment) can see that function, but when i try to run django server by python manage.py runserver, it raises an error: ModuleNotFoundError: No module named 'examplee' How to include fuctions from the other files in a way that django can see them? Thanks;) -
Showing related items to the same model on detail page
I'm working on the News model. I have a list page and a detail page. I need on the detail page with the option of selecting other related news in the admin panel and saving them on the site. My model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link = models.ForeignKey('.'.join(LINK_MODEL), null=True, blank=True) link_title = models.CharField(max_length=500) date = models.DateField(null=True) image = FilerImageField() class Meta: verbose_name_plural = 'news' ordering = ['-date'] Should I use a foreign key? Please suggest any hint in this case. Thank you. -
How to follow Django redirect using django-pytest?
In setting up a ArchiveIndexView in Django I am able to successfully display a list of items in a model by navigating to the page myself. When going to write the test in pytest to verify navigating to the page "checklist_GTD/archive/" succeeds, the test fails with the message: > assert response.status_code == 200 E assert 301 == 200 E + where 301 = <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/checklist_GTD/archive/">.status_code test_archive.py:4: AssertionError I understand there is a way to follow the request to get the final status_code. Can someone help me with how this done in pytest-django, similar to this question? The documentation on pytest-django does not have anything on redirects. Thanks. -
Django, DRY: How to use fields define in multiple model in a single modelform?
Is there a way of not duplicating fields between models and forms, where there are multiple models' fields within a single form? Please keep in mind this example so it can help keep my question clear. class Tree(Model): COLOUR = [(1, 'green'), (2, 'red')] tree_name = CharField() leaf_colour = CharField(choices=COLOUR) class Pool(Model): size = IntegerField() class Garden(Model): maintains_cost = IntegerField() I would like all my models to be in one form, however, I would like to be more DRY about it. Is there a way of using the fields from the models above? class MyGardenForm(ModelForm): tree_name = CharField() leaf_colour = ChoiceField(choice=Tree.COLOUR) size_pool = IntegerField() class Meta: model = Garden fields = ['maintains_cost'] # how this is saved and anything beyond this point is beyond the scope of this question, so I am omitting. As you can see tree_name, leaf_colour, and (pool_)size are all 'duplicated', and given Django being focused on DRY, there must be a way of avoiding this. I have seen Model_Name._meta.get_field(field_name) from here. But I can not seem to figure it out how to use it. Thank you for your time. -
Django Models acting like a dictionnary with double foreign key
i'm new in django. In my project i have so far an app with a student model. Model's fields are name grades (ie math, english....) and comments. This is working just fine. Now i need to add after school activities (ie football, dance, guitar....) The problem starts here, i need to do a model for the activity witch acte like a python dict, activity is the dict, student is the key and hours spend in the activity are the values. It is typicly a M2M relation: an activity has several students, and a student can be in several activities with a different amount of participation in each one. in stackoverflow i've found this answer: How to store a dictionary on a Django Model? witch is realy close but not there yet. I tried different options. Right now i have this: in studentapp.models: class Student(models.Model): nom = models.CharField(max_length=50, blank=True) #grades are all integer fields commentaires = models.TextField(max_length=250, blank=True) class Edudient(models.Model): #frensh for student BTW nom = models.OneToOneField(Etudient, db_index=True, on_delete=True) hours = models.IntegerField(default=0) in activity.models: class Activity(models.Model): nom = models.CharField(max_length=50, help_text="exemple: 'Activity football'") def __str__(self): return self.nom class WhoIsActive(models.Model): activity = models.ForeignKey(Activity, db_index=True, on_delete=True) who = models.ForeignKey(Etudient, db_index=True, on_delete=True) def __str__(self): return … -
Access to my app through django-oidc-provider-0.5.x
so I have this application (which server is on localhost:8000 port), also there is the django-oidc-provider (which server is on localhost:3000). If i go on myapp I'm redirected on django's login page (thing that I want), but after that, I really don't know how to say to myapp 'hey! this is the access_token, decrypt it and make that the user can access to myapp!' any idea? Note: I'm new on python and django -
IndexError: list index out of range, django-allauth
What I am trying to do? I am trying to access the data from the social account and storing it in my Profile model. And I am following this site to get the user data but i am failing to get the data. What is the problem? I getting the following error after successfully logged in to my facebook account: Error: IndexError at /accounts/facebook/login/callback/ list index out of range Looking it up on the internet I saw this post and tried to implement it but that gave a keyerror 'user'. My Code: adaptar.py: from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.socialaccount.models import SocialAccount class CustomAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): account_uid = SocialAccount.objects.filter(user_id=request.user.id, provider='facebook') print account_uid[0].extra_data['username'] settings.py: SOCIALACCOUNT_ADAPTER = 'Authentication.adapter.CustomAdapter' models.py: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) likedArticles = models.PositiveIntegerField(default=0) sharedArticles = models.PositiveIntegerField(default=0) avatar_url = models.CharField(max_length=256, blank=True, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
django 2.0 image not rendered
So I am trying to display an image on the index.html file on my webpage. The html file gets rendered, no problem here, so I configured templates fine. But for static files, the images dont get rendered... My static folder is inside project folder and inside static folder, I have images folder which containes image.jpg. I added these lines to settings.py: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS: [STATIC_DIR, ] STATIC_URL = '/static/' And this is my image path: <img src="{% static "images/rango.jpg" %}"> Image shows broken on webpage. -
DRF testing Model Serializer - Django Restframework
I am testing my Serializer model in django restframework with APITestCase. this is my structure : class Usertest(APITestCase): def test_userprofile_create(self): user = User.objects.create(username='asghar', password='4411652A', email='ww@gmail.com',) profile = UserProfile.objects.create(fullname='asghariiiiii', phonenumber='9121345432', address='bella', user=user) user.user_profile = profile client = APIClient() request = client.get('/user/create/') data = UserCreateSerializer(user, context={'request': request}).data url = reverse('user-create') response_create =client.post(url, data) in my view permissions set to AllowAny. no need for login or force_authenticate. data = UserCreateSerializer(user, context={'request': request}).data AttributeError: 'HttpResponseNotFound' object has no attribute 'build_absolute_uri' as you can see error comes from creating data .first i tried to remove context but error comes with this title : AssertionError: HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. -
How do I filter a query set based on child attributes after following a ForeignKey backwards?
I'm new to Python/Django, so any help is much appreciated! I am trying to find out a winner based on how many times score_1 > score_2 in all the child objects. I have these two Models: class Parent(models.Model): winner = models.IntegerField(default=0) def foo(self): childs_of_me = self.child_set.all() number_childs = childs_of_me.count() one_better = childs_of_me.filter(score_1__gt=score_2) one_wins_count = one_better.count() if one_wins_count > number_childs/2: self.winner = 1 class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) score_1 = models.IntegerField(default=0) score_2 = models.IntegerField(default=0) I've followed the answer to this Question(Select Children of an Object With ForeignKey in Django?) to get child objects of a Parent object. However, I can't seem to figure out how to filter the returned set based on attributes in the Child Model. one_better = childs_of_me.filter(score_1__gt=score_2) returns an error: global variable score_2 unknown How would I go about doing this? -
GeoDjango save data from json or points
If I already have existing MultiString cordinates in a file(as a list) or memory or in a json format, How do I override the save function to save these points instead of the user creating the object on a map? Or perhaps more precisely, how do i load these points to a model and the database? Coordinates in memory/file [[36.66678428649903, -1.5474249907643578], [36.670904159545906, -1.542620219636788], [36.66635513305665,-1.5353272427374922],[36.662406921386726, -1.5403894293513378]] models.py class LogsUpload(models.Model): name = models.CharField(max_length=240) geom = gis_models.MultiLineStringField(blank=True, null=True) How do I use the cordinates and save them in the geom field? -
udt in cassandra cqlengine Django, updates the latest entry while trying to create a new entry
I am trying to create a new entry in Cassandra database using cqlengine, the first post creates a new entry, but when trying to create another entry, the last item gets updated with new values, after restarting the Django server, it works as expected (creates new entry) My Model is # test model udt class address(UserType): name = columns.Text() age = columns.Integer() street = columns.Text() zipcode = columns.Integer() class TestUserProf(Model): user_id = columns.UUID(primary_key=True, default=uuid.uuid4()) emp_id = columns.Text() address = columns.UserDefinedType(address) Seializer is # Test serialzer for test udt class TestProfSerializer(serializers.Serializer): user_id = serializers.CharField(max_length=100, required=False) emp_id = serializers.CharField(max_length=50) user_addr = serializers.DictField(required=False, source='address') def create(self, validate_data): """ Create new entry in ProfSerializer :params validate_data :return : """ addr_data = validate_data.get('address') obj = TestUserProf.objects.create( emp_id=validate_data.get('emp_id'), address=address( name=addr_data.get('name'), age=addr_data.get('age'), street=addr_data.get('street'), zipcode=addr_data.get('zipcode') ) ) return TestUserProf(**validate_data) Django View is # Test code for udt class TestProfView(viewsets.ModelViewSet): """ Test class of udf :prams request :return list of profils """ model = TestUserProf serializer_class = TestProfSerializer def get_queryset(self): return TestUserProf.objects.all() def create(self, request, *args, **kwargs): serializer = TestProfSerializer(data=request.data) try: if serializer.is_valid(): serializer.save() return Response({'status': 'success'}) else: return Response({'status': 'not valid...'}) except Exception as e: return Response({'error': str(e)}) post data is { "emp_id": "EMP112", "user_addr": { "street": "Kochin", … -
django rest framework m2m update method
I have a couple of m2m fields in my serializer that I need to save on update. My create() method functions fine, however I get the following error with my code: Django :: 2.0.1 DRF :: 3.7.7 Direct assignment to the forward side of a many-to-many set is prohibited. Use advice_areas.set() instead. def update(self, instance, validated_data): if instance.name != validated_data['name']: instance.url_name = slugify(validated_data['name']) if instance.postcode != validated_data['postcode']: validated_data['location'] = geo(validated_data['postcode']) for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance This used to work, and I'm unsure why it isn't now. Any help would be appreciated. -
How can I pick up all the titles and articles with scrapy?
I'm currently on scraping some web information. I don't know why but it just doesn't work fine. It would be appreciated if someone could correct my code. This is just an example but what I'd like to do here is from the starting URL, visit all the articles listed on it, and pick up the title and article from each. (all the articles come the way like http://www.bbc.com/sport/tennis/42610656) Here is my code below. Thanks so much for your help! # -*- coding: utf-8 -*- import scrapy from myproject.NLP_items import Headline from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors import LinkExtractor class BBC_sport_Spider(CrawlSpider): name = 'sport' allowed_domains = ['www.bbc.com'] start_urls = ['http://www.bbc.com/sport/'] allow_list = ['.*'] rules = ( Rule(LinkExtractor( allow=allow_list), callback='parse_item'), Rule(LinkExtractor(), follow=True), ) def parse(self, response): for url in response.xpath('//div[@id="top-stories"]//a/@href').extract(): yield(scrapy.Request(response.urljoin(url), self.parse_topics)) def parse_topics(self, response): item=Headline() item["title"]=response.xpath('//div[@class="gel-layout__item gel-2/3@l"]//h1').extract() item["article"]=response.xpath('//div[@id="story-body"]//p').extract() yield item ` -
Two Django app on apache2 server using wsgi?
I am trying to deploy two Django application on Apache2 server, running on Ubuntu-16.04, My 000-default.conf file is like given below: <VirtualHost *:80> <Directory /home/bic/MyApp/MyApp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess MyApp python-path=/home/bic/MyApp:/usr/lib/python2.7/dist-packages WSGIProcessGroup MyApp WSGIScriptAlias /MyApp /home/bic/MyApp/MyApp/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html </VirtualHost> <VirtualHost *:80> Alias /static /home/bic/pep_web/protocol/static <Directory /home/bic/pep_web/protocol/static> Require all granted </Directory> <Directory /home/bic/pep_web/pep_learn> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess pep_web python-path=/home/bic/pep_web:/usr/lib/python2.7/dist-packages WSGIProcessGroup pep_web WSGIScriptAlias /pep_learn /home/bic/pep_web/pep_learn/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> With this setting "MyApp" is working but not the other applicatoin "pep_web" how can I solve this problem? -
Widget for easy handling of HStoreField in admin
I'm looking for a widget or the likes that makes easy to enter HStoreField data in django admin. Any suggestions? -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6)
It's my first time trying to deploy a Django app(django 2.0.1)(Python 3.6) to pythonanywhere, it is a simple portfolio app with no models, no bootstrap. Just Django, HTML, CSS & Javascript. After pulling it from the Github repo onto pythnanywhere with their bash console, I run : python manage.py migrate & was hit with this error : Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/commands/migrate.py", line 12, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/db/migrations/autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/db/migrations/questioner.py", line 9, in <module> from .loader import MigrationLoader File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 8, in <module> … -
How to rewrite the Django model save method?
How to rewrite the Django model save method? class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # I want send email there pass I mean, in the Django model, if I create instance success, I want to call a function, such as send a email in the function. I find in the Django model have a save method. I am not sure whether should write other code, because there are so many params. I mean whether I only should care about my send email logic? -
Filter product_set in django-mptt
Have 2 models class Category(MPTTModel): title = models.CharField() parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True) I want to get tree from both models. Now i can get: in views nodes = Category.objects.all() in template {% for n in nodes %} {% for t in n.product_set.all %} But i want to get nodes = Category.objects.all().**insert_to_category_product_with_filter**(id__in=[list_id]) -
Django rest framework foreign key display details from table 1 to table 2
I have 2 model, MyUser, Family. What i want to do is display users details in Family table based on the MyUser table. It is like adding friends or family in other social media and display them In my current Family table, there are these 3 field. userId , familyId and relationship: userId(foreign key from MyUser table) = current user familyId(foreign key from MyUser table) = current user's family member relationship = who is the family member to the current user (eg: mother, father) But i want to display only some of userId and familyId details from MyUser so the result will be like this: expected result userId = { id = 1, username = tom, image = "/media/images1/asdasdsda000.PNG"} familyId = { id = 2, username = steve, image = "/media/images1/asdasdsda111.PNG"} relationship = father current result userId = 1 familyId = 2 relationship = father How do i do it ? I thought about nested serializer but i only want to display user details but not edit it from there. Here is my code: models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) image1 = models.ImageField(upload_to='images1') dob = models.DateField(blank=True, null=True) gender = models.CharField(max_length=6) class Family(models.Model): userId = models.ForeignKey(MyUser) familyId = models.ForeignKey(MyUser) relationship = … -
suds-jurko api error message
i have the following piece of code using suds-jurko used to interface with Netsuite try: search_response = client.service.searchMoreWithId(search_id, page_index) except: print 'NOTHING LEFT' break else: success = search_response.status._isSuccess if success: <do something on success> else: print 'FAIL' break when i execute this code, the print "FAIL" executes. i wish to check what specific error occured but i'm not sure where to check. I was looking for something like an error message so i could find why it returned a fail but i don't see a property or function for this. Where could i begin checking thanks -
How to map to request.post json key to model serialializer field in django?
I am newbie in djnago-rest-framework. I am leaning about creating instance with serializer in DRF. Let suppose I have models who look like this (models.py) : from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Article(models.Model): headline = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) My serializer look like this (serializers.py) : Class AricleSerializer(serializers.ModelSerializer): reporter = PkDictField(model_class=Reporter) class Meta: model = Article field = ('headline', 'reporter') If I post the data like this: $ curl -H "Content-Type: application/json" -X POST -d '{"headline":"NewHeadline", "reporter":1}' http://localhost:8000/create-article/ In this case everything work fine, It create new entry of article. But actually I want to rename field reporter to article_reporter so actual post request look like this $ curl -H "Content-Type: application/json" -X POST -d '{"headline":"NewHeadline", "article_reporter":1}' http://localhost:8000/create-article/ Yes I understand I can rename key "article_reporter" to "reporter" in views.py before to send data to serializer and It will work fine. But I want to handle this in serializer class, AricleSerialize. can someone tell me how can I solve this in serializer? Any help would be appreciater. Thanks -
django template css files not imported URL
My css and js files are not imported for some the url http://demo.in:8001/dj/dev/userlogin/725/92dc73fa435ec9d727a987a763d309 but the same files are imported for url http://demo.in:8001/dj/dev/userlogin/725 They extend same base file. The path static files are hitting are : http://demo.in:8001/dj/static/.. whereas with the static tag, the should hit following path http://demo.in:8001/static/..