Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selectively apply CSS Styles to Radio Buttons in Quiz in Django
I have users take a quiz. After each question, I want to show them whether their answer was correct or incorrect. The correct answer should be highlighted in Green, and their answer (if incorrect) should be highlighted in red (using Twitter Bootstrap styles). I am currently rendering the quiz results page in Django and HTML like so: {{ player.question }} <div class="myradio"> <label for="choice_1"><input id="id_1" type="radio" value="q1" disabled/> {{q1}}</label> </div> <div class="myradio"> <label for="choice_2"><input id="id_2" type="radio" value="q2" disabled /> {{q2}}</label> </div> <div class="myradio"> <label for="choice_3"><input id="id_3" type="radio" value="q3" disabled /> {{q3}}</label> </div> <div class="myradio"> <label for="choice_4"><input id="id_4" type="radio" value="q4" disabled /> {{q4}}</label> </div> <b><p>Correct Answer: {{solution}}</p><b> Total Score: {{total_score}} I am storing the solution to the question in {{solution}}. I have been trying to figure out how to selectively apply CSS filters if, for example, {{q1}} == {{solution}} that should be highlighted green. I can grab the participant's answer with {{player.submitted_answer}}, and so want to highlight a div element red if {{player.submitted_answer}} != {{solution}}. I have tried messing around with if statement blocks, but can't seem to get it right. Any ideas? -
How do i include bootstrap class in django forms without widget-tweaks?
I want to make a site using django which include forms, but i am not able to find a way to include form-control classes in fields. Is there any way to do so? When i try to install Django-widget-tweaks Could not find a version that satisfies the requirement django-widjet-tweaks (from versions: ) No matching distribution found for django-widjet-tweaks -
How do I access the the following model tables
So I am working on a Django project and I am a beginner. I have a page which displays the list of incubators (from the database). When I click on them, I want to show the their details for which I have made a separate model class. models.py: class Incubators(models.Model): # These are our database files for the Incubator Portal incubator_name = models.CharField(max_length=30) owner = models.CharField(max_length=30) city_location = models.CharField(max_length=30) description = models.TextField(max_length=100) logo = models.FileField() verify = models.BooleanField(default = False) def get_absolute_url(self): return reverse('main:details', kwargs={'pk': self.pk}) def __str__(self): # Displays the following stuff when a query is made return self.incubator_name + '-' + self.owner class Details(models.Model): incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE) inc_name = models.CharField(max_length = 30) inc_img = models.FileField() inc_details = models.TextField(max_length= 2500) inc_address = models.TextField(max_length = 600, default = "Address") inc_doc = models.FileField() inc_policy = models.FileField() def __str__(self): return self.inc_name And this is my views for details: def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.all() return render(request, 'main/details.html', {'inc': inc, 'details': details}) And this is my urls.py urlpatterns = [ url(r'^home/', views.home, name='home'), # Home page url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page url(r'about/', views.about, name='about'), # Websie about page url(r'results', views.result, name = … -
Check if an object exists in django content type framework
I want to be able to check if the object exists using get_object_for_this_type content_type = get_object_or_404(ContentType, pk = id1) if content_type.get_object_for_this_type(pk= id2).exists():` This is obviously not working because it's not a query. Is there a way around it without calling the actual mode. I'm trying to avoid try and except as proposed in the following answer: Django - Proper exception for ContentType.get_object_for_this_type() -
Geodjango intepreting MultiPolygon as LinearRing
I'm importing some OSM data from Trimble into a PostGIS database to process it as part of a Django app. This works fine for points and lines but I'm struggling with the polygons. The import appears to work fine: shp2pgsql -d -I aeroway_polygon_polygon.shp aeroway_polygon | psql -d osm Django InspectDB interprets the data in a sensible manner: ./manage.py inspectdb > models.py models.py contents: class AerowayPolygon(models.Model): gid = models.AutoField(primary_key=True) id = models.FloatField(blank=True, null=True) osm_id = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True) z_order = models.FloatField(blank=True, null=True) aeroway = models.CharField(max_length=80, blank=True, null=True) name = models.CharField(max_length=80, blank=True, null=True) name_en = models.CharField(db_column='name:en', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. operator = models.CharField(max_length=80, blank=True, null=True) ref = models.CharField(max_length=80, blank=True, null=True) faa = models.CharField(max_length=80, blank=True, null=True) iata = models.CharField(max_length=80, blank=True, null=True) icao = models.CharField(max_length=80, blank=True, null=True) website = models.CharField(max_length=80, blank=True, null=True) contact_we = models.CharField(db_column='contact:we', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. phone = models.CharField(max_length=80, blank=True, null=True) contact_ph = models.CharField(db_column='contact:ph', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. ele = models.CharField(max_length=80, blank=True, null=True) tower_type = models.CharField(db_column='tower:type', max_length=80, blank=True, null=True) # Field renamed to remove unsuitable characters. geom = models.MultiPolygonField(srid=0, dim=4, blank=True, null=True) class Meta: managed = False db_table = 'aeroway_polygon' Any attempt … -
dynamically show django model objects attributes with javascript
I am trying to dynamically change text on a webpage on hover that is grabbed from the related. I have a html area tag on a map. <map name="Map"> <area shape="rect" title="Govan" coords="60,510,160,550" alt="Govan" onmouseover="mouseOver(alt)" onmouseout="mouseOut()" href='govan'> <area shape="rect" title="Ibrox" coords="200,620,280,660" alt="Ibrox" onmouseover="mouseOver(alt)" onmouseout="mouseOut()" href='ibrox'> and a java script function that takes the alt as it's input, which is the same as the object name for the stations. class Station(models.Model): name = models.CharField(max_length=128, unique=True) stringName = models.CharField(max_length=128,default='') firstTrainMonSat = models.TimeField(blank=True,null=True) lastTrainMonSat = models.TimeField(blank=True,null=True) firstTrainSun = models.TimeField(blank=True,null=True) lastTrainSun = models.TimeField(blank=True,null=True) latitude = models.DecimalField(max_digits=8, decimal_places=6, blank=True, null=True) longitude = models.DecimalField(max_digits=8, decimal_places=6, blank=True, null=True) slug = models.SlugField(unique=True,default='') def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Station, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'stations' def __str__(self): return self.name I basically want to display the attributes of specific objects (stations) when i get that object name in as text from in the javascript function. Which currently just displays the alt tag that I get in: function mouseOver(x) { document.getElementById('station').innerHTML = x; } -
How we can perform different actions in single HTML form for changing url dynamically in django?
HTML Template <form action="" method="post"> ... ... <input type="submit" name="Next" value="Next"/> <input type="submit" name="Cancel" value="Cancel"/> </form> I want to navigate on different pages by click this buttons. Specifically in django environment. -
Worker failed to boot
I'm trying to deploy my Django project on Heroku, but something is going wrong, and I'm not able to found out what is happening, and what to do in order to solve this. I read in other posts that the problem may be something related with Gunicorn, but I can't solve it. (env) ignacio@ignacio:~/atletico$ heroku logs 2018-03-15T18:04:33.770218+00:00 app[web.1]: [2018-03-15 18:04:33 +0000] [4] [INFO] Reason: Worker failed to boot. 2018-03-15T18:04:47.082000+00:00 heroku[web.1]: Starting process with command `gunicorn mysite.wsgi --log-file -` 2018-03-15T18:04:49.411412+00:00 heroku[web.1]: Process exited with status 3 2018-03-15T18:04:49.139027+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Starting gunicorn 19.7.1 2018-03-15T18:04:49.139593+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Listening at: http://0.0.0.0:25381 (4) 2018-03-15T18:04:49.139786+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [4] [INFO] Using worker: sync 2018-03-15T18:04:49.149373+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [ERROR] Exception in worker process 2018-03-15T18:04:49.149376+00:00 app[web.1]: Traceback (most recent call last): 2018-03-15T18:04:49.149391+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-03-15T18:04:49.149394+00:00 app[web.1]: worker.init_process() 2018-03-15T18:04:49.143828+00:00 app[web.1]: [2018-03-15 18:04:49 +0000] [8] [INFO] Booting worker with pid: 8 2018-03-15T18:04:49.149396+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-03-15T18:04:49.149398+00:00 app[web.1]: self.load_wsgi() 2018-03-15T18:04:49.149400+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-03-15T18:04:49.149401+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-03-15T18:04:49.149408+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-03-15T18:04:49.149411+00:00 app[web.1]: self.callable = self.load() 2018-03-15T18:04:49.149413+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, … -
How can I mock the created field of a model that inherits from TimeStampedModel using model_mommy?
I am trying to test a date filter but have been unable to set the created date using mommy.make(). When I make the objects with model mommy the created field is set to the time the objects were created rather than what I passed in with mommy.make() def test_mommy(self): today = arrow.now() yesterday = today.replace(days=-1) mommy.make('Model', created=today.naive) mommy.make('Model', created=yesterday.naive) model_1_created = Model.objects.all()[0].created model_2_created = Model.objects.all()[1].created self.assertNotEqual(model_1_created.strftime('%Y-%m-%d'), model_2_created.strftime('%Y-%m-%d')) This test fails with the Assertion Error: AssertionError: '2018-03-15' == '2018-03-15' I may have a misunderstanding of how model_mommy creates these objects. But I would think this should create it and set the created dates properly. Though it looks like the default TimeStampedObject behavior is taking over. -
How to get the foreignKey related primary key (pk) in the same model in django?
I need to get the id (pk) of a related model.foreignKey object in order to set the "upload_to" attr of a model.FileField of the same model. Something like this: class myClass(models.Model): related_model = models.ForeignKey(RelatedModel,on_delete=models.CASCADE) file = models.FileField(upload_to=str(related_model.id)+"/") So for example, if the related_model has the primary_key 10 the upload_to attr has to be "10/" It is possible or I have to set that value in the view.py file when the object is created? -
Updating SQLite values periodically
Say I have the following four records (assume there are more): record 1 record 2 record 3 record 4 area California Texas California California food Lobster Lamb Rabbit Bagels popular Bagels Elk Rabbit Rabbit Right now I am adding new records into the database by manually choosing an area and a food. The popular field is then automatically populated by finding the most common food for that specific area at the time of entry. For example, if the above four records were the ONLY records in the entire database, then if I were to add another record with area: California and food: Bagels then popular (for the record I just added) would automatically be assigned the value Bagels because there would be two Bagels in the food field, for the area California. The above is already working, which I achieve the above with the following code: popular = list(ModelData.objects.filter(area=area).values_list('food', flat=True)) Counter(popular).most_common() The problem is, the above still leaves existing records in the database with the incorrect popular value; because popular is only calculated at the time of entry, and never 're-calculated' when more entries are added. Using the above example (adding a new record with area: California and food: Bagels), … -
POST document with Django RequestFactory instead of form data
I'd like to build a request for testing middleware, but I don't want POST requests to always assume I'm sending form data. Is there a way to set request.body on a request generated from django.test.RequestFactory? I.e., I'd like to do something like: from django.test import RequestFactory import json factory = RequestFactory(content_type='application/json') data = {'message':'A test message'} body = json.dumps(data) request = factory.post('/a/test/path/', body) # And have request.body be the encoded version of `body` The code above will fail the test because my middleware needs the data to be passed as the document in request.body not as form data in request.POST. However, RequestFactory always sends the data as form data. I can do this with django.test.Client: from django.test import Client import json client = Client() data = {'message':'A test message'} body = json.dumps(data) response = client.post('/a/test/path/', body, content_type='application/json') I'd like to do the same thing with django.test.RequestFactory. -
Django profile() missing 1 required positional argument: 'username'
I'm following the instructions from a django book, but I'm getting an error (TypeError: profile() missing 1 required positional argument: 'username') while trying to implement a profile view. What I want is to be able to see the profile of a user by going to profile/johndoe for example. Here is my view: @login_required def profile(request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: return redirect('/the_pantry/home') userprofile = UserProfile.objects.get_or_create(user=user)[0] form = UserProfileForm({"name": userprofile.name, "age": userprofile.age, "bio": userprofile.bio, "picture": userprofile.picture}) if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=userprofile) if form.is_valid(): form.save(commit=True) return redirect("profile", user.username) else: print(form.errors) context_dict = {"userprofile": userprofile, "selecteduser": selecteduser, "form": form} return render(request, 'the_pantry/profile.html', context = context_dict) And my urlpatterns: url(r'^profile/(?P<username>[\w\-]+)/$', views.profile, name='profile'), And my UserProfile model. class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length = 60, default = "") picture = models.ImageField(upload_to='profile_images', blank = True) age = models.IntegerField(default=0) bio = models.CharField(max_length = 500, default = "") def __str__(self): return self.user.username Additionally, I'm using django's default login and User. I have an html file for the profile (profile.html) as well. Everything is exactly like in the book. The error I'm getting is: Traceback (most recent call last): File "C:\Users\2254765p\Envs\rango\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\2254765p\Envs\rango\lib\site-packages\django\core\handlers\base.py", line … -
Passing parameters to get request in django template
I'm trying to create a link to a page in django via a GET request. But, I have to pass the value of a parameter. How do I do so? urls.py path('questions/<int:user_id>/', views.recommendationquestions,{'template_name':'questions.html'}, name = 'questions'), answers.html <a href="{% url 'questions' {{rlist.0.userId}} %}">Rate more movies</a> -
Django Administrator Theme
I'm going to develop an app using Django2.0.3 . Now it is questionable that if I can replace HTML admin with default Django admin template completely? Wouldn't be any security problem?? Please guide me to change -
How to serve staticfiles in Django 2.* when DEBUG = False?
I've stucked with deploying Django 2.* on production server. When i set DEBUG = False Styles in admin page simply stopped serving by debugger or something and i have no clue or ideas how to serve static files. My settings\actions: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then just python manage.py collectstatic and no styles in admin =( Will be appreciate for any help. -
Requests Sessions - Only Works First Time
I am working with Django Python. So my code generates a new 10 letter string every time the user connects to it - this acts as a unique identifier for the customer, in the wider picture. But my problem is the following.... In order to generate the random string, the user needs to be logged in. A request is then made to the random string api to generate the string, before returning it. This is the block of code (using hardcoded testing values, and removed the exact public api to minimise fake requests): ### Code To Log In s = requests.Session() credentials = {'username': 'user', 'password': 'pass'} s.post("http://XXXXXX.pythonanywhere.com/api/login/", data=credentials) ### Code to connect to Create String API, and return it as JSON r = s.post("http://XXXXXX.pythonanywhere.com/api/createstring/") results = r.json() I then parse this in my client as normal. The first time I run this code, all connections work fine and the JSON is parsed and everything works perfectly. The random string is generated and printed on the client, as it should. However, when I then run the code again, I get the status code of 500 and no connection is made. When I check the error log on my PythonAnywhere, it … -
Why a lot of ORM does not use pure python comparison in query?
A lot of ORMs (like Django ORM or MongoEngine) use "keywords magic" like id__lte=1 instead of more native Model.id <= 1 (like in SQLAlchemy). But why? It completely breaks down static analysis by IDE (refactoring, autocompletion and type checking). Maybe there are some reasons that I can't see? Or just not so many people think that Model.id <= 1 is better than id__lte=1? Example for Django ORM: Blog.objects.get(name="Cheddar Talk", user_reviews__lte=5) Example for SQLAlchemy session.query(Blog).filter(Blog.name == "Cheddar Talk", Blog.user_reviews <= 5) -
Any library for dynamic forms creation in Django
I wanted to develop a app, where users will create forms with their choice of fields, example a employer want to create a job seeker form with different fields and an other one with different fields, is there any Django library which supports this type of feature which can be used in admin and forms could be rendered at site ? I have been looking for this and found a similar one here but the issue is this is for old Django version, it doesn't work with latest (2.0.3) Appreciated. -
How to authorize only PersonalTrainers to access view but check if objects belong to current PersonalTrainer
I'm writing this django API using django-rest-framework and I'm stuck with this authorization stuff. This is my endpoint: /api/v1/personal_trainers/:id/invites/ I need to authorize only PersonalTrainers to access this view, so I have written this custom permission: personal_trainers/permissions.py class IsPersonalTrainerUser(permissions.BasePermission): """ Allows access only to personal_trainers users. """ def has_permission(self, request, view): return request.user and request.user.is_personal_trainer This is how I authorized the users to access the invites invites/views.py class InviteCreateList(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated, IsPersonalTrainerUser, ) serializer_class = InviteSerializer def get_queryset(self): return get_list_or_404(Invite, personal_trainer=self.kwargs['personal_trainer_pk']) def perform_create(self, serializer): get_object_or_404(PersonalTrainer, pk=self.kwargs['personal_trainer_pk']) serializer.save(personal_trainer=self.request.user.personaltrainer) Now I need to authorize the personal_trainers to read/write ONLY their invites. I have been reading about django object permission. http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions How can I do that? -
How to make a custom field with multiple db fields in Django
I have a class: class MyCustomType(object): a, b = 0, "" def __init__(self, a, b): self.a = a self.b = b I want to make a custom field class for MyCustomType. class MyCustomField(models.Field): @staticmethod def parse_value(value): # magic return MyCustomType(a, b) def from_db_value(self, value, expression, connection): if value is None: return value return self.parse_value(value) def to_python(self, value): if isinstance(value, MyCustomType) or value is None: return value return self.parse_value(value) How can I use two db fields for storing a and b data? a is an integer and b is a string? -
https facebook login automatically redirects to http
My web application (django 1.10) is currently deployed on https, however when I try logging using my social login (facebook) it takes me to http instead of https. I want the user to remain on https instead of being redirected to http. I have tried the below, If I remove my listeners on my aws load balancer listener port 80, I will get an error logging into the app using my facebook account. If I remove the http callbacks from my facebook Valid OAuth redirect URIs. It will prompt an error when I try logging in. I tried looking for the login script within my social accounts third party library, somehow my login script should be a https instead of a http but couldnt find anything resembling a http direct coe it. I am looking for suggestions on tips on how I can fix this. Thanks to anyone who has any idea in advance. -
Downloading Zip file through Django, file decompresses as cpzg
My goal is to parse a series of strings into a series of text files that are compressed as a Zip file and downloaded by a web app using Django's HTTP Response. Developing locally in PyCharm, my method outputs a Zip file called "123.zip" which contains 6 individual files named "123_1", "123_2 etc". containing the letters from my phrase with no problem. The issue is when I push the code to my web app and include the Django HTTP Response the file will download but when I go to extract it it produces "123.zip.cpzg". Extracting that in turn gives me 123.zip(1) in a frustrating infinite loop. Any suggestions where I'm going wrong? Code that works locally to produce "123.zip": def create_text_files1(): JobNumber = "123" z = zipfile.ZipFile(JobNumber +".zip", mode ="w") phrase = "A, B, C, D, EF, G" words = phrase.split(",") x =0 for word in words: word.encode(encoding="UTF-8") x = x + 1 z.writestr(JobNumber +"_" + str(x) + ".txt", word) z.close() Additional part of the method in my web app: response = HTTPResponse(z, content_type ='application/zip') response['Content-Disposition'] = "attachment; filename='" + str(jobNumber) + "_AHTextFiles.zip'" -
install ssl certificate in django on window server
How to install SSL certificate in django based web application running on windows server. one window service is running for this application and there are some other applications running under it such as nssm, nginx and apache Thanks in advance -
How to store a file in memory with Python (django)?
I have this code: NNModel.py import pickle from keras.models import load_model def load_obj(name): with open('/home/user/' + name + '.pkl', 'rb') as f: return pickle.load(f) def load_stuff(): model = load_model("/home/user/model2.h5") voc = load_obj('voc') return (model,voc) It loads my files when I use this function, I'd like to load them to some static or singleton ?class? on the first time and then access that file. How can I achieve that in Python/django? This file is fairly big and right now I belive every request loads it into memory which is not efficient I guess...