Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting 500 error in django while tampering GET parameter (Django)
My code looks like this : def rssfeeds(request): reqdata = request.GET['url'] if reqdata == '': d = "https://github.com/rudrasingh99.private.atom?token=MYPRIVATETOKEN" data = [] for post in d.entries: data.append(post.title) my_context = { "my_list" : data, } else: d = feedparser.parse(reqdata) data = [] for post in d.entries: data.append(post.title) my_context = { "my_list" : data, } return render(request,"base.html",my_context) def home_view(request): return render(request,"index.html",{}) while whenever i try with empty url parameter it gives me 500 error. Thanks in advance -
Django - Getting contact permission from users
On my sign up forms, I am asking users if I can contact them via email or SMS. I am using Django-Allauth and it doesn't seem to list it as an option. I am subclassing the view and trying to sneak it in there: class ListenSignupView(SignupView): template_name = 'listen_signup.html' def form_valid(self, form): form.allows_contact = self.request.POST.get('allows_contact') return super(ListenSignupView, self).form_valid(form) However, it doesn't actually save the result to the user. Do I also need to subclass the forms? What is the easiest way to accomplish this? -
Celery worker not stopping
I've got a django app running on webfaction, and a couple of days ago I upgraded a package that also upgraded django to version 2.1 (from version 2.0). Shortly thereafter, celery stopped working, and when I tried to restart it in supervisor I got the following error: http://127.0.0.1:12637 refused connection When I checked the supervisor logs, I saw the following: 2018-10-06 21:56:58,356 WARN received SIGHUP indicating restart request 2018-10-06 21:56:58,417 INFO waiting for accconsole_celery, catdemo, accconsole_celerybeat to die 2018-10-06 21:56:58,418 INFO exited: catdemo (terminated by SIGTERM; not expected) 2018-10-06 21:56:58,432 WARN received SIGTERM indicating exit request 2018-10-06 21:56:58,590 INFO stopped: accconsole_celerybeat (terminated by SIGHUP) 2018-10-06 21:57:01,604 INFO waiting for accconsole_celery to die 2018-10-06 21:57:04,721 INFO waiting for accconsole_celery to die 2018-10-06 21:57:07,729 INFO waiting for accconsole_celery to die 2018-10-06 21:57:10,736 INFO waiting for accconsole_celery to die 2018-10-06 21:57:13,740 INFO waiting for accconsole_celery to die 2018-10-06 21:57:16,747 INFO waiting for accconsole_celery to die 2018-10-06 21:57:19,752 INFO waiting for accconsole_celery to die 2018-10-06 21:57:22,758 INFO waiting for accconsole_celery to die 2018-10-06 21:57:25,762 INFO waiting for accconsole_celery to die 2018-10-06 21:57:28,766 INFO waiting for accconsole_celery to die 2018-10-06 21:57:31,769 INFO waiting for accconsole_celery to die 2018-10-06 21:57:34,774 INFO waiting for accconsole_celery to die … -
create a user in Django 2.1 that is associated with an existing model
In my models.py file I have the following code -> from django.db import models class Blogger(models.Model): username = models.CharField(max_length=20) email = models.EmailField() first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) password = models.CharField(max_length=30, default='') I want to associate the Blogger model with a User and create the User upon form submission. Here is the forms.py file -> from django import forms from blog.models import Blogger class BloggerForm(models.ModelForm): class Meta: model = Blogger fields = ['username', 'email', 'first_name', 'last_name', 'password'] And here is the views.py -> class BlogView(FormView): template_name = 'blogform.html' form_class = BloggerForm success_url = 'blog/' How do I create a new user on the submission of this form ? -
Default manager for related access not being used
I'm following the guide from Django's documentation to try to use a custom manager for related queries but this manager is not used. Here's an example of my setup: # models.py from model_managers import RelatedModelQuerySet class SampleModel(models.Model): # fields class RelatedModel(models.Model): is_active = models.BooleanField(default=true) sample_model = models.ForeignKey(SampleModel, related_name'relateds') objects = RelatedModelQuerySet.as_manager() class Meta: # This is what the documentation recommends base_manager_name = 'objects' # model_managers.py class RelatedModelQuerySet(models.QuerySet): def inactives(self): return self.filter(is_active=False) And now, I'd like to execute the expression below to get the filtered results instead of an error: $ sample_model_instance.relateds.inactives() > AttributeError: 'RelatedManager' object has no attribute 'inactives' I've even tried setting a different name for the manager and use it in the base_manager_name's Meta attribute but it didn't help too. So how is the correct way to setup the model to be able to use a custome related manager? -
Filtering Results Using `get_context_data` in a ListView
In my ListView, I want to return the entire list of objects from my Publication model and return the total from my Budget model to include in the ListView with each title and the associated total. My Models: Publication App class Publication(models.Model): title = models.CharFiedl(...) Budget App class Budget(models.Model): total = models.DecimalField(...) publication = models.ForeignKey(Publication, ...) Views: Publication App class PublicationListView(ListView): context_object_name = 'publications' model = Publication def get_context_data(self, **kwargs): context = super(PublicationListView, self).get_context_data(**kwargs) context['publication'] = self.get_queryset() context['budget'] = Budget.objects.all() return context In my template, the results I am receiving look something like this: publication 1 1000 2000 3000 publication 2 1000 2000 3000 publication 3 1000 2000 3000 But what I need is: publication 1 1000 publication 2 2000 publication 3 3000 I understand why I am returning all budget objects in each row, I am just not sure how to only display the correct budget with the associated publication. Is using get_context_data the best option for this? -
No module named 'django.urls'
I have a problem: ImportError at / No module named 'django.urls' urls.py: from django.contrib import admin from django.urls import path from polls.views import * urlpatterns = [ path('', EnterPage, name='home'), path('admin/', admin.site.urls), path('main/',EnterPage), path('login/',loginn), path('admin-panel/',adminPan), path('control-users/',panel), path('menu/',menu), path('perspage/',lk), path('spisok-zakazov/',product), path('info/',info), path('task-panel/', tasks), path('tasks/',earncoin) ] I don't know what to do) because I do not understand very well in Django) Somebody, please help meeee))) -
A trouble with Django loaddata command
I am writing some free software based on Django. I have a class Item which describes a pricing plan (such as "subscription, $10 per week without a trial period"). My code often creates new items based on existing. For example new item created based on the above item would be: "subscription, $10 per week with the trial period 10 days" (for the case if a customer paid for 10 days already). Now there are two kinds of items: predefined items (as in the first example); modified items (based on another item, as in the second example). Now the trouble: I create predefined items using ./manage.py loaddata ... command which loads the items from a JSON file. I create modified items in my Python code. If I add a new item to the JSON code and run ./manage.py loaddata ... again, then (accordingly to how I understand) the loaddata command may overwrite one of the modified items (created later by my Python code). What to do to avoid overwriting modified items with new predefined items? More generally, how to keep predefined and modified items distinct, to be sure the code could differentiate which items are predefined and which are not? -
How can I use OrientDB with Django?
I am building a django project that uses a relational DB (for development purposes SQLite) and an non-relational DB(OrientDB). This is my first time a using non-relational DB and I m having difficulty getting it setup with Django. The use of OrientDB in my project is solely to keep track of friend relationships and friend-of-friend relationships, while all other user data is being stored in my relational DB. I know I need to register the DB in my settings file. I am trying to do something like this: #setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'friends': { 'NAME': 'friends', 'ENGINE': 'django.db.backends.orientdb', 'USER': 'root', 'PASSWORD': 'hello', 'HOST': '', 'PORT': '2480', } } When I do this, however, I get the error: "No module named 'django.db.backends.orientdb'" Is this backend module something I have to create myself or can I manually connect to the DB in my code whenever I need something specific done? For example, whenever someone creates a new user in my SQLite DB, can I use a Signal post_save to 1) connect to OrientDb, 2) create a friend instance in Orient DB, and 3) disconnects from OrientDB? It seems like there ought to be a … -
Get foreign key description from particular object Django Rest Framework
I have a problem. I have two models: class Album(models.Model): name = models.CharField(max_length=255) class Track(models.Model): name = models.CharField(max_length=255) album = models.ForeignKey(Album, on_delete=models.CASCADE) I want to retrieve all track for a particular album. For example GET /api/albums/1/tracks/ { "id": 1, "tracks": [ 1, 2 ] } How should my viewset.py and urls.py look? Thanks! -
How to show specific output data using modal
I'm currently stuck with showing specific output using modal and I think it might involve jquery of some sort..but need some pointer, would appreciate it. This picture is showing a clickable asset, that should show data relating to that asset. However, the template that I use right now is showing the data of all the asset as one when I click on each of them. Template of how I make my asset become clickable modal: <tbody> {% for item in my_stock %} <tr class="d-none d-sm-table-row"> <td colspan="2"> <a data-toggle="modal" href="#mydata"> {{item.symbol}}</a> </td> </tr> {% endfor %} Template of my modal: <div class="modal fade" id="mydata" tabindex="-1" role="dialog" aria-labelledby="mydata" aria-hidden="true"> <tr class = " d-none d-sm-table-row"> <th colspan="2">ASSET</th> <th class="text-right"> Quantity </th> <th class="text-right"> Buy Price </th> <th class="text-right"> Investment </th> <th class="text-right"> Date </th> </tr> <tbody> {% for item in my_stock %} <tr class="d-none d-sm-table-row"> <td colspan="2"> {{item.symbol}} </td> <td class="text-right"> {{item.quantity}}</td> <td class="text-right"> {{item.buy_price}}</td> <td class="text-right"> {{item.total_value}}</td> <td class="text-right"> {{item.event_date}}</td> </tr> {% endfor %} -
copy method inside a model
I want to implement a copy() method inside my model 'BlogPost' that: create a complete copy from this model (object) with these specifications: 1-Copy the whole post with all its comments 2-Set the date creation to copied date and time 3-Finally return the new blog post (copied) id from django.db import models from django.utils import timezone from copy import copy, deepcopy class Author(models.Model): name = models.TextField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) def copy(self): pass class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.CharField(max_length=500) for example, we have: one author with the name 'Joe' one post with date_created '7 October' and 3 comments about this post after using copy method for this post: we have one author with 2 posts and 6 comments (each post have 3 separate comments) -
ClassBaseView Create Form
I have simple model: class Test(models.Model): title = models.CharField(max_length=30); Form: class TestForm(forms.ModelForm): title=forms.CharField() And class in view: class TescCreateView(CreateView): template_name = 'test.html' forms=TestForm success_url = '' def form_valid(self, form): return redirect('') But i have erros: invalid literal for int() with base 10: 'test' -
Django: Changing record's value before deleting it
I am trying to change one of the record's field before deleting it: query_item.txId = txId try: query_item.delete() except Exception as e: print(str(e)) The point is that written above code causes an exception: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I have tried playing with with transaction.atomic(): statement, but it did not change anything at all. Moreover, following combination: query_item.txId = txId query_item.save() try: query_item.delete() except Exception as e: print(str(e)) still causes the same error -
Generating Golfer Statistics in Python List
class Score(models.Model): player = models.ForeignKey(User) hole = models.ForeignKey(Hole) strokes = models.IntegerField(default=0) class Hole(models.Model): number = models.IntegerField() par = models.IntegerField() for score in Score.objects.filter(player=request.user): if score.strokes - score.hole.par == 0: statistics['pars'] +=1 elif score.strokes - score.hole.par == 1: statistics['bogies'] +=1 elif score.strokes - score.hole.par == 2: statistics['doubles'] +=1 elif score.strokes - score.hole.par >= 3: statistics['triples'] +=1 elif score.strokes - score.hole.par == -1: statistics['birdies'] +=1 elif score.strokes - score.hole.par <= -2: statistics['eagles'] +=1 I have the models and code above that is used to determine how many pars/birdies/bogies etc. a golfer has for each Score. This works fine for each individual user's statistics. I'm also able to pull all of the scores and group them Score.objects.values('player', 'strokes') but what would be the best approach for pulling every score, grouping scores by player, then generating statistics for each player that can be used in a template? -
Does imageField.save() and add() save the whole model in django?
I just experienced, that my model.save() command was needless, because obviously that has already been done by image.save() and also childs.add() model = Model() child = Child() model.name = 'Test' model.image.save(file) model.childs.add(child) model.save() # is not necessary Usually this shouldn't even work with a new entry, because the add function wont work without a pk. But it looks like the image.save() method did not only move/upload the imagefile but also saved the whole model to the DB. The same seems to be done by childs.add(), because this information is also updated without calling model.save(). I always thought, that updating the database is only done when calling model.save(), obviously I was wrong or where is my mistake? -
extending django HTMLCalendar date is out of range of month
I am extending HTMLCalendar in django but when I try to get date it gives error that date is out of range of month class EventCalendar(HTMLCalendar): def __init__(self, my_year=None, my_month=None, events=None): super(EventCalendar, self).__init__() self.year = my_year self.month = my_month self.events = events def formatday(self, day, weekday, events): """ Return a day as a table cell. """ dateofthisblock = datetime.date(self.year, self.month, day) dateofthisblock = dateofthisblock + datetime.timedelta(7) events_from_day = events.filter(event_date__day=day) events_html = "<ul>" for event in events_from_day: events_html += event.get_absolute_url() + "<br>" + str(dateofthisblock) events_html += "</ul>" if day == 0: return '<td class="noday">&nbsp;</td>' # day outside month else: return '<td class="%s">%d%s</td>' % (self.cssclasses[weekday], day, events_html) def formatweek(self, theweek, events): """ Return a complete week as a table row. """ s = ''.join(self.formatday(d, wd, events) for (d, wd) in theweek) return '<tr>%s</tr>' % s def formatmonth(self, theyear, themonth, withyear=True): """ Return a formatted month as a table. """ events = Event.objects.filter(event_date__month=themonth) v = [] a = v.append a('<table border="0" cellpadding="0" cellspacing="0" class="month">') a('\n') a(self.formatmonthname(theyear, themonth, withyear=withyear)) a('\n') a(self.formatweekheader()) a('\n') for week in self.monthdays2calendar(theyear, themonth): a(self.formatweek(week, events)) a('\n') a('</table>') a('\n') return ''.join(v) The way I am passing year and month is def changelist_view(self, request, extra_context=None): after_day = request.GET.get('event_date__gte', None) extra_context = extra_context … -
Slideshow of my images in a modal window in Django template
I would like a slideshow of my images in a modal window. It works half because only the first images of the for loop that appear everywhere. Someone can help me ? Hello I would like a slideshow of my images in a modal window. It works half because only the first images of the for loop that appear everywhere. Someone can help me ? Hello I would like a slideshow of my images in a modal window. It works half because only the first images of the for loop that appear everywhere. Someone can help me ? Here is my template: {% for a in Type_ServiceListe %} <p> <a href="#lightbox" data-toggle="modal">Open Lightbox</a> <div class="modal fade and carousel slide" id="lightbox"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <ol class="carousel-indicators"> <li data-target="#lightbox" data-slide-to="0" class="active"></li> <li data-target="#lightbox" data-slide-to="1"></li> <li data-target="#lightbox" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% if a.image_1 %} <div class="item active"> <img src="{{ a.image_1.url }}" alt="First slide"> </div> {% endif %} {% if a.image_2 %} <div class="item"> <img src="{{ a.image_2.url }}" alt="Second slide"> </div> {% endif %} {% if a.image_3 %} <div class="item"> <img src="{{ a.image_3.url }}" alt="Third slide"> </div> {% endif %} </div><!-- /.carousel-inner --> <a class="left carousel-control" href="#lightbox" role="button" data-slide="prev"> <span … -
how do I make chatbots in django websites?
I am currently working on a Django project, its actually a crowdfunding website. I want my project to have a chatbot at the corner of its homepage just like how most of the modern websites have, which will help people in answering their website related queries. is it possible in Django? if yes: what should I be learning in order to complete my project, and how much time will it take to make it. if no: why? -
I'd like to kwon how i changes my re_path to path in django and keep the same outcome
Can any one explain to me how i type this in a path converter and still get the same out come. This works fine for now, but i'd like to know the other way of doing this, Thanks in advance. (new to python btw) re_path(r'^lists/(.+)/$', views.view_list, name='view_list') -
Duplicate and Associate an existing table when a entry is created in a different table - Django
I am trying to figure out the best way to link/dupliate a table with a few blank form slots (i.e Notes, Status) that will change for each project. So far i have the following for the main table: class Project(models.Model): name = models.CharField(max_length=200) architect = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=200, blank=True) state = models.CharField(max_length=200, blank=True) zipc = models.CharField(max_length=200, blank=True) status = models.CharField(choices=projectStatus, max_length=200) bidders = models.ManyToManyField(Bidder) notes = models.TextField(blank=True) def publish(self): self.save() def __str__(self): return self.name where bidders is the table i need to duplicate/link. Here is the Bidders table: class Bidder(models.Model): division = models.CharField(max_length=200, blank=True) section = models.CharField(max_length=200, blank=True) size = models.CharField(max_length=200, blank=True) company = models.CharField(max_length=200) address = models.CharField(max_length=200, blank=True) city = models.CharField(max_length=200, blank=True) st = models.CharField(max_length=200, blank=True) zipc = models.CharField(max_length=200, blank=True) contact = models.CharField(max_length=200, blank=True) phone1 = models.CharField(max_length=200, blank=True) phont2 = models.CharField(max_length=200, blank=True) email1 = models.EmailField(max_length=200, blank=True) email2 = models.EmailField(max_length=200, blank=True) notes = models.TextField(blank=True) def publish(self): self.save() def __str__(self): return self.company The whole project can be thought of as a call tracking system. When a new project is created, i need to run down a list of contacts and change the status depending on how the call went (i.e Accepted, rejected, needs more info … -
Django evert migration on custom migration
I'm currently struggling with custom Django migrations and more specifically with the ability to revert it. I have a model UserSubscription with a foreign key 'Subscription' that represent a subscription with price, name, type, etc. UserSubscription keep track of every event occuring with our payment service (last payment, errors, date of sub, etc...) My migration remove this Subscription foreign key and add a new one UserConditionalOffer (that track a sub with promotion or special offers) playing the migration forwards works well, but when I play it backwards, I need to remove UserConditionalOffer and recreate the Subscription foreign key with a default value. As I understand it, Django will do those operations but cannot repopulate the table with subscription values. UserSubscription model : class UserSubscription(models.Model): user = models.ForeignKey(User, verbose_name = 'user', null = False, blank = False) user_conditional_offer = models.ForeignKey(UserConditionalOffer, verbose_name = 'user conditional offer', null = False, blank = False) ... # removed line : subscription = models.ForeignKey(Subscription, verbose_name = 'subscription', null = False, blank = False) As you can see, Subscription cannot be null. So when Django revert this migration, it creates a field subscription in UserSubscription, but leave it null, and fails. I just need to set subscription … -
How to fix CORS issue on Django app deployed on a DigitalOcean droplet
I have a Django app deployed on a droplet on DigitalOcean and a team mate is developing a React based frontend application. We're facing CORS issues even though I implemented django-cors-headers. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'localhost', ) This is the ajax request: $.ajax({ type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", url: "http://ipaddress/api/auth/login", data: { username: "test1", password: "test" }, success: function (data) { console.log(data); } }); We get the error: Failed to load http://ipaddress/api/auth/login: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. What can be the problem? Is there anything wrong the configuration of the django-cors-headers package? Thank you so much for your help. -
Best practice for Javascript which requires context variables in Django
Until now I have been including scripts in my templates by using {% load static %} and having the javascript code in the static directory, separated from html files, because I thought it was the best practice. But more and more I need to use context variables in the javascript. Since template tags cannot be integrated directly in the individual javascript static files (as far as I know), I have been importing these values in the javascript from the rendered template by using selectors. For example: <!--template.html--> <div id="url_ajax" style="display:none">{% url "images:products" %}</div> {%load static%} <script src="{% static "js/ajax.js" %}"></script> /*Ajax.js*/ url_ajax = document.getElementById("url_ajax").innerHTML $.post(url_ajax, { rankit: this.rankit, pd: JSON.stringify(pd) }, function(data) { if (data['status'] == 'ok') { [...] } } ); Although this works, I am feeling this is not a good practice due to security reasons or scalability. But I do not know another way of integrating context variables in the javascript rather than integrating javascript code directly in the template, which is neither a good approach if that code will be used in many templates. As a Django learner I would like to know which is the most often used approach in these situations: separated javascript files … -
Multiple annotations on related objects
I'm trying to calculate some related objects for user using Django ORM. As for example I have 3 models: User, A, B class A(models.Model): creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='A_set') class B(models.Model): creator = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='B_set') a_model = models.ForeignKey('a.A', on_delete=models.CASCADE, related_name='B_set') My query looks like: User.objects.annotate(a_count=Count('a_set')).annotate(b_count=Count('b_set')) When b_count always copying value a_count except when real number of b objects is 0. But when I'm splitting my query into two separate - it works good.