Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Structure: Separate Apps for Users app and Registration?
Quick question regarding separation of concerns when creating Django apps. I have had people recommend that user_registration and users be kept as separate app. For example, if I have a project with, say, an app called "user_info" which simply builds on Django's built in User model with a OneToOne relationship, do you think it would be better to include user registration methods/views/etc. in the "user_info" app or create a separate app for "user_registration." I have always separated them as separate apps but would prefer not to in the future unless there are good arguments to do so. -
Best way to filter a django QuerySet based on value without name (rank)
So I've build a web app with django, using postgres for the database. Using django.contrib.postgres.search.SearchRank, I search for all recipes in my database with the word 'chocolate', and it gives me back a nice sorted QuerySet. from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank # example code: # searching recipe_name: vector = SearchVector('recipe_name') # searching for the term 'chocolate': query = SearchQuery('chocolate') # Recipe = recipes class in Models.py; contains 'recipe_name' column. search_recipes = Recipe.objects.annotate( rank=SearchRank(vector, query) ).order_by('-rank') # this gives me a QuerySet of recipes, which have a rank attribute: print(search_recipes[0].rank) # 0.0607927 I don't want recipes whose match scores are 0 to show up, so I want to filter by score ('rank'). Usually I'd do this by e.g.: search_recipes.filter(rank_gt=0) But 'rank' is an added attribute from postgres's special SearchRank function, it's not a column name or anything, so this creates an error (`Cannot resolve keyword 'rank_gt' into field). I can get what I want with the following: x = [r for r in search_recipes if r.rank > 0] But I'm just wondering if there's a better, less hacky way to do this (seeing as the list comprehension gives me a list recipes, and not a QuerySet --> so I lose … -
How to pass a extra parameter using perform_create of django rest framwork?
I am using django rest frameworks generic views. I am trying to insert request user name in the author field of post. Serializers class PostSerializer(serializers.ModelSerializer): spoter = serializers.PrimaryKeyRelatedField( queryset= User.objects.all(), ) class Meta: model = PostModel fields = ('author','text') View class UserRequestMixin(object): def perform_update(self, serializer): serializer.save(author = self.request.user.id) def perform_create(self, serializer): serializer.save(author = self.request.user.id) class PostViewSet(UserRequestMixin,DefaultsMixin,viewsets.ModelViewSet): permission_classes = (IsOwnerOrReadOnly,) queryset = PostModel.objects.all() serializer_class = PostSerializer Error status -> 400 { "author": [ "This field is required." ] } -
ImportError: No module named AppHome
I have created a Django project by name PrjDjangoProject and an app named AppHome. I have ensured all entries in : 1. settings.py->INSTALLED-APPS 2. urls.py entries in both. 3.I have also checked PYTHONPATH variable to hold the physical path of both However I get an error - ImportError: No module named 'AppHome' -
Is there a viewset in rails like there is one in Django
I have been working with Django, and I use to love the ability of being able to see my API and data by accessing the URL endpoint http://www.django-rest-framework.org/api-guide/viewsets/ I am starting out now with Rails and would like to use it as an API backend. And was wondering, what are similar ways of outputting the API or being able to access the endpoint similarly to Django -
How can I save my results from a task
I have a task that scrapes the data in the background that looks like this. def the_star(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } # scraping from worldstar url_to = 'http://www.worldstarhiphop.com' html = requests.get(url_to, headers=headers) soup = BeautifulSoup(html.text, 'html5lib') titles = soup.find_all('section', 'box') name = 'World Star' def make_soup(url): the_comments_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(the_comments_page.text, 'html5lib') comment = soupdata.find('div') para = comment.find_all('p') kids = [child.text for child in para] blu = str(kids).strip('[]') return blu cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php'] world_entries = [{'href': url_to + box.a.get('href'), 'src': box.img.get('src'), 'text': box.strong.a.text, 'comments': make_soup(url_to + box.a.get('href')), 'name': name, 'url': url_to + box.a.get('href'), 'embed': None, 'author': None, 'video': False } for box in cleaned_titles][:10] # The count return world_entries I run it in a view like this def … -
Which web framework to use? [on hold]
disclaimer: I have no previous web development experience. Okay basically I have created a java application that runs different scripts(python,ruby, perl) using Javas process builder; these scripts parse different files stored on the machine. I would like to create a dynamic web application to do this to allow different users to run these scripts using a web interface. I would like the results of the scripts ran only to be view-able by the user that has ran it(these will be wrote to disk when the scripts are ran). What web framework do you think would be easiest/best to do this? Thanks in advance! -
Django: How can I get the foreign key's class from a classmethod in the referred-to class?
I have the following two Django Classes MyClassA and MyClassB in two separate files. MyClassB has a foreign key reference to an instance of MyClassA. MyClassA cannot import the class MyClassB. my_class_a/models.py: from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=50, null=False) @classmethod def my_method_a(cls): # What do I put here to call MyClassB.my_method_b()?? my_class_b/models.py: from my_class_a.models import MyClassA from django.db import models class MyClassB(models.Model): name = models.CharField(max_length=50, null=False) my_class_a = models.ForeignKey(MyClassA, related_name="MyClassB_my_class_a") @staticmethod def my_method_b(): return "Hello" From within MyClassA's class method my_method_a, I would like to call MyClassB's static method my_method_b. How can I do it? If my_method_a was an instance method, I would simply do self.MyClassB_my_class_a.model.my_method_b(). But since I don't have an instance of MyClassA, I don't know how to do it. I would like to take advantage of the related_name field that allows for reverse lookups of instances. -
How set permissions for create action in rest_framework
I want to set perissions for the create action (post). And I dont know hot to do it. This is my code: In permissions.py class IsAdmin(permissions.BasePermission): def has_object_permission(self, request, view, category): if request.user.role == "admin": return request.user.role == "admin" return False In view class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer def get_permissions(self): if self.request.method in permissions.SAFE_METHODS: return (permissions.DjangoModelPermissions(),) return (permissions.IsAuthenticated(), IsAdmin(),) -
Can't convert 'DeferredAttribute' object to str implicitly
When Iam trying to get the degree of a student and do the return value with that code: def __str__(self): return self.student_subject + " " + Student.last_name I got the above error message. Here is the whole Django code: from django.db import models # Create your models here. class Student(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) age = models.IntegerField(default=0) birth_date = models.DateTimeField() def __str__(self): return self.first_name + " " + self.last_name class Degree(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) student_subject = models.CharField(max_length=150) student_degree = models.IntegerField(default=0) def __str__(self): return self.student_subject + " " + Student.last_name the error is happening because I trying to inherite the return from the above class Student And here is the error message: TypeError at /admin/sellingportal/degree/ Can't convert 'DeferredAttribute' object to str implicitly Request Method: GET Request URL: http://127.0.0.1:8000/admin/sellingportal/degree/ Django Version: 1.10.1 Exception Type: TypeError Exception Value: Can't convert 'DeferredAttribute' object to str implicitly Exception Location: C:\Users\Muham\PycharmProjects\managementsite\managementstudio\sellingportal\models.py in __str__, line 22 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 Python Path: ['C:\\Users\\Muham\\PycharmProjects\\managementsite\\managementstudio', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Fri, 16 Sep 2016 01:04:08 +0200 -
Django Model conditional relationship
Newbie question: Django + Postgres + PostGIS I am trying to setup a Projects model in Django that needs to be conditionally related to a geometry model depending on its geometry type. the geometry types are : Points, Lines or Polygons. The question is how do I define this relationship in the Project Model so that I do not have to save the different geometry types in the same table ( Hence the 3 different geometry models) =======================Here are my models ============================ PRJ_GEOM = ( (1, "point"), (2, "line"), (3, "polygon") ) class Project(models.Model): name = models.CharField(max_length=20) project_geom_type = models.IntegerField(choices=PRJ_GEOM) project_geometry = models.OneToOneField( ????) # I am stuck here - how do I express this conditional relationship which depends on project_geom_type # Geometry Model class Project_Point_Geom(models.Model): project = models.OneToOne(Project, on_delete=models.CASCADE, related_name='project_point') point = models.PointField() class Project_Line_Geom(models.Model): project = models.OneToOne(Project, on_delete=models.CASCADE, related_name='project_line') line = models.LineStringField() class Project_Polygon_Geom(models.Model): project = models.OneToOne(Project, on_delete=models.CASCADE, related_name='project_polygon') polygon = models.PolygonField() -
Django: How to do reverse foreign key lookup of another class without an instance of this class?
I have the following two Django Classes MyClassA and MyClassB. MyClassB has a foreign key reference to an instance of MyClassA. from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=50, null=False) @classmethod def my_method_a(cls): # What do I put here to call MyClassB.my_method_b()?? class MyClassB(models.Model): name = models.CharField(max_length=50, null=False) my_class_a = models.ForeignKey(MyClassA, related_name="MyClassB_my_class_a") @staticmethod def my_method_b(): return "Hello" From within MyClassA's class method my_method_a, I would like to call MyClassB's static method my_method_b. How can I do it? If my_method_a was an instance method, I would simply do self.MyClassB_my_class_a.model.my_method_b(). But since I don't have an instance of MyClassA, I don't know how to do it. Can I use cls instead of self? -
doing POST on Django Rest Framework with viewsets return "405 - METHOD POST NOT ALLOED"
I'm trying to create a HiScore Module for my IOS Apps. I'm stuck on the POST (probably will have the same issue with the PUT, but not sure) part, I'm getting 405 in Postman. LIST AND DETAILS are working great, so there is no problem with the models, serialisers or views, just something I'm guessing with adding permissions somewhere views class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class GameViewSet(viewsets.ModelViewSet): queryset = HiScore.objects.all() serializer_class = GameSerializer class GameTypeViewSet(viewsets.ModelViewSet): queryset = HiScore.objects.all() serializer_class = GameTypeSerializer class GameLevelViewSet(viewsets.ModelViewSet): queryset = HiScore.objects.all() serializer_class = GameLevelSerializer class HiScoreViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny,] queryset = HiScore.objects.all() serializer_class = HiScoreSerializer serialisers.py class HiScoreSerializer(ModelSerializer): image = SerializerMethodField() class Meta: model = HiScore fields = ("user", "game", "gameType", "gameLevel", "points", "image") def get_image(self, obj): try: profile = UserProfile.objects.get(user=obj.user) return profile.image.url except: return None urls.py router = DefaultRouter() router.register(prefix='hiscores', viewset=HiScoreViewSet) urlpatterns = router.urls Again, It is ModelViewSet... not generic and not anything else, and i'v read many questions about view sets that the answers where to genericViews and things like that... please help me with permissions for ModelViewSet. It is killing me, never got stuck on one thing for so long and couldn't find any documentation that could actually help. … -
Django: conflicting models in application
I integrated a third party app into my Django project, and only when I import it will I get this error message. RuntimeError: Conflicting 'task' models in application 'django_q': <class 'django_q.models.Task'> and <class 'models.Task'>. I'm puzzled because my app runs well withouth it so I wonder how it could be an error on my side. I'm only using the app in its most simple use case. My general question is then: how can I investigate ? So the app is django-q, a task queue (github). I installed it and called it in its most simple usage, following the good documentation. CACHE = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', } } Q_CLUSTER = { 'name': 'DjangORM_queue', 'workers': 4, 'timeout': 3600, 'retry': 4000, # 'queue_limit': 50, # 'bulk': 10, 'orm': 'default' } api.py: # api.py # not putting all imports or __init__.py def myhook(task): print task.result import ipdb; ipdb.set_trace() def mymethod(request, pk, **kwargs): from django_q.tasks import async, result async('models.MyModel.method', pk, hook='myhook', sync=True) Now manage.py runserver is ok, until I call my api and it reaches tasks.async. Full stacktrace: Traceback (most recent call last): File "/home/[...]/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/.../my-project/searchapp/models/api.py", line 965, in mymethod tasks.async('models.MyModel.mymethod', … -
Django Mixin to add context variables
I want to create a GenericFormMixin for Django that I can mix into CreateView and UpdateView that will let me use a generic form template by dynamically setting things like the page title, form title, submit button text, etc. I have the following in mixins.py: class GenericFormMixin(object): page_title = '' form_title = '' submit_button_text = '' Instead of having to create a modelname_create.html and modelname_update.html for every CreateView or UpdateView I have, I want to be able to use generic_form.html which will use the mixin's variables in its context to dynamically create an appropriately populated template: {% extends "base.html" %} {% block title %}{{ page_title }}{% endblock title %} {% block content %} <div class="panel panel-primary"> <div class="panel-heading">{{ form_title }}</div> <div class="panel-body"> <form method="post" action="."> {{ form }} {% csrf_token %} <button type="submit" class="btn btn-primary">{{ submit_button_text }}</button> </form> </div> </div> {% endblock content %} My question is: now that I've created the mixin, how do I get the variables into the template context of CreateView and UpdateView? -
Insight on how app servers such as uWSGI work with Django
Could someone please explain how app servers like uWSGI and Gunicorn work with Django in an workflow and architecture view? I am especially a bit curious on how app server does multithreaded requests on a Django process. -
How do I check if a function is being called by a method?
How do I check if a function b() is being called by a method? class hello(): delete(): b() I want to use mock in a unit test. -
Django Form Customisation
I am using django forms and everything is working nicely, with help from the experts on here. Now I want to apply some formatting to the form. As it stands I have the following fields: team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None) They currently display as: Team1: "Dropdown box with all the current football teams" Team2: "Dropdown box with all the current football teams" Is it easy to have the two fields side by side and fix the length of the field? Many thanks in advance, Alan. -
Django 2 Ajax requests, 2 csrf tokens not working - 403
I have 2 $.ajax() functions in one html rendered by Django. The first one works correctly, the second one answers with a 403 CSRF Failed: CSRF token missing or incorrect. This is the relevant js code: $(document).ready(function(){ window.CSRF_TOKEN = "{{ csrf_token }}"; .... $.ajax({ method: "POST", url: "{% url 'alpha:create_cart_item' %}", data: {'item': stockitem_id, 'quantity': '1', 'csrfmiddlewaretoken': window.CSRF_TOKEN}, success: function(resp){...} .... $.ajax({ method: "PUT", url: "{% url 'alpha:update_cart_item' 0 %}".replace("0", cartitem_id), data: {'pk': cartitem_id, 'csrfmiddlewaretoken': window.CSRF_TOKEN}, success: function(resp){ panel_div.hide(); }, error: function(resp){ } }); The second Ajax request is not working. I set the csrfmiddlewaretoken in the exact same way. Why am I getting the 403?. Obviously I'm missing something, please help. -
Django can't convert 'Recipe_instruction' object to str implicitly
I am developing an application in django. Here is my models.py and views.py code: #models.py class Recipe_instruction(models.Model): content = models.TextField(max_length=500) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) order = models.IntegerField(max_length=500) class Meta: app_label='recipe_base' def __str__(self): return self.content views.py #create recipes_dict ... recipe_instructions = Recipe_instruction.objects.filter(recipe = recipe) recipe_instructions_string = "" for recipe_instruction in recipe_instructions: recipe_instructions_string = recipe_instructions_string + recipe_instruction.content ... My goal is to get all the recipe instructions and pin them together into a single string recipe_instructions_string But when I run my views.py, it gives me the following error: recipe_instructions_string = recipe_instructions_string + recipe_instruction.content TypeError: Can't convert 'Recipe_instruction' object to str implicitly Can anyone tell me whats going on? As recipe_instruction.content is a text field so I shouldn't need to convert it again into a string as its already a string. -
Are there any up to date Django packages that work well with Neo4j 3.0.4?
I'm trying to build a second degree connections search capability that's backed by a graph database. The feature is already built into the Django back end, but is currently slow as it's done with Postgres. I have looked into Neo4j, but can't seem to find any good Python libraries or Django packages that are up-to-date or well maintained. I want to have the ability to run Cypher queries, and ideally ORM capability on the Django end. I've looked into: neo4django neomodel neo4j-driver (for python) They all seem to be either outdated or not meeting my needs. Any advice on how I can build this functionality, or good libraries to try working with? -
module 'django.db.models' has no attribute 'Owner'
this the models.py. the car class was left out because it was not needed to save reading but its there class Owner(models.Model): carID = models.ForeignKey(Car) Owner_Entry_Number = models.IntegerField() Owner_Date = models.DateField('Proprietor start date', null=True, blank=True) Owner_Last_Name = models.CharField(max_length=50, null=True, blank=True) Owner_First_Name = models.CharField(max_length=50, null=True, blank=True) Owner_Middle_Initial = models.CharField(max_length=6, null=True, blank=True) Owner_Address = models.CharField(max_length=80, null=True, blank=True) my view from .models import Car, Owner from django.db import models def switchingowners(request): ownersofcar = Owner.objects.filter(CarID = request.user['CarID']) for owner in ownersofcar : addingOwner = models.Owner(CarID=form['CarID'], ) basically it fails to work now i know it kinda confusing but basically all the owners of a car i want to transfer them to a new car or cars but i get module 'django.db.models' has no attribute 'Owner' because of this line addingOwner = models.Owner(CarID=form['CarID'], but i have the imports and dont know why using django 1.8 -
From django rest framework 3 pre_save, pre_delete is not available than how to manipulate and insert requested user name in any field?
I am using django rest framework. I want to insert request user name in the author field of posts. But I cannot manipulate the data before saving as the pre_save method is depreciated from drf 3 drf generic view. class SpoterMixin(object): def create(self, request, *args, **kwargs): data = request.data data['author'] = request.user.id serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() data = request.data data['author'] = request.user.id # here I am manipulating and inserting the requested user serializer = self.get_serializer(instance,data=data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) class SpotViewSet(UserRequestMixin,viewsets.ModelViewSet): queryset = PostModel.objects.all() serializer_class = SpotSerializer Is there a more efficient way of doing this as if I trying to implement all the views likes this that would increase a lot of boilerplate code. So is there any alternative for the pre_save method. -
django getattr and issues with updating
In django I built a simple method that gets called and is passed a uniqueid, field specifier, and a value. It then does a simple addition to update the value in the field. I've coded it a number of ways and have come to the conclusion that getattr does not work when trying to save, update, or refresh the database. One variation of my code: def updatetable(uid, fieldtitle, value): workingobj = bog_db.objects.get(name=uid) objectcall = getattr(workingobj,fieldtitle) objectcall = F(fieldtitle) + value workingobj.refresh_from_db() return I tried hand jamming some code to see if I could figure out the problem. btw: value = 37 In [36]: call = getattr(workingobj,fieldname) In [37]: call Out[37]: 37 In [38]: call += value In [39]: call Out[39]: 74 In [40]: workingobj.save() #refreshed database, checked table, values in db not updated In [41]: workingobj.total_number_posts += value In [42]: workingobj.total_number_posts Out[42]: 74 In [43]: workingobj.save() #refreshed database, values in db were updated It would appear to me that Django does not want you using getattr for doing db calls and updates and instead wants you to EXPLICITLY call object.field. Is this true? Does getattr make a copy of the attributes? I want to better understand why it is behaving … -
Getting Request User on Django Rest Oauth2
I'm using the Django Rest Framework with the Django Oauth Toolkit. I'm connecting fine. I ha no issues with the token, access and permissions. But I'd like to have a queryset with a filter of the current user something like: def get_queryset(self): return Account.objects.filter(user=self.request.user) When I do this, the user I get is a None Type. Even though I was able to pass correctly the Token via Authorization Bearer.