Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there an alternative way to request JSON REST API in django?
I currently have a fully working Serializers using the Django REST Framework. I want to be able to parse data or request data that can be used in my django app. I have been using import requests r = requests.get('django_api_url') data = json.loads(r.text) I have no problem using this, but I'm trying to see if there's a better/faster way. -
Django constraint between ManyToManyField and ForeignKey
Consider I have following models: class Cargo(models.Model): name = models.CharField(default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) class Box(models.Model): name = models.CharField(default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.ManyToManyField(Cargo, blank=True) I want to avoid situation when I add some cargo object to box with different owner. For example: cargo = Cargo(owner=1) box = Box(owner=2) box.add(cargo) How to add such a constraint on a model level? -
Get object list with ajax in Django
I'm using ajax in my django aplication, it works well except when I want to get all the registers in a table. I don't know how to send from my 'ajaxview' to the javascript code and then, how to parse the result. Here is my list.html <table> <thead> <tr> <th>id</th> <th>Name</th> <th>Gender</th> <th>Birth date</th> </tr> </thead> <tbody id="clientList"> <!--Here where I want to put the client list--> </tbody> </table> <script> getAllClients(); </script> This is my urls.py from django.conf.urls import url, include from django.contrib import admin from django.urls import path from django.views.decorators.csrf import csrf_exempt from store_app import ajax as ajaxview urlpatterns = [ path('admin/', admin.site.urls), url(r'^listClients/$', csrf_exempt(ajaxview.listClients), name='listClients'), ] This is my ajax.py where I have diferent views than in views.py def listClients(request): data = [] clientlist = clients.objects.filter(clientstatus=1) #Here is where I don't know if I am doing correctly #I don't know how to send the client list or if I have to send it as a JSON #Please help here data.append({'clist':clientlist }) return HttpResponse(json.dumps(data), content_type="application/json") The last code actually work for other stuff, but not to send all the data This is my list.js script funtion getAllClients() { $.ajax( { type: "POST", url: "/getAllClients/", data: "", success: function(result) { … -
Saving data from form to database django
I am trying to add objects to database via form, but nothing happens, information does not appear in db. Here is my code, i've been searching for a few hours and found nothing models.py from django.db import models import os from django import forms from django.contrib.auth.models import User class Projects(models.Model): Cascades = [] for d, dirs, files in os.walk('pd/haarcascades'): for f in files: path = os.path.abspath(f) # формирование адреса name = os.path.splitext(f)[0] file_name_path = () file_name_path = (path, name) Cascades.append(file_name_path) ProjectName = models.CharField(max_length = 15) ProjectOwner = models.OneToOneField(User, primary_key = True) # ProjectType = models.CharField(max_length = 1) # D for Detection , C for Creating Own Cascacde CascadeType = models.CharField(max_length = 150, choices=Cascades) CascadePath = models.CharField(max_length = 150, null = True) ProjectPath = models.CharField(max_length = 100)# for later downloading ProjectReadyFilter = models.BooleanField(default=False)# 0 uncompleted project, 1 - completed forms.py from django import forms import os from .models import Projects class ChosingCascade(forms.ModelForm): class Meta: model = Projects fields = ('ProjectName', 'CascadeType',) views.py class PhotoDetectionProcessView(FormView): template_name = "pd/ChosingCascade.html" success_url = "/pd/ChosingCascade" form_class = ChosingCascade def ChosingCascade(request): def get(self, request): form_class = ChosingCascade() return render(request, self.template_name, {'form_class':form_class}) def post(self,request): form = ChosingCascade(request.POST) if form.is_valid(): post = form.save(commit = False) UserName = request.user post.ProjectOwner … -
Clean Django form fields with same name
Below is a Django form (which has been rendered in a template) whose fields have same names. I want to use the cleaned_data method to clean form data in views.py before storing them in the database. <input name='this-field' value="testValue"> <input name='this-field' value="anotherTestValue"> The problem I'm facing is that if I use form.cleaned_data['this-field'], only the last field's data is fetched i.e. in this example, the field with value anotherTestValue is fetched and cleaned. If I fetch the data using request.POST.getlist('this-field'), all the fields' data is fetched and stored as a list, but, I don't know how to clean it using cleaned_data method. Is there a way to apply the cleaned_data method to the list of field data? -
Why is Django returning a QuerySet even if flat is True?
Can someone please explain me why this is returning me a QuerySet even if flat=True ? images = Image.objects.filter(message_id=messageid).values_list('image', flat=True) I thought that if flat is set to true it would return me ValuesListQuerySet. Image is just the url which is stored in the database as VARCHAR. Maybe I do something wrong ? Thank you for your help. -
Accessing custom thumbnail options in templates
In a Django CMS project with Filer enabled, the Admin dashboard for Filer allows you to create custom Thumbnail Options, similar to defining an alias using easy-thumbnails. How do I access these options in templates? {{ obj.image.thumbnails }} allows me to choose from one of the DEFAULT_THUMBNAILS defined in abstract.py in the Filer package, such as admin_tiny_icon, but I can't for the life of me figure out how to access these custom options defined in the front-end. Thumbnail images are also not automatically created in {{ MEDIA_ROOT }} for these custom Thumbnail Options when adding new images like they are for the DEFAULT_THUMBNAILS. -
Can I change a django model field type without deleting the table?
My question is maybe idiot, but how can I change a model field type in Django without deleting the existing records? I want to change an IntergerField to a DecimalField, the makemigrations command is ok but the migrate says: No migrations to apply. I presume this is because there is already a migration, so Django tells me the migration is already applied. This occurs even if I delete the migrations file. I have read the solution was to delete the concerned rows in the sql table. Is there an other solution? Can we change model field type easily? -
Can't get model to be saved getting error: "TypeError expected string or bytes-like object"
I'm trying to take info from a few models and generate table entries in the model Calendar. I cannot get it to save the Calendar entry. Getting a TypeError. Eventually I would like this system to add calendar entries into the future based of the last scheduled monday. But currently this task will only be performed on mondays. But I would like to be able to project more than one week forward if possible. Template: <form action="{% url 'portal:custom_admin' %}" method="post"> {% csrf_token %} <div style="background-color:red; width:15%;"> <button name="submit">Project</button> DANGER! Only click on mondays, until future projecter can go based off futuremost monday generated into Calendar </div> </form> View with which I am struggling: def custom_admin(request): """ Displays MaxSettings, also Takes time_slots and create a week of it into the future (only should be done on mondays) Note:eventually this should be able to generate from the last monday in the calendar instead of today """ max_settings = MaxSettings.objects.filter() time_slots = TimeSlots.objects.filter() if request.method != 'POST': pass # Do nothing else: # Project A week forward for slot in time_slots: #there will be an if statement for each weekday if slot.day.weekday == 'Monday': new_entry = Calendar( date=datetime.timedelta(days=7), timeslot_A=slot.timeslot_A, timeslot_B=slot.timeslot_B, booked=False ) … -
Heroku worker can't access database
I have a Django project hosted by Heroku with a (postgresql) database, an app that interacts with that database (on a web dyno), and a worker that should also interact with the database. The app asks the worker to do long running tasks in the background, like some database queries. However, I'm having trouble implementing this. I think the problem is that the worker is not authorized to access the database. The specific error I'm seeing is: app[worker.1]: ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This doesn't make sense to me as an error coming from the worker. The settings are getting loaded fine- everything on the web dyno works as expected. The only thing I can figure is that the worker doesn't have access to the configured settings, including the database credentials. How do I resolve this? -
django and angular export xlsx file
Good afternoon! hi guys I've been trying to export an xlsx file from my django backend and get it with my Angular front-end. Like I have a button with ng-click that call my function this button is in my template and it is getting my table id 'diogo-test' and passing to my function <md-dialog-actions> <md-button ng-click="doExcel('diogo-test')" class="md-raised md-accent" aria-label="t"> Imprimir </md-button> </md-dialog-actions> this is my angular function in my controller vm.diogoTeste = function(oportunity){ reportProvider.diogoTest(oportunity.id) .then(function(report){ $mdDialog.show({ controller: ["$scope","reportProvider","oportunity","data",function($scope,reportProvider,oportunity,data){ $scope.data = data; $scope.oportunity = oportunity; $scope.doExcel = function(idDOM){ var textRange; var j=0; var tab = document.getElementById(idDOM); // id of table console.log(tab) for(j = 0 ; j < tab.rows.length ; j++) { var tab_text=tab_text+tab.rows[j].innerHTML+"</tr>"; console.log(tab_text) tab_text=tab_text+"</tr>"; } tab_text=tab_text+"</table>"; tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { txtArea1.document.open("txt/html","replace"); txtArea1.document.write(tab_text); txtArea1.document.close(); txtArea1.focus(); sa=txtArea1.document.execCommand("SaveAs",true,"test.xlsx"); } else{ sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); return(sa) } } $scope.today = function(){ return new Date(); } }], templateUrl: staffUrls.templates['diogoTest'], // Vai chamar a url que esta em staff.url.js parent: angular.element(document.body), … -
Django: Get text value of the hyperlink when hyperlink is clicked
I have a hyperlink like below and I want to get "VALUE I NEEDED" when this hyperlink is clicked <a href='http://www.example.com'>VALUE I NEEDED</a> In Django what I can do is the following <a name = {{ value }} href='http://www.example.com'>{{ value }}</a> Then in views.py i can do the following def index(request): text = request.GET.get("name") *** SOME CODE HERE *** return render(request, 'index.html') But this is not working. Anyone please help me to achieve this. -
How can you use a Multi-Select field in Django Admin without a ManyToManyField in your model?
I'm developing a Django website at work using Django 2.0 (python 3). The website will be used by our customers. Each customer will have a user they login as, and customers belonging to the same company are grouped into "Companies" to make them easier to manage. The project will have a bunch of apps - some customers will have access to some of the apps - other customers will have access to other apps. What I need is a way to control: The default app for a customer When a user logs in, they'll be redirected to the default app's main page The apps the customer is allowed to access The nav bar will only show them links to the apps they have permissions to view Admins, using the Django Admin interface, should be able to allow or deny app use for customers So far, I think I've gotten the default_app bit worked out by having this in my models.py in my login app: from django.apps import apps # Groups users (Customers) class Company(models.Model): app_choices = [] for app in apps.get_app_configs(): if app.verbose_name.endswith("_App"): if app.verbose_name != "Login_App": app_choices.append( (app.verbose_name, app.verbose_name.replace('_', ' ')), ) company_name = ... company_logo = ... default_app … -
How can I use an extended user model in a DetailView?
I've got a Django view in charge of showing a user profile. I'm using the user model provided by django itself but I also would like to extend it with some of my own information, So I made my own model to extend the user model itself: class UserProfile(AbstractBaseUser): is_verified = models.BooleanField(default=True) current_profile = models.ImageField(default=static('img/default_profile.jpg')) ratings = models.ManyToManyField(Video, through='UserProfileVideoRating', related_name='ratings') views = models.ManyToManyField(Video, through='UserProfileVideoView', related_name='views') CommentRating = models.ManyToManyField(Comment, through='UserProfileCommentRating', related_name='CommentRating') subscriptions = models.ManyToManyField(User) And here is my view I'd like to use for that: User = get_user_model() # Create your views here. class profileDetailView(DetailView): template_name = 'profile.html' def get_object(self): username = self.kwargs.get("username") if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) Now my question is, seeing as DetailViews are meant for a single model, How can I achieve this? -
Populate Django fields for each new created field
class CourseCategory(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE) course_category = models.CharField(max_length=50, unique=True) lecture_title = models.CharField(max_length=50) content = models.TextField() link = models.URLField(blank=True) def file_size(self, value): limit = 2 * 1024 * 1024 if value.size > limit: raise ValidationError('File too large. Size should not exceed 2 MiB.') file = models.FileField(blank=True, validators=[file_size]) def __str__(self): return self.category_name class Meta: verbose_name = "Course Category" verbose_name_plural = 'Course Categories' I want that every time I create a new course_category, I will be able to add a lecture_title, content, link and file more times to the same course_category. Should I just make a new model ? Is there a simpler way ? -
Django: Querying database with custom search algorithm
Context: I have a database of houses which users can query by location name (e.g. 'New York, NY' or '100 1st Street, San Francisco'). I'm using Google Maps API to retrieve pinpoints on a map of each of the query results, in addition to a list of each of the objects. Am using Django and Postgres as my framework and DB respectively. Problem: I'm wondering how to filter the House objects by their location, but not all location queries will contain the same information (i.e. some may have a house number, some may have a city or state, and some may not). As shown by the code below, every House object is linked via a OneToOneField to a Location object which contains the necessary fields. This is also complicated by the fact that every Location object is made up of several fields, whereas the query will be a string that might not match a single field as you would use in Django's filter() method. A query such as '100 1st Street, San Francisco' doesn't match any of the individual Location fields since this query is made up of several fields. How might I write an algorithm of sorts to find … -
Namespace for redis-queue queue in django app
I have a django app that uses redis-queue for managing long running tasks in the background. I have it set up and running (if in a stupid configuration), but I'm unclear what the appropriate namespace to store my queue is. I set up the rq worker as recommended in the docs: #rqsetup.py import os import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() I can add the queue to my view: # views.py from rqsetup import conn from rq import Queue from somewhere import bgtask def myview(request): q = Queue(connection=conn) job = q.enqueue(bgtask) return render(request, 'somepage.html') This is obviously dumb, because then the queue and the job are lost after the view is returned. The whole point is to have the queue in some namespace where I can access it again later. However, I can't figure anywhere else to put it. If I try to in rqsetup, I just get import errors, or it imports out of order before its set up properly. I don't really have a good guess of where else it should go. I otherwise … -
Django Role based permissions varies on different project
Hi i am working on Django to build project management app, in that i have 100s of users & 50 plus projects. where single user are involved in multiple projects with different role. now how to give project-role based permission ?? For example. Let say user "Arnold" is working on "[project-A as Manager, project-B as Vendor , project-C as Artist]", *As a manager arnold will get all permissions in project-A, *As a vendor arnold will get read-only permissions in project-B, *As a Artist arnold will get read,write and update permissions in project-C, So now tell me how can i design model relation as mentioned above ? -
can't patch nested values from django rest framework
I am trying to develop a REST API with django-rest-framework for updating a django model. I want to unit test it with the following unit test url = reverse('investments:investments-detail', args=[investment.id]) data = { 'sponsorships': [ {'sponsor': sponsor1.id, 'percentage': 80}, {'sponsor': sponsor2.id, 'percentage': 10}, ] } print("> data", data) response = self.client.patch(url, data=data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(1, Investment.objects.count()) investment = Investment.objects.all()[0] # It fails below : no investments are created self.assertEqual(len(investment.sponsorships()), 2) The model can be summed up with class Investment(models.Model): # ... a few fields def sponsorships(self): return self.investmentsponsorship_set.all().order_by('sponsor__ordering', 'sponsor__name') class InvestmentSponsor(models.Model): name = models.CharField(max_length=200, verbose_name=_('name')) ordering = models.IntegerField(default=0) class Meta: ordering = ('ordering', 'name', ) class InvestmentSponsorship(models.Model): sponsor = models.ForeignKey(InvestmentSponsor) investment = models.ForeignKey(Investment) percentage = models.DecimalField(max_digits=5, decimal_places=2) The api is using rest-framework base classes class InvestmentViewSet(viewsets.ModelViewSet): model = Investment def get_serializer_class(self): serializers_class_map = { 'default': InvestmentSerializer, 'partial_update': PartialUpdateInvestmentSerializer, } return serializers_class_map.get(self.action, serializers_class_map['default']) def perform_update(self, serializer): serializer.save() Then I expect to get and handle the "sponsorhips" data in the serializers class InvestmentSponsorshipSerializer(serializers.ModelSerializer): class Meta: model = models.InvestmentSponsorship fields = ('sponsor', 'percentage', ) class PartialUpdateInvestmentSerializer(serializers.ModelSerializer): sponsorships = InvestmentSponsorshipSerializer(many=True) class Meta: model = models.Investment fields = ( 'id', '... others', 'sponsorships', ) def validate_sponsorships(self, value): print("validate_sponsorships", value) return value def update(self, instance, validated_data): … -
Angular 2/5 Smart Table with Django REST API
I am looking for an example of a smart table that accesses an API provided by Django REST API. Since my database is very large, it is very important to have server-side pagination and filtering. JSON response of my API { "count": 11512, "next": "http://127.0.0.1:8000/api/icd/?page=2", "previous": null, "results": [ { ... Can you help me with a little jump-start, please? -
Working with reportlab to create tables
I am trying to loop the user data in django to create a table with the help of reportlab. But I am running into an attributeError that 'tuple' object has no attribute 'username'. def admin_tools_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="users.pdf" ' buffer=BytesIO() p=canvas.Canvas(buffer,pagesize=A4) width, height = A4 styles = getSampleStyleSheet() styleN = styles["BodyText"] styleN.alignment = TA_LEFT styleBH = styles["Normal"] styleBH.alignment = TA_CENTER user_data=User.objects.all().values_list('username','email') username=Paragraph("'<b>Username</b>'",styleBH) email=Paragraph("'<b>Email Id</b>'",styleBH) data=[[username,email]] for i in user_data: username=str(i.username).encode('utf-8') email=str(i.email).encode('utf-8') user=Paragraph(username,styleN) mail=Paragraph(email,styleN) data+=[user,mail] table=Table(data,colWidths=[4*cm,4*cm,4*cm,4*cm]) p.showpage() p.save() pdf=buffer.getvalue() return response The import files are: from io import BytesIO from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Table, TableStyle,Paragraph from reportlab.lib.pagesizes import A4, cm from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER Thanks a lot! -
How to define a model of episodes w a series as foreign key in django effectively
Hi and thanks for your time! I have a model of series and a model of episodes (different apps) with a series as a ForeignKey for the episodes. I have a few issues: Isn't a bit of a mess to have all episodes in the same model whithout taking into account the series they belong to (ofc there's the foreignkey, but they are all shuffled together)? If it is, how could I solve it? With my current model, I don't know how to create a field that automatically adds the number of episode taking into account the episodes that already exist of a CONCRETE SERIES. I have a DetailView of each series in my app "series" (url = series/<slug(of the series)>/, and I want to define a DetailView for each episode. Should I define the url in the episodes app or in the series app? Once I have the url, how do I get the the episode object in the DetailView most effectively? I first thought of getting all episodes in the get_qs and then filtering in the context_data, but I don't know how to get the series out of the URL to filter, and this method seems quite long … -
Patch django reusable app settings constant
I build a django library. This library has it's own settings file. In short: from django.conf import settings RANDOM_SOURCE = 'random' MY_SOURCE = 'source1' DEFAULT_SOURCE = RANDOM_SOURCE TASK_SOURCE = getattr(settings, 'MY_TASK_SOURCE', DEFAULT_SOURCE) I don't know if it's right design, moreover I have a problem with testing - patching the TASK_SOURCE. Whether I try to override settings or patch it just doesn't work for modules that import TASK_SOURCE. inb4: I have separate test settings file, it's irrelevant for the problem @patch('mylib.settings.TASK_SOURCE', MY_SOURCE) doesn't work @override_settings(TASK_SOURCE=MY_SOURCE) doesn't work as well Is it bad design or I miss something during testing? -
How do I lookup the reverse of a foreign key relationship in 1 Django query?
I have the following classess: class EpisodeAnalytic(models.Model): class Meta: unique_together = ("episode", "target_date") episode = models.ForeignKey(Episode, null=False, blank=False) target_date = models.DateField(null=False, blank=False) class Episode(models.Model): pass And I'm wondering how I can do the following in a single query in Django:?? episode_analytics_in_target_period = EpisodeAnalytic.objects.filter(target_date__range=[start_date, end_date) episode_ids = list(map(lambda episode_analytic: episode_analytic.episode.id, episode_analytics_in_target_period)) episodes_in_target_period = Episode.objects.filter(id__in=episode_ids) -
Template not found by heroku
I just deployed my Django site on Heroku but I'm getting TemplateNotFoundError: Traceback (most recent call last): 2018-01-17T16:17:41.010548+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner 2018-01-17T16:17:41.010548+00:00 app[web.1]: response = get_response(request) 2018-01-17T16:17:41.010549+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response 2018-01-17T16:17:41.010550+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2018-01-17T16:17:41.010551+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response 2018-01-17T16:17:41.010551+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2018-01-17T16:17:41.010552+00:00 app[web.1]: File "/app/workoutcal/views.py", line 51, in redirect_to_calendar 2018-01-17T16:17:41.010553+00:00 app[web.1]: return calendar(request, year = today.year, month = today.month) 2018-01-17T16:17:41.010554+00:00 app[web.1]: File "/app/workoutcal/views.py", line 56, in calendar 2018-01-17T16:17:41.010554+00:00 app[web.1]: return prompt_login(request) 2018-01-17T16:17:41.010555+00:00 app[web.1]: File "/app/workoutcal/views.py", line 286, in prompt_login 2018-01-17T16:17:41.010556+00:00 app[web.1]: return render(request, 'workoutcal/prompt_login.html') 2018-01-17T16:17:41.010556+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render 2018-01-17T16:17:41.010557+00:00 app[web.1]: content = loader.render_to_string(template_name, context, request, using=using) 2018-01-17T16:17:41.010558+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string 2018-01-17T16:17:41.010559+00:00 app[web.1]: return template.render(context, request) 2018-01-17T16:17:41.010559+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py", line 63, in render 2018-01-17T16:17:41.010560+00:00 app[web.1]: reraise(exc, self.backend) 2018-01-17T16:17:41.010561+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py", line 84, in reraise 2018-01-17T16:17:41.010561+00:00 app[web.1]: raise new from exc 2018-01-17T16:17:41.010565+00:00 app[web.1]: django.template.exceptions.TemplateDoesNotExist: workout/base.html I already did what is recommended in this answer: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, "templates"), ) but it didn't help. What is the problem here?