Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using RESTful API and Django: how to temporarily add data into backend?
I am currently building a webapp (that will be presented as a single site eventually) using django and sqlite - the goal is to present an interactive front end where the user is able to see a randomized sample of the data I am storing. At this point I have a working connection between the sql database and what is presented in the views, but the way I have it set up I must enter the data manually. I would like to use an API (NYTimes) to automatically be called upon a few times a day, store what is given from the API, and present it on a basic JavaScript page. I was thinking the best method would be to call GET from the API in the JavaScript file of the view, and then load it into the backend --- and this is where I get a bit lost. (As you can tell I am new at this) I have tried searching for a method like this, but nothing seems to do quite what I need. If I am missing anything big or if you have any suggestions/solutions, I would love to hear! -- Thanks in advance -
Django: How should I structure models for this?
I am trying to make my first website. I am using Django for it. I have these models right now related to which I have question: class Clinic(models.Model): name = models.CharField(max_length=100) DOC_DAYS_CHOICES = ( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ) DOC_DAYS_SHIFTS = ( 'Morning', 'Afternoon', 'Evening' ) class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') days = models.CharField(max_length=200) time = models.TimeField() shift = models.CharField(max_length=15) I am stuck with this thing. I have been modifying the models as I go along. Now I don't know how to achieve what I want. I have attached two images. One shows how my data will be and another shows how I would like it to appear on page. I would like to structure the models such that code is efficient that what I want display should make a lesser DB hits anything I can achieve with prefect? As the image shows. Each doctor has multiple clinics. Then 7 days of week he can have 3 shifts per day for each clinic. -
Django models design
I am working on a quiz app on Django and have the following models - User, Test, Question and Answer. The Test model acts as a wrapper for the Questions model. This is what my models looks like at present - models.py class Test(models.Model): def id_count(): current_count = Test.objects.count() current_count += 1 return current_count test_id = models.PositiveIntegerField(default=id_count,primary_key=True) test_description = models.CharField(max_length=255) class Question(models.Model): def id_count(): current_count = Question.objects.count() current_count += 1 return current_count test = models.ForeignKey(Test,on_delete=models.CASCADE) question_id = models.PositiveIntegerField(default=id_count,primary_key=True) question_text = models.CharField(max_length=255) option_one = models.CharField(max_length=12,default="Always") option_two = models.CharField(max_length=12,default="Never") class Answer(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) customuser = models.ForeignKey(CustomUser,on_delete=models.CASCADE,blank=True, null=True) original_answer_score = models.IntegerField(default=-1) The current models basically allow every user to answer the same question multiple times. How can I design my models to allow every user to answer one question only once? Thanks. -
Django is it written good?
I have a question to u guys. Is the href in code written good without url? html template <div class="panel-body anime-list text-center"> <div class="btn-group btn-group-xs"> {% for i in alphabet %} <a href="{{i}}" class="btn">{{i}}</a> {%endfor%} </div> </div> urls urlpatterns = [ path('', views.list, name='list'), re_path(r'^[A-Z]{1}/', views.list_detail, name='list_detail')] views from django.shortcuts import render import string from django.http import HttpResponse alphabet = string.ascii_uppercase def list(request): context = {'alphabet': alphabet} return render(request, 'list/list.html', context) def list_detail(request): return HttpResponse('Something') -
Check if locale is in languages list in settings Django
is there a way to check if locale = 'some locale' is in settings.LANGUAGES I do like this: lang ='en' languages = settings.LANGUAGES lang_found = False for language in languages: if lang in language: lang_found = True break I think it is not a good way. -
How to import RegistrationForm from forms.py?
I have created two classes in forms.py class RegistrationForm(UserCreationForm): class EditProfileForm(UserChangeForm): And, I have to import them in views.py. Do help. -
2 Rows and 3 columns using bootstrap in Django
Trying to iterate multiple posts through a loop, into 2 rows of 3 items. Currently my code looks like this {% for post in post.all %} <div class="row"> <div class="col-md-4"> <div class="thumbnail"> <div class="caption"> <h3>{{ post.title }} - {{post.assignment_level}}</h3> <p>by {{post.author}} from {{post.pub_date}}</p> <h4>{{post.assignment_body}}</h4> <p><a href="#" class="btn btn-primary" role="button">Read...</a></p> </div> </div> </div> </div> {% endfor %} {% endblock%} this gives me one column of 6 posts. How do I split them in to 2 rows of three posts. Really been googling this. Thank you in advance -
Using CAS server/client within Django to log into two sites concurrently
I've got a working example of a CAS server using django-mama-cas and two CAS clients using django-cas-ng. Both clients can authenticate via the server, but when I log into one I'm logged out of the other. I need to have access to both at the same time so I can redirect to website B to store the OAuth codes and seamlessly pass back to Website A. Does anyone know of config options in either the server or client software that would allow me to pass the current user between sites? Reason for this need: We have two Django-based websites - Website A deals with data visualisation, website B handles data collection and shares it via an API. The flow I need is: Login to Website A Authorise via 3rd party website and gain OAuth tokens OAuth redirect URL to Website B to store OAuth tokens in data warehouse / API Finally, redirect from Website B back to Website A to visualise data. My thinking is that a CAS setup could handle the shared authentication. I hope someone who has experience of these Python libraries or CAS in general could provide some pointers. I have a working version of the three … -
Celery task to write file in subprocess call
dene is a celery task to call subprocess and in the subprocess script, I want to write some text in file (auth_path) when each function in script done. The problem is, if I call python3 apt.py from shell, text written in the file. but when i call subprocess in task, progress works correctly, all functions works in apt.py but nothing written in aut_path. Why I cannot write some texts when I call script from subprocess. @task(name="dene") def dene(): cmd = ['timeout', '240', 'python3', "apt.py"] output = check_output(cmd) in apt.py there is a write func and calling it again and again. def write_out_auto(msg): with open(aut_path, 'a') as the_file: the_file.write(msg +'\n') write_out_auto("Finished the section 2") -
How to use scrapy with django and upload it to heroku
I am using scrapy to scrape some data. But I want to use it with django for user interface and to save the data to database. Also I want to know how can I upload it to heroku -
when i am adding new product or modifying the record it is not showing the result set in search after building index in django oscar
As I used Solr for search backend, and once my product get index and now the second time when I add new products and change price after index created that product not being search in and sorting of price also not worked for new change ( i need to rebuild index then start the java server then will work properly ), is there any other solution for the same . I am using Solr 4.7.2. -
Django - admin.get_urls not actually getting my new urls
I am working on an existing codebase and stumbled on a admin mixin that uses the get_urls method. class MPTTEditAdminMixin(object): def get_urls(self): info = self.model._meta.app_label, self.model._meta.model_name remove_view = "%s_%s_change" % info original = super(MPTTEditAdminMixin, self).get_urls() filtered = [p for p in original if p.name != remove_view] return [ url(r'^(?P<object_id>\d+)/edit/$', self.admin_site.admin_view(self.change_view), name='%s_%s_real_change' % info), url(r'^(?P<object_id>\d+)/$', self.admin_site.admin_view(self.readonly_view), name='%s_%s_change' % info), ] + filtered def readonly_view(self, request, object_id, form_url='', extra_content=None): (...) It is used on multiple admin classes (hence the somewhat convoluted use of the 'info' variable), however, I am encountering the following bug: Links to the '%s_%s_real_change' url are not working, instead the code always seems to refer to the '%s_%s_change' url link. I have moved the 'real_change' code above the 'change' code yet the problem persists. Its almost as if it stops parsing the url as soons as it completes the 'r'^(?P\d+)' part. Does anyone know why this is / what we are doing wrong? -
Django - form object has no attribute '_errors'
Im trying to create a form that will show a list of checkboxes based on a models items. Then also to be able to filter this list if required. However I am getting the below error and am not sure as to why? error: File "/usr/local/lib/python3.6/site-packages/django/forms/forms.py" in errors 174. if self._errors is None: Exception Type: AttributeError at /sites/site/auto_gen_subnets/7 Exception Value: 'AutoSubnetForm' object has no attribute '_errors' forms.py class AutoSubnetForm(forms.Form): subnet_type_data = SiteTypes.objects.all() def __init__(self, *args, **kwargs): self.site_type = kwargs.pop("site_type") # get site type if set and filter against it if self.site_type: subnet_type_data = SiteTypes.objects.filter(site_type=self.site_type) # create list for types subnet_types = [] for stype in subnet_type_data: # add tuple for each type subnet_types.append((stype.id,stype.site_type)) subnets = forms.ChoiceField( choices=subnet_types, widget = forms.Select( attrs = {'class': 'form-control'} ) ) views.py: @login_required @user_passes_test(lambda u: u.has_perm('config.add_subnet')) def auto_gen_subnets(request, site_id): #generate_subnets(site_id) from config.models import SubnetTypes site_data = get_object_or_404(SiteData.objects.select_related('site_type'),pk=site_id) subnets = None if request.method == 'GET': form = AutoSubnetForm(site_type=site_data.site_type) else: # A POST request: Handle Form Upload form = AutoSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnets = form.cleaned_data['subnets'] return render(request, 'sites/generate_subnets.html', { 'data': subnets, 'subnet_form': form, 'SiteName' : site_data.location, 'SiteID' : site_id, } ) -
How does Workers work in Django Channels
Im using django channels for a project, it normaly starts 3 workers when I run the django server using: manage.py runserver What I understood is the workers are running separate each but still sharing their variable values? How is that achieved using the inmemory solution without redis? I need to change variable independent from the worker that is running the function, I tried thread locking, but didnt solve since it seems to be 3 times the python script loaded, and not multithreading one script. Thank you in advance -
Return all objects that are referenced exactly twice by a related model
I have the following models: class Person(...): name = CharField(...) class Address(...): person = ForeignKey(Person) address = CharField(...) I need to select all persons that have exactly two addresses. So if my Address table looks like this: ------------------------- | id | person | address | ------------------------- | 1 | 1 | xyz | | 2 | 1 | xyz | | 3 | 2 | xyz | | 4 | 3 | xyz | | 5 | 3 | xyz | | 6 | 4 | xyz | | 7 | 5 | xyz | | 8 | 5 | xyz | | 9 | 5 | xyz | ------------------------- The resulting queryset should be <QuerySet [<Person: 1>, <Person: 3>]> I tried a lot, but just don't seem to get it right. I would be glad for a quick fix. -
Django Model: Display only corresponding values from Model DB by user selection
I want to create an Application in Django that displays oil parameter from a model to calculate with. My Model.py look like: #models.py class OilModels(models.Model): oil_name = models.CharField(max_length = 200, default = '') oil_density = models.DecimalField(max_digits = 9, decimal_places = 2, default = '') oil_temperature_1 = models.DecimalField(max_digits = 9, decimal_places = 2, default = '') ... The oils are added in the admin.py view: #admin.py admin.site.register(OilModels) I want to display the oil_name in a html select option like: #index.html <select> {% for oil in objectlist %} <option value="{{ oil.pk }}">{{ oil.oil_name }}</option> {% endfor %} </select> And then if the user selects an oil from the html select, I want to display only the corresponding values from the model like: #index.html <input type="number" value="{{oil_density}}" readonly /> <input type="number" value="{{oil_temperature_1}}" readonly /> ... Sadly I don't get it to work. I hope one of you has an idea and can help me. Thank you in advance. -
Build the same image multiple times with different entrypoints in Docker
I have a Django app and use Celery for background tasks. For deploying, I use Docker with Kubernetes. Deployment is automatized with Jenkins. All is good, however I feel like this can be drastically optimized. The problem is that Jenkins builds almost the same images for a django app and 5 celery workers. The only difference they have is the entry point. Django app image starts gunicorn, celery container starts, well, celery. What is the best practice to build almost the same images? I would optimally like to build the same image several times and indicate the entrypoint during the build process. Thank you for any help. -
Celery Async Tasks and Periodic Tasks together
Unable to run periodic tasks along with asynchronous tasks together. Although, if I comment out the periodic task, asynchronous tasks are executed fine, else asynchronous tasks are stuck. Running: celery==4.0.2, Django==2.0, django-celery-beat==1.1.0, django-celery-results==1.0.1 Referred: https://github.com/celery/celery/issues/4184 to choose celery==4.0.2 version, as it seems to work. Seems to be a known issue https://github.com/celery/django-celery-beat/issues/27 I've also done some digging the ONLY way I've found to get it back to normal is to remove all periodic tasks and restart celery beat. ~ rh0dium celery.py import django import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bid.settings') # Setup django project django.setup() app = Celery('bid') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() settings.py INSTALLED_APPS = ( ... 'django_celery_results', 'django_celery_beat', ) # Celery related settings CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 43200, } CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_CONTENT_ENCODING = 'utf-8' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULER … -
Custom QuerySet for related model
My Group class has a many-to-many relationship with User: group.user_set.all() Users can be active or inactive, and often I need to filter these in a group: group.user_set.filter(active=True) group.user_set.filter(active=False) It would be handy to have something like: group.user_set.active.all() group.user_set.inactive.all() I have tried setting up a Manager but I am not sure whether I should place it in Group or in User. The docs make it clear when it comes to defining a manager for a given class to tailor custom querysets for your model, but it is not so clear when you need to use custom querysets for related models. How can I do this? -
Display different edit profile forms for 2 user types in Django
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for student, the same form as for teacher is displaye... a student has different attributes so it has a different form I need to show. @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user == teacher.user: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif user == student.user: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) I'm sure mistake is somewhere in this view. -
How to add data from junction table to many to many field with DRF serializer?
I have models like the following and I need to serialize the magazine model with the DjangoRestFramework serializer: class Publication(models.Model): ... class MagazinePublication(models.Model): publication_date = models.DateField() class Magazine(models.Model): ... publications = models.ManyToManyField(Publication, through=MagazinePublication) I want to serialize a magazine instance like this so that publications contain their publication dates from the junction (through) table: magazine = { id: ..., publications = [ {id: ..., publication_date: ...} ] } is there a way to do this with DjangoRestFramework serializer? A link to the docs would be appreciated too. -
Django: postgresql full text search: search lookup: Some terms not searching
I am using Django 2.0 and postgres (PostgreSQL) 9.6.1 I am having the below model with headline and body_text: class Entry(models.Model): headline = models.CharField(max_length=255) body_text = models.TextField() def __str__(self): return self.headline The below is my content headline: cheese making body_text: The simplest way to use full text search is to search a single term against a single column in the database. For example: >>> Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]. This creates a to_tsvector in the database from the body_text field and a plainto_tsquery ... The following the search results using the the search lookup. I have added 'django.contrib.postgres' in INSTALLED_APPS. Case 1: Works In [1]: Entry.objects.filter(body_text__search='Cheese') Out[1]: <QuerySet [<Entry: cheese making>]> Case 2: Not working In [2]: Entry.objects.filter(body_text__search='Pizza') Out[2]: <QuerySet []> (the word Pizza is there in the body_text still is not searching) Case 3: Not working In [3]: Entry.objects.filter(body_text__search='vector') Out[3]: <QuerySet []> (the word vector is there in to_tsvector Case 4: Not working In [9]: Entry.objects.filter(body_text__search='Entry') Out[9]: <QuerySet []> Case 5: Not working In [10]: Entry.objects.filter(body_text__search='data') Out[10]: <QuerySet []> How to search for the terms which are not working. -
Django recommend pages based on visited
I'm building a blog using django 1.11.7, and I'm looking for a way to list recommended posts based on the posts they have already viewed on the site. I have searched and been unable to find any convenient way to do this and hope that someone here might have a solution. -
Django: Group By between two range of Dates that are not present in Database
I am currently making an API in Django Rest Framework and in that I am filtering the dates which was given by the user(coming from frontend) and after then I am grouping it in months. The problem I am facing is what if the start date is lesser than min(createddate), then the data I am getting is filtered but instead of that I need the grouped time from start date to the end date(grouped in a range), if there is no data for some months then the database should return 0. I know SQL(I am using SQL as my DB) evaluates first where clause and after group by, is there a way to group the data first and then we could apply where clause. For example: Body - I am passing to the API { "StartDate":"2017-06-01", "EndDate":"2017-08-08" } Current Response - I am getting from my API "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] Correct Response - I wanted from data "data": [ { "key": "Count", "bar": true, "values": [ [ "2017-06-01T00:00:00", 1496255400000, 0 ], [ "2017-07-01T00:00:00", 1498847400000, 0 ], [ "2017-08-01T00:00:00", 1501545600000, 1 ] ] } ] -
Django Count how many manytomany relation ships in an attribute
This is my model: class Set(models.Model): name = CharField(max_length = 25) teacher = ForeignKey(get_user_model(), null = False, on_delete = models.CASCADE) students = ManyToManyField(get_user_model(), related_name= 'set_students') and I want to know how many students are in the manytomanyfield. Ive tried this set_ = Set.objects.get(pk=id_) students = len(set_.students) But that hasn't worked. Thanks for any help!