Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dango rest framework ListAPIView returning no value
I am using django reset framework to create an api. here is my Serializer.py class ArticleSerializer(serializers.Serializer): class Meta: model = Article fields = ("title", "content") views.py class ArticleListView(ListAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleDetailView(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer urls.py from .views import ArticleListView, ArticleDetailView urlpatterns = [ path('', ArticleListView.as_view() ), path('<pk>', ArticleDetailView.as_view() ), ] when i pull up http://127.0.0.1:8000/api/ all what i am getting is this ``` [ # i have 3 objects of the Article class {}, {}, {} ]``` models.py class Article(models.Model): title = models.CharField(max_length=120) content = models.TextField() def __str__(self): return self.title i just done understand why i cant see the values of the title and content of my class ? Any help would be greatly appreciated -
Reverse for 'add_items' with arguments '('1 Topping',)' not found. 1 pattern(s) tried: ['add_items\\/(?P<pizza_name>[-a-zA-Z0-9_]+)\\/$']
how to resolve this error and I also want to send multilple variables with this url Reverse for 'add_items' with arguments '('1 Topping',)' not found. 1 pattern(s) tried: ['add_items\\/(?P<pizza_name>[-a-zA-Z0-9_]+)\\/$'] index.html <table> {% for pizza in r_pizzas %} <tr><a href="{% url 'add_items' pizza.pizza_type %}">{{pizza.pizza_type}} , {{pizza.small}} , {{pizza.large}}</a> </tr><br><hr> {% endfor %} </table> urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login" , views.login_view , name="login"), path("logout" , views.logout_view , name="logout"), path("register" , views.register , name="register"), path("registration_successful" , views.registered , name="registered"), path("add_items/<slug:pizza_name>/" , views.add_items , name="add_items") ] views.py def add_items(request , pizza_name ): item = pizza_name related model class Sicilian_Pizza(models.Model): pizza_type = models.CharField(max_length=64 , default=None) small = models.DecimalField(max_digits=5, decimal_places=2 , default=None) large = models.DecimalField(max_digits=5, decimal_places=2 , default=None) -
Mixing Manual and Model form in Django
I have a table in which I have 5 columns and out of those 5 columns, one column is Comment(which is currently NULL in db). I am able to fetch the data from database on a page and it shows comment as null because I am only fetching the data. I need to do 2 things here - I need to load the data against 4 columns and show comment column as text box. Once the user enters something in comment column, it should be saved with that record in the database. 3) And next time, the user is loading the page, it should show the comment for that record. I am able to fetch the data but could not mix the manual form and model form in DJango. Please help. -
Convert api data to HTML in python
The want the data I got in json format to be able to view and code in HTML. This is the python code I have written. The data is received from MongoDB def get_audit_run(request, theA=0, theR=0, result=''): if 'url' in request.GET: page = request.GET['url'] else: page = '' theinput_dict = observepoint.get_audit_run(theA, theR, result, page) # Transform python object back into json theoutput_json = json.dumps(theinput_dict, indent=4) #return render(request, 'audit.html', {"data" : output_json} ) return HttpResponse(theoutput_json, content_type='application/json') My result: { "a": 72040, "b": 60, "c": false, "d": 100, "sm": false, "id": 885057, "completed": "2018-08-27T15:34:20.000-04:00", "tU": 99, "userId": 4267, "started": "2018-08-27T15:12:46.000-04:00", "limit": 100, "SF": [ "abc", "xyz", "pqr" ] } I want to render the results above to HTML table. Please help! -
Django url manipulation - detail page with pk / id should not show based on attributes of that object - Best Practice
i have the following Use Case: django page that displays a list of links. Each link points to the detail page of the respective object. The link contains the pk/id of that object (something like ../5/detailObject/) The list is generated on the backend and has some filtering baked into it. Only generate a link if that object has state x etc. . Clicking on the links works and everything is all fine, but the user could "manipulate" the url and pass a valid link (object with that pk exists in the database) but the state might be wrong. (a wrong pk/id is being handled with the get or 404 shortcut) My Question is if there is a best practice / django solution for this kind of scenario. I want to avoid code duplication for the filtering logic. Do you place that kind of filtering into the object's model class? (Atm i am using function based views) Short background - experienced with Python, but new to Django (using 1,9 Django and Python 2.7) -
Django/Python - Django-Auth-Ldap group restriction wildcard
I'm currently implementing Django Ldap Auth for my intranet site I'm building. It's working absolutely fine. However, I wish to restrict the authentication to a set of groups within one specific OU. I'm trying to set the AUTH_LDAP_REQUIRE_GROUP to allow any group and am using AUTH_LDAP_GROUP_SEARCH to restrict the groups found. It finds the groups required. I've attempted to use the below to restict #AUTH_LDAP_REQUIRE_GROUP = LDAPGroupQuery('(objectCategory=group)(name=*)') #AUTH_LDAP_REQUIRE_GROUP = LDAPGroupQuery('(name=*)') #AUTH_LDAP_REQUIRE_GROUP = '*' Unfortunately I get errors similar to: Caught LDAPError while authenticating username: OPERATIONS_ERROR({'desc': 'Operations error', 'info': '000020D6: SvcErr: DSID-031007E5, problem 5012 (DIR_ERROR), data 0\n'}) Is there a way to use a wildcard I'm unaware of? -
Django refresh page handler
i've created a page with Django. views.py executes a request that loads json file and transfers data retrieved to my template. Everything works fine, but i wonder how to handle the action of refreshing the page, because every time a user does this, views.py will execute the request again and that may cause a lot of problems and timeouts. I think there might be two alternatives. First one is to store variables passed to my template and do some of javascript. Second one, handling views.py and asking if json variable is not empty -
How to add foreign key relationships from within django admin
I two model classes class Product(models.Model) name = ... class Part(models.Model) product = models.ForeignKey(Product, on_delete= models.CASCADE,default=1) In my database I already have populated a number of parts. Is there a way to change Admin to allow a drop down/select of parts for the product I'm looking at, e.g I want to assign a foreign key relationship of parts A, B, C, F to the Product I'm looking at the admin page for Proudct X. I have seen the inline option, but I don't want to add new parts, I just want to be able to associate the parts with the product I'm looking at Thanks in advance for the help! -
Configuring React Routes, Django URLs using Webpack
Teaching myself how to use a React frontend with a Django server and I'm having difficulty getting the React routes to work properly. Whenever I reload the page it thinks I'm making a GET request to the server. Refreshing at localhost:8000 works fine, but anything other than an API route errors out. Pretty sure the issue is in one of my urls.py files. quiz_app/urls.py urlpatterns = [ path('', include('quizzes.urls')), path('', include('frontend.urls')) ] frontend/urls.py urlpatterns = [ path('', views.index ) ] quizzes/urls.py urlpatterns = [ path('admin/', admin.site.urls), path(r'^nested_admin/', include('nested_admin.urls')), re_path('api/quizzes/', views.QuizList.as_view()), re_path('api/quizzes/<str:name>/', views.SingleQuiz.as_view()), re_path('api/questions/', views.QuestionList.as_view()), re_path('api/answers/', views.AnswerList.as_view()) ] For good measure: frontend/views.py def index(request): return render(request, 'frontend/index.html') frontend/src/App.js class App extends Component { render() { return ( <Router> <div className="App"> <Grid> <Header /> <Route exact path="/" component={Quizzes} /> <Route exact path="/:name" component={Quiz} /> </Grid> </div> </Router> ) } }; To reiterate, the issue is that the "/:name" routes in App.js are attempting to make "GET" requests to the Django server and erroring out because there's nothing to handle them rather than defaulting to a React route. Let me know what I'm doing wrong here. I've fixed this problem when using React with other server frameworks, but I'm new to Python/Django so … -
Django forms with grid layout
I am trying to implement a grid layout for entering marks of students into my model. The model is described as: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=True) email = models.EmailField('email address', blank=False) first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='student_profile') yoe = models.IntegerField('year of enrollment', choices=YEAR_CHOICES, default=datetime.datetime.now().year) photo = models.ImageField(upload_to='student/%Y/') class Paper(models.Model): semester = models.CharField(max_length=1) name_of_paper = models.CharField(max_length=200) max_pass_marks = models.IntegerField("Max Marks",validators=[MaxValueValidator(99)]) class Test(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, default='') paper = models.ForeignKey(Paper, on_delete=models.CASCADE, default='') dot = models.DateField("Date of Test") marks = models.IntegerField("Marks Obtained",validators=[MaxValueValidator(99)], default=0) I want to be able to create a form with a grid layout where each row of the grid will have the students name followed by text boxes where users can enter the test scores obtained by students in each of the 'Paper' they have opted for. Obviously the test scores should then populate the 'Test' table/model. I am relatively new to django and cant really wrap my head around this. Any help will be appreciated. -
Unit testing in django with legacy sql server driven application
I'm trying to write unit tests for my django app with a legacy SQL Server database. This is how I access data from the database currently. I created a file called db_service.py. It's purpose is to perform raw sql queries requested by views.py and return the result back. The queries are usually fairly complex and were already created (in a legacy Perl CGI app). So I'm not too keen on creating models and using django's queryset to achieve the same. An example is shown below. views.py @login_required def view_load_from_db (request): params = request.GET.get('params') result = db_service.get_something_from_db(params) do something with result and return as JsonResponse db_serivce.py def get_something_from_db(params): query = '''complex sql query with stored procedures/joins/outer apply etc''' result = cursor.execute(query) return result For unit testing a view, I'm mocking db_service methods and returning a static pre determined result as shown below: test_views.py class ExampleTest(TestCase): @mock.patch('app.db_service.get_something_from_db') def test_view_load_from_db (self, mock_get_something_from_db): mock_get_something_from_db.return_value = {some static value} response = self.client.get(url_to_view_load_from_db , params) self.assertEquals(response.status_code, 200) But since, most of the logic lies in db_service itself, I feel like I'm not actually testing anything and also I can see how mocking could get very cumbersome to maintain too (if multiple db_service are used in a … -
Django multiple formsets in a single view only saves last value entered
I am trying to use multiple formsets in a single view, but I am not able to implement this functionality properly. For example: When I try to add say 3 values in each formset,i.e. 3 entries for 1st formset and 3 entries for 2nd formset only last enties are stored in the database and first 2 values are discarded and not saved. Please find the code written so far as below: 1) models.py from __future__ import unicode_literals from django.db import models from bokeh.themes import default from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class FeeForService(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) requestor_name = models.CharField(max_length=240, blank=False, null=False) requestor_RU_or_PL = models.CharField(max_length=240, blank=False, null=False) vendor_procurement_system = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False) vendor_name = models.CharField(max_length=254, blank=False, null=False) vendor_address = models.CharField(max_length=480, blank=False, null=False) vendor_email = models.EmailField(max_length=254, blank=False, null=False) phone_number = PhoneNumberField(blank=True) proposed_start_date = models.DateTimeField(blank=False, null=False) proposed_end_date = models.DateTimeField(blank=False, null=False) brief_proposal = models.CharField(max_length=480, blank=False, null=False) status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) class DeliverablesFeeForService(models.Model): milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False) poa_institution = … -
How to convert to a full JSON
How to convert to JSON type format. Instead of the object ID you need to get full information about it. From such [ { "title": "scenario factory - sump", "scenario_pipeline": [ { "pipeline": 11 } ], "scenario_exist": [ { "factory": 43 }, { "factory": 44 } ] } ] To such a [ { "title": "scenario factory - sump", "scenario_pipeline": [ { "title": "factory - sump", "percent": 11, "start_point": [ 57.332892983304895, 36.40013349999995 ], "end_point": [ 51.829824506973154, 43.43138349999996 ], "point": [] } ], "scenario_exist": [ { "id": 43, "title": "factory", "choice": "Factory", "address": [ 57.332892983304895, 36.40013349999995 ] }, { "id": 44, "title": "sump", "choice": "Sump", "address": [ 51.829824506973154, 43.43138349999996 ] } ] } ] My models.py The basic model of Scenario, the two remaining inline class Scenario(models.Model): title = models.CharField(max_length=200) class ScenarioExist(models.Model): scenario = models.ForeignKey('Scenario', related_name='scenario_exist', on_delete=models.CASCADE) factory = models.ForeignKey('factory.Factory', related_name='factory', on_delete=models.CASCADE) class PipelineTwo(models.Model): scenario = models.ForeignKey('Scenario', related_name='scenario_pipeline', on_delete=models.CASCADE) pipeline = models.ForeignKey('pipeline.Pipeline', null = True, on_delete=models.CASCADE, related_name = 'point_two') If you want to show the models to which the fields are accessed, I will show. My serializes.py class PipelineTwoSerializer(serializers.ModelSerializer): class Meta: model = PipelineTwo fields = ['pipeline'] class ScenarioExistSerializer(serializers.ModelSerializer): class Meta: model = ScenarioExist fields = ['factory'] class ScenarioSerializer(serializers.ModelSerializer): scenario_pipeline = … -
Issue with canonical url, when using mysql
Currently I'm using Ubuntu 18.04, I'm trying to develop blogging websites using django. I'm trying to use canonical url for displaying more meaningful url format. Every things i fine when I'm using dajngo default database i.e sqlite3. But when I shift from sqlite3 to mysql, post_detail page is not dispalying. For better explanation of my problem screenshot is given below, what i'm facing. But I'm not facing any types of error while using sqlite3.. So, Please help me out from this problem -
_str__ returned non-string (type NoneType) after migrations of mezzanine apps
During start of an Django mezzanine project, I am getting following message: You have 7 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth, blog, conf, forms, galleries, mainapp, pages. Run 'python manage.py migrate' to apply them. I have not really noticed when/why it starts appearing. I have definitely not updated any library. When I migrate, I get following error whenever I access any page: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11 Python Version: 3.6.5 Installed Applications: ('mezzanine.boot', 'modeltranslation', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.redirects', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', 'mezzanine.conf', 'mezzanine.core', 'mezzanine.generic', 'mezzanine.pages', 'mezzanine.blog', 'mezzanine.forms', 'mezzanine.galleries', 'mezzanine.twitter', 'mainapp', 'filebrowser_safe', 'grappelli_safe', 'django.contrib.admin', 'django.contrib.staticfiles', 'django_comments') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mezzanine.core.request.CurrentRequestMiddleware', 'mezzanine.core.middleware.RedirectFallbackMiddleware', 'mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware', 'mezzanine.core.middleware.SitePermissionMiddleware', 'mezzanine.pages.middleware.PageMiddleware') Template error: In template /home/matous/PycharmProjects/webapps/iacah/app/templates/base.html, error at line 0 __str__ returned non-string (type NoneType) 1 : <!doctype html> 2 : <html lang="{{ LANGUAGE_CODE }}"{% if LANGUAGE_BIDI %} dir="rtl"{% endif %}> 3 : {% load pages_tags mezzanine_tags i18n staticfiles %} 4 : 5 : <head> 6 : <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta name="keywords" content="{% block meta_keywords %}{% endblock %}"> 9 : <meta name="description" content="{% block meta_description %}{% endblock %}"> … -
2018 way of creating an upload file progress bar
The research I've done sofar led me to techologies that seem out of date. I wonder if there is a right/common way to upload files and get progress info in 2018. I've read that RFC1867 is obsolete I'm trying to setup NGINX Upload Progress Bar but it uses jsonp in its response and I've also read that I should not use jsonp. My stack is NGINX, Gunicorn, Ubuntu, Django 2.1, React I'm trying to avoid jquery I only need last version of Firefox and Chrome to be supported Note : I'm only intersted in the client/server communication part, for UI I use react semantic ui progress -
How to multithread AsyncConsumer with Django Channels
I've been working with Django Channels for a week and somethin bugs me with the runworker parallelism. For example, I have this MQTT client which publishes in the channels when it receives a message, basic. async def treat_message(msg): channel_layer = get_channel_layer() payload = json.loads(msg.payload, encoding="utf-8") await channel_layer.send("mqtt", { "type": "value.change", "message": payload }) This is sending it well. I can send how much I want, it will be sent to the redis queue. To the channel mqtt. I then run the worker which will redirect messages in the queue for mqtt with : python manage.py runworker mqtt 2018-09-12 16:33:42,232 - INFO - runworker - Running worker for channels ['mqtt'] This is where the problem begins. Here is the content of the AsyncConsumer reading the data : class MQTTConsumer(AsyncConsumer): async def value_change(self, event): await asyncio.sleep(5) print("I received changes : {}".format(event["message"])) I putted a sleep in order to simulate business of the task. And this is where I'm going : the async consumer is not multi threaded ! When I send two messages to the channel, it takes 10 seconds to the consumer to treat the second message, instead of 5 if it were multi threaded. As shown below. 2018-09-12 16:45:25,271 - … -
Universal images handler
Some of my models has image field and I want to compress those images before saving and also create thumbnail for them. So I created abstract model: from django.db import models def image_path(instance, filename): return f'{instance._meta.model_name}/{instance.id}/{filename}' class BaseImageModel(models.Model): image = models.ImageField( blank=True, null=True, upload_to=image_path ) preview_image = models.ImageField( blank=True, null=True, upload_to=image_path ) class Meta: abstract = True I'll write a method which will process all logic with images but I'm wondering whether there is more clean way to apply my logic to inherited models than call image processing method on each model's save method. -
Django-REST-Framework: ForeignKey instance is not passed to `validated_data`
I'm trying to create an instance overriding create method and passing the ForeignKey instance in the data, but that field is not included in validated_data passed to create method. How can I pass that to create ?? I have this model. class UserProfile(models.Model): name = models.CharField(verbose_name='Name', max_length=50) email = models.EmailField(verbose_name='Email') address = models.TextField(verbose_name='Address', null=True, blank=True) user = models.OneToOneField(User, verbose_name='User', on_delete=models.CASCADE) And here's my serializer. class UserProfileSerializer(ModelSerializer): class Meta: model = UserProfile fields = '__all__' depth = 2 def create(self, validated_data): print(validated_data) return UserProfile.objects.create(**validated_data) Official doc suggests to create another serializer for User model and use that, but is there any other way without creating that serializer ?? -
TypeError: 'module' object is not callable, Django rest framework
def country_list(request): if request.method == 'GET': countryList = CountryModel.objects.all() serializer = CountrySerializer(countryList, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CountrySerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.error, status=400) strong text I am getting error TypeError: 'module' object is not callable at serializer = CountrySerializer(data=data) and 'module' object is not callable at serializer = CountrySerializer(countryList,many=True). I have just started learning django, so guys help. -
Django Admin Inline FileField link to open in new tab
I have fieldfields in an inline in Django Admin. The link to the file works fine and the uploaded file is shown in browser. Now i want to make the link open in a new tab. I imagine the quickest way is to insert a target="_blank" into the html, but there seems to be no template for it - maybe it's generated by python code. Can you please help me pinpoint where to inject? Thank you very much. -
Django template - Is there a built-in way to get current date as type 'date' instead of type 'str'?
I know I can get the current date as a str in a Django template (using the template tag now), like this: {% now "Y-m-d" as today_str %} <p>{{ today_str }}</p> But I cannot use that for comparissons: {% now "Y-m-d" as today_str %} {% if object.date < today_str %} {# WRONG: this compares 'date' and 'str' #} <p>Is before today</p> {# do some other rendering #} {% endif %} Possible solutions: I know I can pass a context variable to the template, but it requires code in my view: # in my class-based-view in 'views.py' def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['today'] = timezone.now() return ctx Or I can create a custom template tag, but that is even more additional code. As you can see I have workarounds for my problem, but I would like to know if there is a buit-in way to get the current date (or datetime) in the template? -
how to integrate API with HTML in django template?
I am using both POST and GET method through python requests to fetch datas and submit data in an API. class ApiLoginView(TemplateView): template_name = 'index.html' def post(self,request): email = request.POST.get('email') print(email) password = request.POST.get('password') print(password) API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxx' API_URL = 'http://dev.com/rest/storeLogin' parameter = { 'authToken':API_KEY, 'email':email, 'password':password, } r = session.post(url = API_URL, params=parameter) print(r.json()['code']) return render(request,'index.html') With this above views.py class method i'm trying to post data.and I have an readymade HTML form for login ready. <form class="my-login-form" action="/login" method="post"> {% csrf_token %} <div class="field-wrap"> <input type="email" name="email" required autocomplete="off" placeholder="Email Id"/> </div> <div class="field-wrap"> <input type="password" name="password" required autocomplete="off" placeholder="Password"> </div> <button class="button button-block"/>Login</button> <div class="forgot"><a class="user-form-toggle" href="#forgot">Forgot Password?</a></div> </form> So my dilemma is how to map both class based view and html form. Right now it seems html form is stand alone! -
how to define a copy method in django models
i have three models for a blog , shown blow: class Author(models.Model): name = models.CharField(max_length = 50) class BlogPost(models.Model): title = models.CharField(max_length = 250) body = models.TextField() author = models.ForeignKey(Author,on_delete = models.CASCADE) date_created = models.DateTimeField(auto_now_add = True) def copy(): pass class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete = models.CASCADE) text = models.TextField(max_length = 500) i want to define a copy() method for BlogPost model that copies a BlogPost instance with copieng related comment instances . how can i do this? -
How do I add an annotation with Django annotate on a QuerySet?
I have a model class with a status field, which might have several alternatives, say: class MyModel(models.Model): status_choices = ( ('status1', 'status1'), ('status2', 'status2'), ('status3', 'status3'), ('status4', 'status4'), ) status = models.CharField(choices=status_choices) Then I want to annotate the instances with an active field which might be either True or False. The instance is active when status is IN [status1, status2]. Django version is 1.11.