Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django testing: TypeError: 'int' object is not callable
I have written some test case in django, facing a type-error, def setUp(self): self.mobile_number = 9876543210 def test_obj_count(self): result = self.get_obj(self.mobile_number) self.assertEqual(result, 3) def get_obj(self, mobile_number): return Tolls.objects.filter().count()(toll__request__driver__profile__mobile_number=mobile_number) Here this line is throwing error result = self.get_obj(self.mobile_number) TypeError: 'int' object is not callable However it is working fine if I am using this function like as follow- def get_obj(self, mobile_number): toll = Tolls.objects.filter().count()(toll__request__driver__profile__mobile_number=mobile_number) return toll.count() -
How to set up a APIView in Django-Restframework?
I have a problem with the Django-Restframe work. I order to fill the charts of my website with stock prices I chose to set up a django rest framework based api. I am new to Django and watched a tutorial on youtube which i now of course do not find again. On local host the entire application works but once I want to publish the application on digital ocean I get errors like: AttributeError at / 'module' object has no attribute ‚JSONField' /usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py in ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField I think that I ignored major steps when setting up the rest-framework. Is here someone who knows how to set this up appropriately. I have spent quite some time into the entire application and API and would appreciate if someone could point me at some documentation where I could find an example of an similar case. Below I have attached all the code used for this case. I would appreciate very much if you could help me. The application is called TechnicalAnalysis btw. Application Files I have not jet made any changes to the Admin.py, Apps.py or Models.py files. I am especially concerned about not registering any models. But only found information about … -
Using get_queryset() in ViewSets, can't access the Detail Views. Error: Cannot use None as a query value
When I do a DELETE request to 127.0.0.1:8000/tasks/10/, I get the error that Cannot use None as a query value. views.py class TaskViewSet(viewsets.ModelViewSet): def get_queryset(self): p1 = self.request.query_params.get('parameter') queryset = Task.objects.nearby(p1) return queryset serializer_class = TaskSerializer urls.py task_list = views.TaskViewSet.as_view({ 'get': 'list', 'post': 'create' }) task_detail = views.TaskViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) # The API URLs are now determined automatically by the router. urlpatterns = [ url(r'^', include(router.urls)), url(r'^tasks/$', task_list, name='task-list'), url(r'^tasks/(?P<pk>[0-9]+)/$', task_detail, name='task-detail'), ] Everything works fine for list e.g. all requests to 127.0.0.1:8000/tasks/. However, none of the request work for the detail views. I'm assuming it's something to do with the get_queryset(). -
Uploading image to django ImageField using jdbc
I am trying to upload image file to a django Image field. All the fields get populated except image. My model is as follows: class ImageModel(models.Model): image_title = models.CharField(max_length=50, null=False, blank=False) uploader = models.CharField(max_length=50, null=False, blank=False) image = models.ImageField(upload_to='imgs/', null=True, blank=True) And here's the Java code snippet for inserting data: String query = "INSERT INTO testcaseconfiguration_Screenshots (image_title , uploader , image) VALUES(?, ?, ?)"; File file = new File("Image location goes here"); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte [] buffer = new byte[1024]; for(int readNum; (readNum = fis.read(buffer)) != -1; ){ bos.write(buffer, 0, readNum); System.out.println("Read " + readNum + " bytes..."); } byte [] image = bos.toByteArray(); PreparedStatement ps = connection.prepareStatement(query); ps.setString(1, "Some Title"); ps.setString(2, "Uploader Name goes here"); ps.setBytes(3, image); ps.executeUpdate(); }catch (Exception e) { e.printStackTrace(); } I know ImageField in django won't behave as I am expecting here but don't know how to proceed with the issue. Please someone help me. -
How do you add a custom django inline data table?
I have a model called "Stock", I want to create a admin view where when you go into the detail you can see a table of all the relevant stock amounts underneath as a InlineAdmin. I could do this with a custom template but I would want it to automatically page increment. Is there something that already does this or will I have to create custom views with a custom UI outside the admin to make this happen? -
Dynamically create workflow in viewflow using xml
Is it possible to create flow dynamically by defining the flow in xml and then parsing it. -
Django- Migrating an app from production to my local uat session - throwing appregistrynotready - Apps aren't loaded
I have a prod version of a project (made by someone else) that I am trying to deploy on my laptop. I have installed python through Anaconda 3. I have the necessary paths registered. And the code is working in the production environment without any issues. I have PostGreSQL installed and have it configured it like the prod environment. The command I am running is C:\sites\myanalysis>python manage.py makemigrations The result ends with the following exception: File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\db\models\base.py", line 90, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\apps\registry.py", line 244, in get_containing_app_con fig self.check_apps_ready() File "C:\Users\rambo\AppData\Local\Continuum\anaconda3\lib\site-packages\dj ango-2.1-py3.6.egg\django\apps\registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Googling the possible issue - I have the following installed apps within the settings.py file # Application definition INSTALLED_APPS = [ 'project.apps.ProjectConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] The settings.py file already has the following imported import psycopg2 import os Anyone can please help as to what else I can try? -
django override auth login method
I want to override login function in __init__.py of django.contrib.auth I did steps: urls.py url(r'^login/$', 'my_login'), views.py from django.contrib import auth def login(request, user, backend=None): # do some stuff settings.py INSTALLED_APPS = [ #'django.contrib.auth', 'my_auth_app' ] But i feel, its wrong way. Actually i want to get default conrtib.auth with overided login method -
building apps with kivy to intract with Django Restframework
so I have a project that developed with django ,Django Restframework. I had planned for UI handling. Reactjs and Reatnative for UI .but I searched and found Kivy project that comes with Cross Platforms for making Apps and games.my project doesn't involve any game stuff just regular web site. is it good using kivy for handling UI for Android and IOs? I also checked kivy supports fully Url request for interact with Rest APIs. https://kivy.org/docs/api-kivy.network.urlrequest.html -
Django inlineformset will not submit
My application has two models, Recipe and RecipeIngredient, related by foreign key. Each Recipe may have many different RecipeIngredients (and different number of associated ingredients for each recipe). So using a dynamic formset to assign ingredients to a recipe seems to be the best approach. I have a simple form that has a user enter a quantity and select a unit and ingredient from a dropdown. As a standalone form it works fine. Unfortunately, I cannot get any formset incorporating it to submit. I have searched many of the different formset Q&As here on StackOverflow but cannot see where the problem is. When I click 'submit', the form blinks and refreshes in place, with the entered values still in the form. No objects are created. No errors report to the console nor to the browser. The related code: The models: class RecipeBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) creation_date = models.DateField("Record creation date",auto_now_add=True) creation_user = models.CharField("Record creation user",max_length=150) lastupdated_date = models.DateField(auto_now=True) lastupdated_user = models.CharField(max_length=150) category = models.ForeignKey(RecipeCategory,on_delete=models.CASCADE,related_name='recipes') subcategory = models.ForeignKey(RecipeSubcategory,on_delete=models.CASCADE,related_name='recipes') def __str__(self): return str(self.name) class RecipeIngredient(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) quantity = models.DecimalField(max_digits=8,decimal_places=3,null=False) referenced_unit = models.ForeignKey(UnitDetail,on_delete=models.CASCADE) referenced_ingredient = models.ForeignKey(Ingredient,on_delete=models.CASCADE) parent_recipe = models.ForeignKey(RecipeBase,on_delete=models.CASCADE,related_name='ingredients') def __str__(self): return str(self.id)[:8] The call to enter ingredients: … -
best database design?
A table of user profile with 40 columns or 4 tables with 10 columns of user profile - divided into education,job,family. I require to filter to user profile on different fields given. -
Issues with image.path being reported wrong causing failing of a Celery task
I have the following model: class Image(models.Model): image = models.ImageField(upload_to=file_upload_to) I have a dynamic file_upload function: def file_upload_to(instance, filename): base = 'placeholder' .... base = '_'.join([str(instance.item.pk), instance.item.slug]) return os.path.join('accounts', base, 'item', base_2, 'images', filename) and in a modelform: class ImageModelForm(ModelForm) def save(self, commit=True): image_obj = super().save(commit=commit) # print(image_obj.image.path, image_obj.image.name,image_obj.product_id ) ..... product_image__task.delay(image_obj.image.path, image_obj.image.name, image_obj.product_id) return image_obj The file is saved properly in a path like: media/account/12_blue/images/image_name.jpeg The problem is that image_obj.image.path is not reporting the correct path, but this path: media/image_name.jpeg I use the image path, further passing it as an argument to a task, but because I received the wrong path, it will fail. How can I fix this, and receive the correct path ? (I thought of using a delay after save, but this not that good, because we don't know prior the time needed)