Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django prefetch_related cache not reflecting the changes
I have a model "Banks". and I have 6 entities in it. This is my prefetch code. `queryset = Banks.objects.all().prefetch_related('field1','field2')` when I enter new entity into my Banks model and get the data, I still get only the old data. The newly added entity is not getting reflected when I download the data. -
Communication models of different applications
As when adding the model object of the first application, make it added as another model in the second application with the properties of the first object. # firstApp.models class itemInShop(models.Model): name = models.CharField(blank=True, null=True, max_length=100) slug = models.SlugField(blank=True, null=True) url = models.CharField(blank=True, null=True, max_length=100,editable=False) descr = models.TextField(blank=True, null=True, max_length=5000) title = models.CharField(blank=True, null=True, max_length=100) text = models.TextField(blank=True, null=True, max_length=5000) propertiesManufacturer = models.BooleanField(default=False) propertiesType = models.BooleanField(default=False) propertiesPrice = models.BooleanField(default=False) propertiesPower = models.BooleanField(default=False) propertiesAmount = models.BooleanField(default=False) The output should be about this code. Is it possible? class Pech(models.Model): name = models.CharField(blank=True, null=True, max_length=100) manufacturer = models.CharField(max_length=100, choices=CHOICES_PECHI_MANUFACTURER, blank=True, null=True) type = models.CharField(blank=True, null=True, max_length=100, choices=CHOICES_PECHI_TYPE) price = models.PositiveIntegerField(blank=True, null=True) power = models.FloatField(blank=True, null=True) -
ModuleNotFoundError: No module named 'blogdjango'
I am getting this error when trying to run server: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001FD20F4F510> Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blogdjango' I do not have a module named 'blogdjango' anywhere. This is getting out of my hands. Please help me out here. -
Getting Value of Selected Nav Pill
I'm trying to make a pair of nav pills to choose between a graphical and a tabular output for a set of data and I can't seem to figure out how to grab the value of the nav pill. I defined the nav pills as follows: <div class="col-md-2"> <ul class="nav nav-pills nav-stacked"> <li {% if type_display == 'charts' %}class="active"{% endif %}><a href="charts" class="text-primary"><i class="fa fa-fw fa-bolt"></i> Charts</a></li> <li {% if type_display == 'tables' %}class="active"{% endif %}><a href="tables" class="text-primary"><i class="fa fa-fw fa-calendar"></i> Tables</a></li> </ul> and they render like this: How do I pass the selected nav pill back to django? I tried: display_type = request.GET.getlist('charts') I have next to no experience in HTML so any info would be awesome. Thank you! -
Django "dirty-edit" file manager issue
I need something simple to edit files on my server from the admin interface. I found this application https://github.com/synw/django-dirtyedit and followed all the stes to install it and it seemed fine at first sight but when I try to add any file I get this error: What could I do to make it work? Or maybe there is something better? Thanks. -
Mysterious null value added to the beginning of my array
I am creating an online voting system using Django. I am trying to pass the id of the candidate in the database from client side back to server side in the order they appear to the user. I am using Django's templating language to add the data to <meta> tags as below: {% for candidate in candidates %} <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}"> {% endfor %} I understand this is bad practice but I didn't know how else to do this. The problem arises when adding the values to the array. The part of the script that tackles this is here: var button = $("#send"); $(button).click(function() { var metatags = document.getElementsByTagName('meta'); var cands = []; for (var i = 0; i < metatags.length; i++) { cands.push(metatags[i].dataset.id); // console.log(cands); }; cands = JSON.stringify(cands); console.log(cands); When I do this the console is showing an array with all the candidate IDs, but a null value at the beginning. My best guess as to why is that a <meta> is created some other way in the rendering of the page (possibly by the bootstrap I have used?) which is being caught by document.getElementsByTagName('meta'). What is the best way to avoid the null value? Should I … -
Available for Remote Volunteer Work on a Python/Django Project
I'm a newbie in Python/Django language and I will love to hone my skills by volunteering alongside an engineering team whose project(s) uses Python or Django framework. I am available to work remotely. If you need an extra hand with your work, I'll be glad to work with you. My email is tundebarnabie@yahoo.com -
Django dumpdata generates invalid json format file
I'm working Django1.11. and I want to move from sqlite to PostgreSQL. So I need to dump data from Sqlite and load to PostgreSQL. I generate the dumped data with python3 manage.py dumpdata > db.json I have changed db setting to PostgreSQL and did python3 manage.py loaddata db.json and got this error. raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) So I use hexdump and tried. raise JSONDecodeError("Expecting value", s, err.value) from None django.core.serializers.base.DeserializationError: Problem installing fixture '/var/lib/myproject/fixtures/db.json': Expecting value: line 1 column 1 (char 0) I took the look at db.json and it is not valid json. -
Django 2.0 Admin "Add", filter by foreign key in another model
In a project I'm working on for a little office building, I have models that include Floors, Locations, down to Assets (workstations and printers and such): class Floor(models.Model): name = models.CharField(max_length=20) floornumber = models.IntegerField(default=1) class Location(models.Model): fkfloor = models.ForeignKey(Floor, on_delete=models.CASCADE) name = models.CharField(max_length=30) isroom = models.BooleanField(default=False) class Asset(models.Model): name = models.CharField(max_length=50) serialnumber = models.CharField(max_length=50) class Workstation(models.Model): name = models.CharField(max_length=30) owner = models.CharField(max_length=20) asset = models.OneToOneField(Asset, on_delete=models.CASCADE, primary_key=True) In the Admin interface, I need a way for adding Workstations in the OneToOne relationship with Assets, but with a filter for the location so that the entire list of Assets (including non-workstations) in every part of the building doesn't show up in the admin Add/Change form for Workstations. I've read through two books and searched SO and Django docs for every combination of terms I can think of for what I'm trying to accomplish, and I haven't found a working solution yet. I can use list_filter just fine to show the existing items, but that doesn't carry over into the admin add/change form. inlines aren't what I'm looking to use. What concept am I missing here? Many thanks in advance. -
How to schedule SMS using Twilio w/o using Celery?
I want to schedule SMS using Twilio in Python. After reading some articles I came to know about Celery. But I opted not to use celery and go with Python Threading module. Threading module works perfectly when using some dummy function, but when calling client.api.account.messages.create( to="+91xxxxxxxxx3", from_=settings.TWILIO_CALLER_ID, body=message) it sends the SMS at the same time. Here is my code from threading import Timer from django.conf import settings from twilio.rest import Client account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN message = to_do client = Client(account_sid, auth_token) run_at = user_given_time() #this function extracts the user given time from database. it works perfectly fine. # find current DateTime now = DT.now() now = DT.strptime(str(now), '%Y-%m-%d %H:%M:%S.%f') now = now.replace(microsecond=0) delay = (run_at - now).total_seconds() Timer(delay, client.api.account.messages.create( to="+91xxxxxxxxx3", from_=settings.TWILIO_CALLER_ID, body=to_do)).start() So the problem is that Twilio sends SMS at the same time, but I want it to send after given delay. -
Im trying to connect my django to postgress with heroku
this´s in my settings.py DATABASE_URL = os.environ['MYPOSTGRESKEY'] import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) im tryng to push to master but throws this: KeyError: 'MYPOSTGRESKEY' it´s weirds cause im using the database url what obtain from the command $ heroku config -
Matching query does not exist error
There are a bunch of people on this site have had a similar questions to mine, but I can't seem to find one that has solved it the way I want it to. I'm trying to get a password out of a database so that I can send an email automatically. To do this, I am calling Credential.objects.get(username='foo').password. This is where I get the error. What's really weird about this is I already had access to this database in a python console, and I've created a row in it. I have no clue why it's not showing up! Other people seem to recommend doing the following: try: Credential.objects.get(username='foo').password except Exception as e: return None All that this is doing is making sure the program doesn't return an error. This doesn't help me because this can't fail. An email must be sent and this call must get it. I'm almost certain I'm calling the right function for this, but I've been wrong before. Any help on this would be greatly appreciated. credential.py (not putting up max_length for security reasons): import d_models as models class Credential(models.Model): username = models.CharField() password = EncryptedCharField() -
Django - Form Signed up. Get Name from URL and save in hidden first_name
On my form signed up I want to override the behavior I want to get from url www.example.com/accounts/signup/?name=Michael and save the name as first_name. But I need that input first_name hidden What i've tried: class SignupForm(forms.Form): def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.save() <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> <input type="hidden" name="{{ form.first_name }}" value="test" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> So The form would be something like: e-mail; password but also save first_name as Michael. Thanks for help! -
Server profile pic users on Django with DEBUG = False
I was deployng my project to Heroku and set up the DEBUG option to False. Until that, all was working ok. But, now, I can't server the user profile images. I want to server only with the Django, not with Apache or Nginx. I know that it's not the best option, but I don't need the best way to do this, so, if exists any way to server this with only the Django, will better to me. This is my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'saga', 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' This is my urls.py: from django.conf import settings urlpatterns = [ #URLs ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And I think that's goodn say that I'm using the WhiteNoise to server the Static Files on Heroku. -
Django Installation Issue
I am using Hostgator shared hosting. I have done the following: Installed virtual environment Installed flup. Created index.fcgi Created .htaccess It gives 404 not found. Missing WSGI when run from shell. -
Django + Redis + Celery Struggle to set the tasks
I have been trying to set up my scheduled task to run every x minutes, but I am not making any progress. I read the documentation and tried different approaches to the problem but I am obviously still doing something wrong. celery.py CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/1' from datetime import timedelta from celery import Celery app = Celery('taskscheduler', broker=CELERY_BROKER_URL, backend=CELERY_RESULT_BACKEND) app.autodiscover_tasks() CELERYBEAT_SCHEDULE = { 'schedule-name': { 'task': 'taskscheduler.task.just_print', 'schedule': timedelta(seconds=5), }, } task.py from celery import shared_task @shared_task def just_print(): print("Print from celery task") __init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from taskscheduler.celery import app as celery_app __all__ = ['celery_app'] All of the files are inside one of the many apps folders. What I am trying to achieve is basically to set up this task when I start the server and run it every x seconds, as long as the server is on. -
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/$']
Am trying to develop an app for student management. Every thing seems to be working fine. but am receiving an errors at some point. If i open the list view it shows all the student, if i click a student photo it will open a detail view of that student for me, then if i click add button inside the view it will show me (NoReverseMatch at /add_subj/3/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$'] ). I want to be able to add subject to a particular id. Please need some help, am new in django. This is the link to my models.py, views.py and urls https://gist.github.com/AnyiLloyd/a963e9e3f52aa8f46fd7ef9a6ec0dddb -
Django Pagination + Regroup
So I'm working on a list view for one of my models and I want to display them by group like: Group 1 - Item - Item Group 2 - Item Group 3 - Item - Item - Item That's easy enough to do with regroup tag in Django, no problem there. But what if I want to paginate the queryset? Unless each group has the exact same number of items (they don't), I'll run into problems if I just do the standard: queryset = Model.objects.all() paginate_by = 10 So I'm wondering if there's anyway to paginate by group, or is Django's built in paginator totally incompatible with the regroup tag? From my searching I get the feeling that I'd have to implement a custom pagination system to achieve this, but I couldn't find anything conclusive so thought I'd check here in case I'm missing something and possibly get some clean alternatives. -
Django polls app not taking votes on selecting and clicking votes
Problem statement : I am new to Django and trying polls app. am currently in the place where we create vote function to accept votes and show results. but problem am facing is it's not capturing the vote. when I go to the results page it shows the names but no votes.Below are the code and snips. def results(request, question_id): i = get_object_or_404(Question, pk=question_id) return render(request, "span/results.html", {'i': i}) def vote(request, question_id): i = get_object_or_404(Question, pk=question_id) try: selected_choice = i.choice_set.get(pk=request.POST['choice']) except: return render(request, 'span/detail.html', {'i': i, 'error_message': "Please select a choice "}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('span:results', args=(i.id,))) above is my views.py and below shoing my detail: {% extends 'span/base.html' %} {%block main_content %} <h1> {{i.question_text}}</h1> {% if error_message %} <p><strong>{{error_message}}</strong></p>{% endif %} <form action = "{% url 'span:vote' i.id %}" method = "post"> {% csrf_token %} {% for j in i.choice_set.all %} <input type = "radio" name = "j" id="j{{forloop.counter}}" value = "{{j.id}}"/> <label for ="j{{forloop.counter}}">{{j.choice_text}}</label> <br> {% endfor %} <input type = "submit" value = "vote"> </form> {% endblock %} and my result {% extends 'span/base.html' %} {% block main_content %} <h1> {{i.question_text}}</h1> <ul> {% for j in i.choice_set.all %} <li> {{j.choice_text}} -- {{j.votes}} vote{{ j.votes|pluralize}} … -
Django: is it possible to calculate the sum of an annotated field within a group by segment?
Django: 2.0.2 DB: PostgreSQL: 10.1 I have a QuerySet of Event objects: I am annotating the filtered Sum of an IntegerField from a many-to-many on each Event based on a property of each object in the many-to-many, let’s call this event_cost) I am then grouping by the event month using ‘.values(‘event_month’)’ where event_month contains the event’s year and month I then want to annotate the Sum of event_cost within each month Generally the code looks like this: events_queryset = Event.objects.filter(...somefilters...) ids_list = [...listofids...] events_queryset\ .annotate(relevant_salaries=Sum(‘attendees__salary', filter=Q(attendees__id__in=ids_list)))\ .annotate(event_cost=F('relevant_salaries') * F('length'))\ .values(‘event_month’)\ .annotate(segment_total_cost=Sum(‘event_cost’)) The issue I am running into is having my event_cost annotation to be available after the .values() call: If I don’t add event_cost to values() it is not accessible to be used within Sum() after the values() call. However, if I do include it in values() the GROUP BY effect of the values() call is not correct (instead of getting values of 1/18, 2/18, 3/18, for example, the result would be more like (1/18, $12), (1/18, $26), ….. (2/18, $3), (2/18, $19)….. ($s added for clarity)) Is there a way to accomplish this query through the Django ORM or must this be done as a raw SQL query? Let … -
Having issues with Django URL mapping
Hi I am trying Django for an upcoming project and going through a tutorial and running into issue with defining URL paths. Below is the project structure showing the urls.py at the project root. The urls.py in my timer package is pretty simple: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] However when I launch the application and navigate to localhost:8080/timer/ I am getting a 404. Any suggestions what I should be looking at? Thanks Suresh -
how to: creating a view and serializer for adding, editing, and deleting objects with foreign relationships django rest framework
I am having a very hard time connecting all the documentation on django and django rest framework on how to create a view and serializer that allows for a foreign key. Example I have these models. class SearchCity(models.Model): city = models.CharField(max_length=200) class SearchNeighborhood(models.Model): city = models.ForeignKey(SearchCity, on_delete=models.CASCADE) neighborhood = models.CharField(max_length=200) I want to be able to choose a city and then view all the neighborhoods that city has, and be able to add a neighborhood, edit and neighborhood and delete a neighborhood. so perhaps the url to get all the neighborhoods a city has or create a new neighborhood for a city url(r'^neighborhood/(?P<citypk>[0-9]+)$', SearchNeighborhoodListCreate.as_view()), and one to edit and delete a neighborhood: url(r'^neighborhood/(?P<citypk>[0-9]+)/(?P<neighborhoodpk>[0-9]+)$',SearchNeighborhoodDetail.as_view()), I am currently using the ListCreateAPIView and the RetreiveUpdateDestoryAPIView from DRF Generics I understand that we have options like query_setrelated that allow us to get all the relations a model has. I know we have the x_set option. used like this in my example. Searchcity.SearchNeighborhood_set.all() I know we have related serializers and that the proper way I create them is such: class CityNeighborhoodSerializer(serializers.ModelSerializer): neighborhood = serializers.PrimaryKeyRelatedField(many=True, read_only=False) class Meta: model = SearchCity fields = ('City', 'neighborhood') But how do I use it in this use case? http://www.django-rest-framework.org/api-guide/relations/#serializer-relations … -
Django login after registration
Im' trying to auto login the user after registration but anything seems to work. Does not work: if registroForm.is_valid(): registroForm.save() user = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) request.session['_auth_user_id'] = user.pk request.session['_auth_user_backend'] = user.backend return JsonResponse({}) Does not work: if registroForm.is_valid(): registroForm.save() usuario = authenticate(username=registroForm.cleaned_data['username'], password=registroForm.cleaned_data['password1']) login(request, usuario) return JsonResponse({}) I'm using Django 2.0 -
gentelella for django doesn't recognize changes on custom.css
I am trying to apply gentelella bootstrap template for django, so I copied the app directory into my own django project. I am using some of-the-box html templates, so I copy them to the templates directory of the proper application, but I keep all static content on the app directory. The problem is when I modify the app/static/build/css/custom.css file, because I the html files don't reflect the change. In this case, I added the new class yellow to the custom.css file, and I added such class to some objects in the index2.html file, but the color of the text didn't change. This the django project directory tree: ├── Attractora │ ├── ActorsManagerApp │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── templates │ │ │ └── ActorsManagerApp │ │ │ ├── index2.html │ │ │ └── profile.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── Attractora │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── app │ │ ├── __init__.py │ │ ├── __init__.pycn-36.pyc │ │ ├── admin.py │ │ ├── … -
How to allow any user to upload an image with django-filebrowser-no-grapelli and tinymce?
I can't seem to find an answer for this anywhere so I think it will be useful for other people looking for it. I can only upload an image if I'm the admin user. Otherwise I get an unauthorised access warning from the Django admin, prompting me to login as admin. My guess is that I need to change the url pattern, which right now starts with "admin" as it can be seen below. re_path(r'^tinymce/', include('tinymce.urls')), re_path(r'^admin/filebrowser/', site.urls),