Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to make methods in a Model Manager automatically called?
I'm building a Cart model and a BooksInCart model, I want the book_quantity field in a cart model update automatically each time when I add books into a cart. The update_cart_quantity function run manually perfectly in the shell. But I want it to be called each time when I add books into a cart. cart/model.py: class BooksInCartManager(models.Manager): def update_cart_book_quantity(self): books = BooksInCart.objects.all() for b in books: b.cart.book_quantity += b.quantity b.cart.save() class Cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) book_quantity = models.IntegerField(default=0) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) def __str__(self): return self.user.email + '_cart' class BooksInCart(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) objects = BooksInCartManager() def __str__(self): return self.book.title On admin site, Cart looks like this: -
Django If Statements not working
So I have been trying to implement a way to create a post where I can upload multiple images with it. I am currently using two forms and two tables, one for the actual post, and one for multiple images associated with it. However, the if statement checking if both forms are valid does not work. It does not post any errors, its just that nothing happens. Nothing gets created nor added to my databases. It doesn't validate even if the forms are complete and correct. I would really appreciate any help ! MY code: views.py class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() #project_form = ProjectsForm(initial=self.initial) project_form = ProjectsForm() context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST, request.FILES) multi_img_form = P_ImageForm(request.POST, request.FILES) if project_form.is_valid() and multi_img_form.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() images = multi_img_form.save(commit=False) images.save() data = { 'is_valid': True, 'name': images.p_file.name, 'url': images.p_file.url } else: data = { 'is_valid': False, } return JsonResponse(data) basic-upload.js $(function () { /* 1. OPEN THE FILE EXPLORER WINDOW */ $(".js-upload-photos").click(function () { $("#fileupload").click(); }); /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */ $("#fileupload").fileupload({ dataType: 'json', done: function (e, data) { … -
django models timer delete
I am trying to put a timer on each object that being created after the time is up the object will delete it self I have my models set up so far I can see if I create an object and I can see my Gamesplayed object with all the data on html is there a way to add another field to the Gamesplayed of a countdown timer that will be shown on html and will delete the objects after the time is up? my models from django.db import models class Gamesplayed(models.Model): Game=models.CharField(max_length=30,blank=True) Myviews = models.CharField(max_length=30,blank=True) Price=models.PositiveIntegerField() is there any field that dose that? saw Durationfield but not sure how to use -
DRF create only works if serializer is set to (many=True)
I'm having an issue with a POST request view. DRF will throw an attribute error if I do not set the serializer(AnswerSurveySerializer) to (many=True) but I just want to post a single entry for the field which is a foreignkey. It works as intended for the other FK which is "choice" so it really stumps me why it wouldn't work for "survey". Appreciate any advise and thanks in advance. Error Traceback: http://dpaste.com/3TN8D0N models.py class Survey(models.Model): history = HistoricalRecords() user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='surveys', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) is_completed = models.BooleanField(default=False) def __str__(self): return self.status class Question(models.Model): history = HistoricalRecords() created = models.DateTimeField(auto_now_add=True) question_text = models.TextField() def __str__(self): return self.question_text class Choice(models.Model): history = HistoricalRecords() question = models.ForeignKey( Question, related_name='choices', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) choice_text = models.CharField(max_length=255) value = models.DecimalField(max_digits=3, decimal_places=2) def __str__(self): return self.choice_text class Answer(models.Model): history = HistoricalRecords() survey = models.ForeignKey( Survey, related_name='answers', on_delete=models.CASCADE) choice = models.ForeignKey( Choice, related_name='answers', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) serializers.py class AnswerChoiceSerializer(serializers.ModelSerializer): class Meta: model = models.Choice fields = ('id',) class AnswerSurveySerializer(serializers.ModelSerializer): class Meta: model = models.Survey fields = ('id',) class AnswerSerializer(serializers.ModelSerializer): survey = AnswerSurveySerializer(many=True) choice = AnswerChoiceSerializer class Meta: model = models.Answer fields = ('choice', 'survey') views.py class AddAnswerView(generics.CreateAPIView): """Handles creating answers … -
relationships in django 2 models.py
I want to design a relation between book and member with borrow in models.py ER but I dont know how to defin borrow relationship? in borrow table It must be determined which books have been borrowed by who.and Books have been returned on which date(for this field I should use another table??) models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext as _ class CategoryType(models.Model): category_name = models.CharField(max_length=200) def __str__(self): return self.category_name class Book(models.Model): name = models.CharField(verbose_name="عنوان", max_length=128) number_of_copy = models.IntegerField(default=0) writer = models.CharField(max_length=64) B_category = models.ForeignKey(CategoryType, on_delete=models.CASCADE) class Meta: ordering = ["B_category"] def __str__(self): return self.name class Borrow(models.Model): borrowed_from_date = models.DateField(_("borrow Date"), default=0) borrowed_to_date = models.DateField(_("return Date"), default=3) actual_return_date = models.DateField() borrowed_by = models.ForeignKey(member, on_delete=models.CASCADE) books = models.ManyToManyField(Book) def __str__(self): return self.id class member(AbstractUser): pass I think in member class should have field contain of borrow id ?but how? -
listen for sensor continuously when using django as a server
I have developed a smart bulb using relay to switch the bulb on and off when I clap. This works with a simple python script but that i want to use django as a server for handling this use case. I could not handle the following cases 1) there will be button for turning the bulb on and off (this i could do) 2) when i clap, the bulb should turn on and again if i clap the bulb should turn off. For second case, how can i continuously listen for the sensor data so my bulb can act it accordingly. Here is the simple script which works #!/usr/bin/python import RPi.GPIO as GPIO import time # telling pi we are not using the pin but BCM standard GPIO names for the pins GPIO.setmode(GPIO.BCM) BULB_OUTPUT_PIN = 4 SOUND_INPUT_PIN = 17 # as I am refering to the BCM mode instead of BOARD mode so the output pin is # GPIO4 which is 7th pin in the pi when starting the first pin from left. GPIO.setup(BULB_OUTPUT_PIN, GPIO.OUT) GPIO.output(BULB_OUTPUT_PIN, GPIO.HIGH) # for sound sensor GPIO.setup(SOUND_INPUT_PIN, GPIO.IN) SleepTime = 6 # main loop try: while 1: print('#######GPIO INPUT PIN##### ', GPIO.input(SOUND_INPUT_PIN)) if GPIO.input(SOUND_INPUT_PIN) == … -
Get foreign key fields in django rest framework
Accessing my API endpoint I get something like this: { place: "https://example.com/api/places/998/?format=json", item: "Stone Fruit Salad", description: "greens • fennel • cucumber" }, { place: "https://example.com/api/places/999/?format=json", item: "Elote", description: "sweet corn • raddish • goat milk feta • pepita • chipotle yogurt dressing • (can be made vegan)" } What I'd like to do is have the place name and other fields available from this endpoint, instead of the the URL to another endpoint. Is this possible? Something like this: { place_name: "Place 1", place_website: "example.com", item: "Stone Fruit Salad", description: "greens • fennel • cucumber" }, { place_name: "Place 2", place_website: "example.com", item: "Elote", description: "sweet corn • raddish • goat milk feta • pepita • chipotle yogurt dressing • (can be made vegan)" } Files serializer.py from ..models import MenuItem from rest_framework import serializers class MenuItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MenuItem fields = ('place','item','description') views.py (api views) from ..models import MenuItem from rest_framework import viewsets from .serializers import MenuItemSerializer class MenuItemViewSet(viewsets.ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer -
Django: does `django.db.connection.close()` is safe (no data loss) in multiprocessing?
I'm using django 1.11 and PostgreSQL9.5 and psycopg2 library. Here is the sample code structure of my project: def lets_save_data(data_to_save): # Insert data into the Database for data in data_to_save: MY_MODEL.objects.create( ... ) and data_list_list = [ [{'a':1, 'b':2, 'c':3}, {'a':4, 'b':5, 'c':6}, ...], [{'a':5, 'b':5, 'c':2}, {'a':1, 'b':4, 'c':3}, ...], .... ] with Pool(12) as p: p.map( lets_save_data, [data_list for data_list in data_list_list] ) When I run these code, I'm faced with psycopg2.OperationalError errors like below: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/rightx2/.pyenv/versions/3.6.2/lib/python3.6/multiprocessing/process.py", line 249, in _bootstrap self.run() File "/home/rightx2/.pyenv/versions/3.6.2/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/home/rightx2/Dropbox/Programming/Workspace/django/super_trading_project/super_trading/data_manager/managers/upbit_manager.py", line 97, in store_orderquote symbol = Symbol.objects.get(market="upbit", currency=currency, code=code) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/query.py", line 374, in get num = len(clone) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/query.py", line 232, in __len__ self._fetch_all() File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 899, in execute_sql raise original_exception File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 889, in execute_sql cursor.execute(sql, params) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/rightx2/.pyenv/versions/super_trading_project/lib/python3.6/site-packages/django/db/utils.py", … -
Django migration doesn't recognize abstract base model class changes
I have an abstract model class and its non abstract subclasses. When I run makemigrations for the first time, non abstract subclasses are created without any problem, but when I change the abstract base class, like adding a new field, makemigrations doesn't recognize that non abstract subclasses inherit the changes on their parent class. I have to delete de models, recreate them and run makemigrations. Is there any way for makemigrations to know that the abstract base class has changed and its change must be applied to its subclasses? -
Django REST Framework CurrentUserDefault() with serializer
I have been trying for a while now to add an 'owner' field to my models. I have looked at other questions but I still have had no luck. Ideally when a new note is created, the current user will be set in the owner field and won't be changeable. Below is my model, serializer, and view for a Note as far as I have gotten. I'm guessing the CurrentUserDefault() function needs additional context but I can't set it properly. views.py class NoteListCreateView(ListCreateAPIView): authentication_classes = (SessionAuthentication, TokenAuthentication) permission_classes = (DjangoModelPermissions,) lookup_field = 'pk' serializer_class = serializers.NoteSummarySerializer def get_queryset(self): qs = Note.objects.all() # general search query = self.request.GET.get('search') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(content__icontains=query) ).distinct() # title search query = self.request.GET.get('title') if query is not None: qs = qs.filter(title__icontains=query) # content search query = self.request.GET.get('content') if query is not None: qs = qs.filter(content__icontains=query) return qs serializers.py class NoteSummarySerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault(), read_only=True) class Meta: model = Note fields = ( 'pk', 'title', 'containerId', 'created', 'updated', 'owner', ) models.py class Base(models.Model): title = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Meta: abstract = True ordering = ['title', '-updated'] class Note(Base): containerId = … -
how to launch django app which is on rabbitmq using docker containers
I wanted to launch a Django app locally on my machine to edit it. The previous developers had put it into docker containers and used rabbitmcq. I do don't know how to launch them locally now. -
Python 'user' cannot be converted to a MySQL type
I have this problem when inserting the data from other database. In the following scripts, the 'owner' is the user that acquired from the mysql database linked to Django. But there's error showing as: Failed processing format-parameters; Python 'user' cannot be converted to a MySQL type. Does the user format cannot match with mysql?How could I deal with it? Thx! def save_mysql(search_content, pmid, joke_content, owner): db = mysql.connector.connect(user='root', password='xxxxx', host='localhost', database='crawling') mysql_content = (search_content, pmid, joke_content, owner) sql = 'INSERT INTO crawling_result(search_content, pmid, content, username) VALUES(%s, %s, %s, %s)' cursor=db.cursor() cursor.execute(sql,mysql_content) db.commit() db.close() -
How to display forms.ValidationError friendly? -- Django
I would like to know how to display Django forms.ValidationError/message.error friendly before form.save, while messages.error didn't work and ValidationError is ugly like a bug of program not for clients: The partial code of views.py is like this: class ProjectCreateView(CreateView): model = Project form_class = ProjectForm def form_valid(self, form): request = self.request for u in user_project: user_times = int(sum(t['learn_times'] for t in times)) if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8: # messages.error didn't work messages.error(self.request, u.username + "'s learn_times is more than 8 hours, please check!") # ValidationError is ugly like a bug of program not for clients raise forms.ValidationError(str(u) + "'s learn_times is more than 8 hours, please check!" else: pass project = form.save(commit=False) project.save() form.save_m2m() messages.success(self.request, 'Project created successfully!') return super(CoursePermitCreateView, self).form_valid(form) def get_success_url(self): return reverse('project_change', kwargs={'pk': self.object.pk}) I can't add forms.ValidationError in forms.py and also can't add form.add_error in views.py as below screenshot of code(code link), as when I add test = Test.objects.get(pk=self.kwargs['pk']) in ProjectForm of forms.py, I will get error of 'ProjectForm' object has no attribute 'kwargs'! and If I use request.POST.get() in Projectform of forms.py, also will get the error of 'ProjectForm' object has no attribute request . Thanks so much for any … -
JQuery Ajax .preventDefault() is still redirecting on submit
I have tried the return false, .on('click' function..., tricks that most have posted on here for the other .preventDefault() redirect issues for Ajax. Here is mine: I have a Django formset that I am trying to submit for form validation using ajax ( I really want to use axios, but can't figue that out) so I don't wipe the user inputs and the dynamically generated forms. The template and JS are on the same document Just in case that matters The Template: <form method="POST" id="feedbackform" action="{% url 'error_checking' %}"> {% csrf_token %} {{ formset.management_form }} <div style="background-color: black; padding: 20px 60px 20px 60px; margin-right: 15px;" class="row form-row"> <div class="input-group"> <div v-for="form in formList"> <br> <div style="background-color: #ffe673; padding: 20px" v-html="form"> </div> </div> <div style="padding-left: 60px; background-color: black"> <p v-on:click="addForm" class="btn btn-primary btn-lg">Add Form</p> <p v-on:click="formID" class="btn btn-primary btn-lg">Delete Form</p> <p v-on:click="totalCost" class="btn btn-primary btn-lg">Total Cost</p> </div> <br> <br> </div> </div> <div style="margin: 0px 15px 100px -15px; padding: 0px 0px 60px 60px; background-color: black"> <div class="btn btn-primary btn-lg"> <paypal-checkout :amount='amountStr' currency="USD" :button-style="aStyle" :client="paypal" env="sandbox" v-on:payment-authorized="paymentAuthorized" v-on:payment-completed="paymentCompleted" v-on:payment-cancelled="paymentCancelled"> </paypal-checkout> </div> </div> <input type="submit" value="Submit feedback" class="btn btn-primary"> </form> The JS <script> $(document).ready(function () { $("#feedbackform").submit(function (event) { event.preventDefault(); $.ajax({ data: $(this).serialize(), type: … -
Django NoReverseMatch URL pattern
Hi I have been stuck on this error for about 3 hours now and I am unable to solve it. It a NoReverse Match error. My initial thoughts is they way my url pattern is written. I've tried many different url patterns and it doesn't seem to work. I am not to familiar with when to use path vs re_path. error: django.urls.exceptions.NoReverseMatch: Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P<entry_id>\\d+)/$'] file urls.py: urlpatterns = [ # Home page path('', views.index, name='index'), # Show all Categories path('categories/', views.categories, name='categories'), # Show all topics associated with category re_path(r'^topics/(?P<category_id>\d+)/$', views.topics, name='topics'), # Show single topics re_path(r'^topic/(?P<entry_id>\d+)/$', views.topic, name='topic'), ] views.py: from django.shortcuts import render from .models import Category, Entry, Topic # Create your views here. def index(request): """The home page for Learning Logs""" return render(request, 'blogging_logs/index.html') def categories(request): """show all categories""" categories = Category.objects.all() context = {'categories': categories} return render(request, 'blogging_logs/categories.html', context) def topics(request, category_id): """Show all topics for a single category""" category = Category.objects.get(id=category_id) # get category that was requested topics = category.topic_set.all() # get all topics associated with category that was requested context = {'category': category, 'topics': topics} return render(request, 'blogging_logs/category.html', context) def topic(request, entry_id): """Show entry … -
Handling temporary Django files
I am currently attempting to create a website whereby I can search for product items and the search results would be an aggregation of the search results from different websites. My model looks like this: class Product(models.Model): name = models.CharField(max_length=100) image_file = models.ImageField(upload_to='images/') image_url = models.URLField(max_length=200) url = models.URLField(max_length=200) price = models.CharField(max_length=10) At the moment, my implementation involves scraping the search results from the different pages and extracting the information I need. This includes downloading every single product image from those pages. All of these products are then stored in the database. To prepare for the next search, whenever I enter the "search" page (there is no search bar in the results page), I delete all the contents of my database and also delete the image files I downloaded. def index(request): if Product.objects.all().exists(): Product.objects.all().delete() shutil.rmtree('img directory') #deletes everything in directory return render(request, 'myproject/index.html') This is undoubtedly a terrible way of doing things. What could I do instead to avoid doing this every time? Is there a way for database entries to automatically delete themselves after some amount of time perhaps? Thanks! -
Compare values in 2 columns of database - django
I have this problem, i need compare 2 values from query. Steps 1) The user search something, for example "somebrand cars" 2) i need compare if the title searched by user first exist on the Title field on the db and if the tag field also match with the title 1 test with a simple comparison a = Data.objects.filter(title__iexact=query).values('title') b = Data.objects.filter(tag__iexact=query).values('tag') if a == b: print("We have results) 0 results on console 2) test related = Data.objects.filter(Q(title__iexact=query)&Q(tag__iexact=query)).values('title','category','description','image','url') no results If exist i need create a link on the details product for example also check this : backlink to "brand" -
Error while adding data using Django Administration's panel
I'm currently experimenting with the Django framework and i've made an application that includes 2 models. The first one is the user model which contains the user and some basic information about them. The second model is the Image model which has an author(links the user model with a foreign key) and a filename. App name: Sc Models: User, Image The code for my models: from django.db import models class User(models.Model): username = models.CharField(max_length=128, default='') password = models.CharField(max_length=512, default='') ip_address = models.CharField(max_length=32, default='') def __str__(self): return f"{self.id} - {self.username}" class Image(models.Model): author = models.ForeignKey(User, on_delete=models.DO_NOTHING) filename = models.CharField(max_length=512) def __str__(self): return f"{User.objects.filter(id=self.author)} - {self.filename}" I can add users using Django's administration panel however I can't add any images. I select the user I want as the author of the image and I add a random file name but I get the following error when I try to add the new image: TypeError at /adminsc/image/add/ int() argument must be a string, a bytes-like object or a number, not 'User' Request Method: POST Request URL: http://localhost/adminsc/image/add/ Django Version: 2.0.7 Exception Type: TypeError Exception Value: int() argument must be a string, a bytes-like object or a number, not 'User' Exception Location: C:\Python37\lib\site-packages\django\db\models\fields__init__.py in … -
Many To Many relationship django
class Itinerary(models.Model): departure = models.ManyToManyField('Segment') connection = models.ManyToManyField('Segment') objects = ItineraryManager() def __str__(self): """A string representation of the model.""" return '%s %s--%s' % (self.pk, self.departure, self.connection) class Segment(models.Model): carrier = models.CharField(max_length=3) flight_number = models.IntegerField() ... scheduled_arrival_date = models.DateField() scheduled_arrival_time = models.TimeField() objects = SegmentManager() def __str__(self): """A string representation of the model.""" return '%s%s%s--%s' % (self.carrier, self.flight_number, self.departure_location , self.destination_location) The tables created during migration are dashboard_itinerary_departure dashboard_itinerary_connection Both intermediate tables have a id(pk), itinerary_id and segment_id. When an Itinerary is saved in the program, both intermediate tables are correctly populated with the respective Segment ids. if I call: a = Itinerary.objects.get(id='1').departure.all() I do get the segment associated. BUT if I call: a = Itinerary.objects.get(id=other.pk) it returns: 15494 dashboard.Segment.None--dashboard.Segment.None If I do a select on the pk id of the Itinerary, I would like to retrieve both segments. What am I not understanding? -
Extend from UserModel of Django and use it to login
I need create a Authenticated method for to use is_authenticated() and another methods from my templates. The problem is that i didn´t understand a django documentation. I have my User model, and I wish to use it like the User model how django use its own model. What should I do? Who can guide me please? Thanks! -
How to get all models of a class in all apps of a Django project
I have a model class AppModelActions that inherits from CustomModel that inherits from django.db.models, and I use it in all apps of the project. I want to get all instances of AppModelActions in all apps, from a command file in one of the apps. I can't import each one explicitly because I want this command to work dynamically. I tried to import the instances programmatically, but it didn't work (I get this error: `KeyError: 'AppModelActions'). This is my code: from django.core.management.base import BaseCommand from django.db import IntegrityError from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext_lazy as _ from django.conf import settings from GeneralApp import models class Command(BaseCommand): help = _("""Run this commando to populate an empty database with initial data required for Attractora to work. For the momment, this models are considered on 'populate_db' command: - InventoriManagerApp.InventoryManagerAppActions """) def populate_db(self): applications = settings.INSTALLED_APPS for application in applications: try: import applications.models except: pass #from InventoryManagerApp.models import InventoryManagerAppActions models_to_populate = (vars()['AppModelActions']) #models_to_populate = (InventoryManagerAppActions,) for model_to_populate in models_to_populate: self.populate_model('InventoryManagerApp', model_to_populate) def populate_model(self, app_label, model_to_populate): model_to_populate_instance = model_to_populate() content_type = ContentType.objects.get(app_label=app_label, model=model_to_populate_instance.name) if hasattr(model_to_populate_instance, 'populate_data'): populate_data = model_to_populate.populate_data for record in populate_data: for key, value in record.items(): setattr(model_to_populate_instance, key, value) try: model_to_populate_instance.save() except … -
Django GetStream update activity sorting after activity to push it to the top of a feed
I have a panel model with an Activity mixin to tie in to the GetStream system. Each of this panels can be edited and there can be comments added to this panels. When either of this activities takes place, I would like to push this activity to the top of all feeds that are subscribed to the actors feed. I was told that there was no way to update the activity time because the time id pair is the way that GetStream makes activities unique, so I was told to accomplish what we want to accomplish we may remove the activity from the main feed than add it back in with the updated time of the activity I will achieve the desired result. So I have tried to start of by removing the activity from the main feed, as this is vague I assume .. and correct me if im wrong, that it is the actors user feed so this is the code I tried from the console. But first you should see what the timeline looks like from another users feed { currentTimeline(number: 3) { token foreignId time subject { ... on PanelType { author { id username } … -
Code: unknown, Error: Invalid response while obtaining request token from "api.twitter.com" - how to obtain and print Twitter error message
I am using Django Allauth with Django 2.0.8 and 3.5 I have followed the instructions for using Twitter to login to a site. However, when I attempt to login to my website, I am getting the following message: Social Network Login Failure An error occurred while attempting to login via your social network account. There is no log output containing more information - which makes debugging this unnecessarily difficult. Based onan answer for this question, I have added information to my tempate which sheds some more light: Code: {{ auth_error.code }}, Error: {{ auth_error.exception }} However, the error message is: Code: unknown, Error: Invalid response while obtaining request token from "api.twitter.com" Which doesn't help very much. I want to see the actual response returned by the twitter.api, so I can get to the bottom of the problem - however, it is not obvious to me how to output or log the ACTUAL response obtained from the twitter API. How do I see/capture the Twitter API response when I attemtp to login using django-allauth? -
creating signup form in django 2.0
I'm trying to create a new user with UserCreationForm in django2.0, i'm able to add email field but can't make it required. I have almost tried every options available online. Thank you. --- views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from .forms import SignupForm # signup view for new users #### Allow signup with binghamton email id only. else error def signup_new(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid: form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignupForm() return render(request, 'registration/signup.html', {'form': form}) --forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
django 2.1 environment with venv
I have a problem with the environment variables and django, I am following all the internet documentation but I can not find the problem, I did these steps mkdir protectora.com inside protectora.com virtualenv -p python3.6 venv3.6 source venv3.6/bin/active pip install django==2.1 django-admin startproject refugio inside refugio django-admin startapp polls Now there's the problem, polls does not work if I do not install it as refugio.polls 'DIRS': os.path.join(BASEDIR,'refugio/templates') it should not work this way, it seems that it is pointing out of shelter in the folder where manager.py is located I also did another test pip install gunicorn in refugio gunicorn wsgi:application error: what am I doing wrong?