Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot see the bottom part of html page in Django
I visualized pandas dataframe into html template in Django referring to this page. However, the bottom part of table cannot be seen as below image.(cannot scroll down) Does anyone know what is causing this problem and how to fix it? Thank you. -
How run Django server on public ip in Android
Using termux I am able to run Django server on localhost but I am not able to run the server on Public ip (Intranet-ip) -
redefine response in django-rest-social-auth
My question, how me can redefine standard response_code and response in django-rest-social-auth sent on endpoint /login/social/token/ this is link https://github.com/st4lk/django-rest-social-auth on documentation -
How to add few fields in admin to the same model
I have django app (django 1.11) Here is 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() related_news = models.ForeignKey('news.News', on_delete=models.CASCADE, null=True, blank=True) My admin.py file: from django.contrib import admin from modeltranslation.admin import TranslationAdmin from news import models class NewsInLine(admin.TabularInline): model = models.News extra = 1 class NewsAdmin(TranslationAdmin): list_display = ['title', 'subtitle', 'text', 'link_title'] date_hierarchy = 'date' inlines = [ NewsInLine ] admin.site.register(models.News, NewsAdmin) My problem is that I do not want to connect only a few "related_news" fields to one of the News objects. But my solutions allow you to connect new ones instead of existing objects. -
How can i add an unsubscription link for email using django
I don't know how can I add unsubscription option to receive emails for users in Django? I need to add this option urgently in case any user don't want to receive email from me Models.py: class User(AbstractUser): username_validator = UnicodeUsernameValidator() username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), unique=True) Views.py: @csrf_exempt def email_users_date(request): if not request.method == 'POST': return json_data = json.loads(json.loads(request.body)[0]) date=json_data.get('date') print(json_data) # date = request.POST.get('date') for user in User.objects.all(): subject = 'Data updated' template = get_template('interface/emaildata.html') context = {'user': user, 'date':date} text_msg = strip_tags(msg) send_mail(subject, text_msg, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=msg) return HttpResponse() -
TypeError when running objects.all() on model
This is my model: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField(null=True) cardios = fields.CardiosField(null=True) def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ And I'm trying to do this from the django shell: (workout) Sahands-MBP:workout sahandzarrinkoub$ shell Python 3.6.2 (default, Jul 17 2017, 16:44:45) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from workoutcal.models import Workout >>> Workout.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/query.py", line 62, in __iter__ for row in compiler.results_iter(results): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 842, in results_iter row = self.apply_converters(row, converters) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 827, in apply_converters value = converter(value, expression, self.connection, self.query.context) TypeError: from_db_value() takes 4 positional arguments but 5 were given What's the explanation behind this error? I haven't sent any arguments anywhere, so as far as I can tell, the error must lie in my declaration of the model, but I can't see the mistake I made. Thankful for help. -
jquery not working on django
jquery does not work on django project I used with bootstrap. please help me .html <div class="domains-slider marquee"> <ul> <li><a href="#">BTC/USD</a><span class="price"> $2,33 CAD</span></li> </ul> </div> {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> </body> </html> script.js jQuery(window).load(function() { jQuery(".marquee").marquee({ duration: 10 * jQuery(".marquee").width(), duplicated: true, pauseOnHover: true }); }); -
Generate date alerts in Django
I need to generate an alert in a birthday software tell me with an alert that a certain person's birthday will arrive How can I do it? the data is with a table in mysql that has the identification number and its date of birth Please, how can I do it? -
Django transactions not working when using MS SQL
I am parsing a file and would like to import the rows line by line inside of a transaction into my MS SQL database so I don't have to load it all into RAM. try: with transaction.atomic(using='mssql'): with open(filepath, 'r', newline='\n') as clean_file: for row in clean_file: measurement = json.loads(row) current_measurement = Measurementdata( mea_datetime=measurement['imp_datetime'], dun=measurement['dun_id'], exp=measurement['exp_id'], ptr=measurement['ptr_id'], mea_value=measurement['imp_value'] ) current_measurement.save() This code works fine using SQLite as the database engine ... 'mssql': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'mssql.sqlite3'), } ... and the log shows that the transaction worked ... (0.000) BEGIN; args=None (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, 24, 44.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 343.22); args=['2000-01-01 07:51:24', 5, 12, 24, 343.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, 24, 44.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 343.22); args=['2000-01-01 07:51:24', 5, 12, 24, 343.22] (0.000) INSERT INTO "MeasurementData" ("MEA_DateTime", "DUN_ID", "EXP_ID", "PTR_ID", "MEA_Value") VALUES ('2000-01-01 07:51:24', 5, 12, 24, 44.22); args=['2000-01-01 07:51:24', 5, 12, … -
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 `