Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Differences between using Resource Model (Tastypie) and single Rest-Framework function
First of all, I am new to Python and Django, I am trying to understand the pros/cons of apis by single function and apis by resources (Tastypie's ModelResources). I had been working on a Django project and been using rest-framework along all the way. However, I created each function for each api from the server. For example, this is a simple register function I wrote using rest-framework: @api_view(['POST']) @permission_classes((AllowAny,)) @parser_classes((JSONParser,)) def register(request): if request.data is not None: try: username = request.data['username'] password = request.data['password'] user = User.objects.create_user (username=utils.encrypt(username), password=utils.encrypt(password)) ...... This is another register example using Tastypie's ModelResource: class RegisterUserResource(ModelResource): class Meta: allowed_methods = ['post'] always_return_data = True authentication = Authentication() authorization = Authorization() queryset = User.objects.all() resource_name = 'register' ....... def obj_create(self, bundle, **kwargs): try: username = bundle.data["username"] password = bundle.data["password"] if User.objects.filter(username=username): raise CustomBadRequest( code=status.HTTP_201_CREATED, message="This username is taken" ) # Create object bundle.obj = User.objects.create_user(username=username, password=password) bundle.obj.save() # Create user profile object UserInfo.objects.create(user=bundle.obj) except KeyError: raise CustomBadRequest( code="missing_key", message="Must provide {missing_key} when creating a user." ) except User.DoesNotExist: pass return bundle Please help me to understand what are the differences between those two ways and which way is better. I personally think using Tastypie's ModelResource is pretty … -
Django REST framework serializer without a model
I'm working on a couple endpoints which aggregate data. One of the endpoints will for example return an array of objects, each object corresponding with a day, and it'll have the number of comments, likes and photos that specific user posted. This object has a predefined/set schema, but we do not store it in the database, so it doesn't have a model. Is there a way I can still use Django serializers for these objects without having a model? -
Why does there not exist a i18n_patterns variation for countries for Django?
We use i18n_patterns to add language codes to urls and to help us serve different content based on the language required by the client. But we can also wish to have country specific content. For example: 127.0.0.1:8000/en --> should serve content specific to the United States 127.0.0.1:8000/ca/fr --> should serve content specific to canada and french Is there another way that Django wants us to handle delivering country specific content, and if there isn't, why doesnt there exist libraries and more demand for the type of library I am asking about. PS: I found a github library that does this, but it seems to be outdated with the newer versions of Django Github Link -
AWS lambda could not connect to EC2 Mysql Server
I have been trying to connect EC2 mysql server from AWS Lambda which is not happening. I find Lambda function is perfectly working when I just comment database fetching code. I am using Django framework and using zappa to deploy code to Lambda and add setting in AWS API GateWay. Things I did: Created a user in Mysql with the aws Lambda host address While deploying with zappa Added Subnet Id and Security Group Id in settings file. Did not create new VPC as the EC2 instance has default VPC created. So I just used it. I see it Lambda function is working really fine when I just comment Database code(EC2 Mysql database, trying to fetch results from aws lambda). Code: class GetData(APIView): def post(self, request, format=None): if request.method == "POST": item_id = request.data.get('item_id') if item_id not in [None, '', ' ']: item = Item.objects.get(item_id=item_id) # Comment 1 item_name = item.item_name # Comment 2 return Response({"return": "OK OK OK OK"}) else: return Response({"return": "ITEM NOT OK "}) else: return Response({"return": "NOT OK "}) In the above code If I just comment out comment 1 and comment 2 lines I am receiving status code 200 and returning below response {"return": "OK … -
set USERNAME_FIELD to uuid can't get token correctly
I have mutiple custom backend, support phone+password, email+password, username+password, so I add user_id = models.UUIDField(unique=True) to User model, and let USERNAME_FIELD = 'user_id'. and when I use token auth(django-rest-framework supply): from rest_framework.authtoken import views url(r'^api-token-auth/', views.obtain_auth_token), then, I use httpie: http POST http://127.0.0.1:8000/api-token-auth/ username=username password=pwd --json get some error: { "non_field_errors": [ "'username' is not a valid UUID." ] } After I reset USERNAME_FIELD='username', then everything is ok, I get token correctly. -
Getting KeyError when attempting to get a value for field <field> on serializer <serializer> in Django Rest Faramework
I'm getting an error when trying to access serializer.data before returning it in the Response(serializer.data, status=something): Getting KeyError when attempting to get a value for field <field> on serializer <serializer> Because of the OrderedDict, I can change the order in which the fields are declared and I'll get a different <field> in the KeyError. The class definition looks like this: class BulkProductSerializer(serializers.ModelSerializer): list_serializer_class = CustomProductListSerializer user = serializers.CharField(source='fk_user.username', read_only=False) class Meta: model = Product fields = ( 'user', 'uuid', 'product_code', ..., ) Here's an example view: def partial_update(self, request): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list), partial=True) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() pdb.set_trace() return Response(serializer.data, status=status.HTTP_200_OK) Trying to access serializer.data at the trace causes the error. Here's the save method that is invoked in this particular case (bulk update of a list of serialized products) class CustomProductListSerializer(serializers.ListSerializer): """ Customized ListSerializer is necessary for bulk operations on Products, as per https://stackoverflow.com/a/45468966 """ def save(self): instances = [] result = [] for obj in self.validated_data: uuid = obj.get('uuid', None) if uuid: #update an existing instance instance = get_object_or_404(Product, uuid=uuid) # Specify which fields to update, otherwise save() tries to SQL SET all fields. # Gotcha: remove the primary key, because update_fields will … -
django ValidationError when submitting a form
When submitting a django form i am getting a ValidationError. In my form this is my input: 01/01/2017 But django tell me that the format must be 'AAAA-MM-GG'. With this Exception Location: /usr/local/lib/python3.5/dist-packages/django/db/models/fields/init.py in to_python, line 1271 This is the code on my project: # models.py class Archivio(models.Model): sys_codice = models.AutoField(primary_key=True) some_other_field ... class QuoteIscrizione(models.Model): sys_chiave = models.AutoField(primary_key=True) sys_cod = models.ForeignKey(Archivio, on_delete=models.CASCADE) data_quota = models.DateField(blank=True, null=True) # forms.py class ArchivioSearchForm(forms.Form): data_quota = forms.DateField(required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self: field.field.widget.attrs['class'] = 'form-control ' if type(field.field.widget) is DateInput: field.field.widget.attrs['class'] += 'datepicker' def clean(self): data_quota = self.cleaned_data['data_quota'] return self.cleaned_data # views.py def ArchivioSearchView(request): model = Archivio form = ArchivioSearchForm() if request.GET.get('data_quota'): selection = Archivio.objects.filter(Q(quoteiscrizione__data_quota__gte=request.GET.get('data_quota')) return render(request, 'search_template.html', {'selection':selection}) # search_form.html <form action="" method="get" class="form-horizontal"> <div class="form-group form-group-md"> <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}"> {% for field in form %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="{{ field.id_for_label }}">{{ field.label }}</label> <div class="col-md-6"> {{ field.as_widget() }} </div> </div> {% endfor %} <input type="submit" value="Confermo" /> </div> </form> And I also have this on my settings.py LANGUAGE_CODE = 'it-IT' TIME_ZONE = 'Europe/Rome' USE_I18N = True USE_L10N = True USE_TZ = True I have tried to use on my settings.py of … -
Django : get() returned more than one
I have trouble to get my data from DB. Basically one teacher can create more no of class_room each class_room contains a title and it has more number of students. models.py class class_room(models.model): user = models.ForeignKey(User,related_name = 'classroom') title = models.charField(max_length=50) students = models.ManyToManyField(User,related_name= 'commits',symmetrical=FAlSE) views.py def index(request): user = request.user Total_class = class_room.objects.get(user = user) students_list = Total_class.students.all() class_name = Total_class.title.all() return render(request,'trial/index.html,{'Total':Total_class ,'no':students_list, 'class_name ':class_name ) When i try to execute this code. i get this error get() returned more than one Then i removed get() bcoz the user has more number of class_room so i put filter() After that i get 'QuerySet'object has no attribute 'students' Any help appreciated :( -
What is the best practice of integrating Django with Vuejs?
There is not enough information about that topic. I want to make some part of UI using Vuejs, not 100% Vuejs+Django rest framework. The question is, how to integrate in the right and efficient way? What if I put the Vuejs scripts only to templates where I will use it. (Example: login.html, where it will validate my login form)? Using Webpack. If I gonna use the Webpack, npm packages, how to integrate it with Django, I guess if I create a folder with packages in my "static" folder it will be a disaster. Can anyone advise something, or maybe do you know a good tutorial? -
Unable to enforce authentication requirement in Django Rest Framework
I'm trying to enforce Authentication for access to my API, but the permission_classes = permissions.IsAuthenticated,) attribute of my ViewSet doesn't seem to be working. Because I try to access the User's profile later on when in get_queryset(), I'm getting errors like: TypeError: 'AnonymousUser' object is not iterable" I also have authentication set in my rest_framework settings: 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), And I also added to my dispatch method before doing the other business logic checks on the User profile: def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return Response(status=status.HTTP_401_UNAUTHORIZED) That's not working either: File "/lib/python3.5/site-packages/rest_framework/response.py", line 57, in rendered_content assert renderer, ".accepted_renderer not set on Response" AssertionError: .accepted_renderer not set on Response Why do none of these authentication controls work? -
Django DateTimeField hide date
I have a model where an object is called time which is model.DateTimeField(default=datetime.now) I also have a form where the user can specify the time, but I wanted to only have the H: M in there, not the whole datetime. I tried using the TimeInput widget in my form, but that would give me an error upon submitting because I didn't have the 'date' portion of the DateTimeField. If I use models.TimeField for time, I lose the ability to keep track of the date in the admin page. How can I hide the date from showing in my form? -
invalid literal for int() with base 10: 'explore', but I'm not using numbers. Only returning a list of shows. Any Ideas?
I'm pretty new to Django, and I'm having a hard time figuring out this error code. A lot of my searches on google lead to people using actual numbers and integers, but my ExploreListView is just suppose to show a list of shows stored in my database. I followed the exact same way I did for my ShowListView and I am not receiving that error. I've looked over it so many times line for line, and I am not sure why ShowListView is working with no error, but ExploreListView is having the error. How can I solve this error code? Please ELI5 Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/shows/explore/ Django Version: 1.11.4 Python Version: 3.6.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shows'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\detail.py" in get 115. self.object = self.get_object() File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\detail.py" in get_object 38. queryset = queryset.filter(pk=pk) File "C:\Users\\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in filter … -
NoReverseMatch at /hrfinance/home/ Django
I have no idea why i have error saying "Reverse for 'lscholarship' not found. 'lscholarship' is not a valid view function or pattern name." when i am trying to run http://127.0.0.1:8000/hrfinance/home/. Inside my views.py, i have already defined scholarship instead of lscholarship and i wrote views.scholarship in my urls.py. views.py def scholarship(request, id=None): query_results = [] if request.POST.get('delete'): Scholarship.objects.filter(id__in=request.POST.getlist('item')).delete() return redirect('/hrfinance/lscholarship/') elif request.POST.get('add'): form = ScholarshipForm(request.POST) if form.is_valid(): scholarship = form.save(commit=False) scholarship.save() return redirect('/hrfinance/lscholarship/') else: form = ScholarshipForm() id = request.GET.get('scholarship') query_results = Scholarship.objects.all() data = { 'query_results':query_results, 'form':form } return render(request, 'hrfinance/add_remove_scholarship.html', data) urls.py urlpatterns = [ url(r'^home/$', views.home, name='home'), #timesheet to be filled up by students url(r'^timesheet/$', views.timesheet, name='timesheet'), #list of timesheets under 'View Timesheet' url(r'^ltimesheet/$', views.ltimesheet, name='ltimesheet'), #list of applications under 'View Application' url(r'^lapplication/$', views.lapplication, name='lapplication'), #list of scholarships under 'Add/Remove Scholarship' url(r'^lscholarship/$', views.scholarship, name='lscholarship'), url(r'^base/$', views.base, name='base'), ] below is the traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/hrfinance/home/ Django Version: 1.11.1 Python Version: 2.7.13 Installed Applications: ['hrfinance.apps.HRFinanceConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template D:\curtin\year3 SEM 2\XiMing_2Jul\myHDR\hrfinance\templates\hrfinance\base.html, error at line 0 Reverse for 'lscholarship' not found. 'lscholarship' is not a valid view function … -
Best practices for products catalogue in Django
I'm working on a catalogue application for storing product information in Django. The challenge here is that there are a lot of products in the catalogue, each with their own attributes. Since this is a key part of the application, and a lot will be built around it, I want this to be designed as good as possible. I know there are several options of handling this in Django, but I would like to know what others have experienced with these several options. The first option: Single abstract class I could just create a single abstract class, which contains all the base attributes, and let other classes derive from that one class. class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000) price = models.DecimalField() class Meta: abstract = True class Phone(Product): series = models.CharField(max_length=100) This would be the most straightforward option, but this will include a lot of work in Django Forms and Views. This will also create a single table for each Product subclass, so when the Product class is changed, all other tables will have to changed as well. The second option: Product base class Here the Product class is not abstract, which implies this class can be used … -
How to render a form in Django in a template hierarchy
my base_page.html is this {% load static %} <!DOCTYPE html> <html lang="it"> <head> <meta charset="UTF-8"> <!-- Bootstrap and other things --> {% block head %}Additional head info{% endblock %} <title>Title</title> </head> <body> {% include "planner/navbar.html" %} {% block content %}Page content{% endblock %} <footer> <div class="navbar navbar-default navbar-fixed-bottom"> <span class="navbar-text pull-left">Credits</span> </div> </footer> </body> </html> which includes a navbar template {% load static %} <nav class="navbar navbar-default"> <!-- <div class="row"> --> <div class="col-lg-2 logo-container"> <img class="logo" src="{% static "planner/img/logo.svg" %}"/> </div> <div class="spacer col-lg-5 "></div> {% include 'planner/login_form.html' %} </nav> And then I have a homepage.html which extends base_page.html, of course. As you can see, the navbar is in turn including a login_form.html for a form I specified in forms.py, constisting of a CharField for email and a PasswordField. This is the form template: <form id="login_form" class="login-form col-lg-5 nav-links" action="{% url 'planner:login' %}" method="post"> <div class="col-lg-5 nav-links"> <div class="input-group"> {{ form.email }} <i class="glyphicon glyphicon-user form-control-feedback "></i> </div> </div> <div class="col-lg-5 nav-links"> <div class="input-group"> {{ form.password }} <i class="glyphicon glyphicon-lock form-control-feedback"></i> </div> <input type="submit" value="Login"> </div> </form> Now, how can I pass that form variable in the template hierarchy? Please consider that I'm using a TemplateView to render the homepage, … -
Why Django migration on second system does not work
I developed my application on my Laptop and wanna run them on a Raspberry Pi. On my laptop it works very well, but on my RPi it does not work. I receive that the Database and the tables are not exist. I receive the same error when i run python manage.py migrate or python manage.py makemigration All the migration files are also in the repository. How can I create the DB and the columns by a django manage.py command? -
ValueError: Expecting property name: line 4 column 9 (char 48)
I am making a Django app. Whenever I am trying python manage.py runserver I am getting the following error. I don't know what it says: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Manish/Projects/Spark/ad-tracking-django-env/ad-tracking-django/ad_tracking/__init__.py", line 5, in <module> from .celery import app as celery_app File "/Manish/Projects/Spark/ad-tracking-django-env/ad-tracking-django/ad_tracking/celery.py", line 12, in <module> app = Celery('proj', broker=settings.BROKER_URL,) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Manish/Projects/Spark/ad-tracking-django-env/ad-tracking-django/ad_tracking/settings.py", line 110, in <module> CONFIG = json.load(f) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 290, in load **kw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 4 column 9 (char 48) I have no idea where the … -
django 'StepInLine' is not defined
So I am trying to link 2 models together so I can add things easily. I tried using the stack in line way, but I get the error: "name 'StepInLine' is not defined". from django.contrib import admin from .models import Animal, About class AboutInLine(admin.StackedInline): model = About class AnimalAdmin(admin.ModelAdmin): inlines = [StepInLine, ] admin.site.register(Animal, AnimalAdmin) from django.db import models class Animal(models.Model): created_at = models.DateTimeField(auto_now_add=True) species = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.species class About(models.Model): name = models.CharField(max_length=255) weight = models.IntegerField(default=0) fur_color = models.CharField(max_length=10) animal = models.ForeignKey(Animal) def __str__(self): return self.name -
Python hangs when trying to access celery shared_task
I have a celery task within a django project which when called, does absolutely nothing. No exception is produced, Rabbit MQ nor the celery worker registers receiving the task either. @shared_task def test(): print('starting task') time.sleep(10) return True In the interactive shell if I import the task and try to run it >import twitterbot.tasks >twitter_bot.tasks.test.delay() The REPL just sits there until I send a keyboard interrupt. I then receive ^CTraceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'data' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'tasks' During handling of the above exception, another exception occurred: keyboard interrupt here .. Strangely, if I simply try to access a property of the task >twitter_bot.tasks.test I have the same issue. Is this an issue with my imports or what? -
Where put phone number filed
Some kind of user don't have phone number, some kind of user have. For example, shopping user have phone_numer, admin don't have. So I add one ShoppingPorfile(OneToOne relation to user) for shopping user, because I don't want to let phone_numer's null=True. But if do like this, I have to combine two form(UserForm + ProfileForm) to complete register: if all(user_form, profile_form): user = user_form.save() profile = profile_form.save(user=user) Does it ok? or you have more better advice. -
How to get all my feeds exclude which is commented by me
there are three classes class User(models.Model): name = models.CharField() class Feed(models.Model): user = models.ForeignKey(User) class Comment(models.Model): user = models.ForeignKey(User) feed = models.ForeignKey(Feed) If I specified a user named Jack, how to get Jack's feeds and comments of them, but not get the comments which the user of the comment if not Jack If there are two feeds of Jack: [ "feed1": [{"comment1":{"user": "Lily"}}, {"comment2":{"user": "Bruce"}], "feed2": [{"comment1": {"user": "Jack}}, {"comment2":{"user":"Lily"}], ] I use the follow code to get: Feed.objects.filter(user__name="Jack").exclude(comment__user__name="Jack") I want to get the result: [ "feed1": [{"comment1":{"user": "Lily"}}, {"comment2":{"user": "Bruce"}], "feed2": [{"comment2":{"user":"Lily"}], ] but in fact, it returns the wrong result: [ "feed1": [{"comment1":{"user": "Lily"}}, {"comment2":{"user": "Bruce"}] ] I just want remove the comment which is not commented by Jack, but it remove all the feed which one of its comment has the same user Jack -
how to use google PeopleAPI in django
I try to run the sample in the link below with Django project but the HTML file does not render completely https://developers.google.com/people/quickstart/js -
Passing a parameter to a ListView in Django
I have a HTML drop list with certain values that I want to pass to my generic view in order to return a filtered list. The class: class filteredListView(generic.ListView): template_name = 'guestlist/guestlist.html' def get_queryset_filter(self, relation): if relation == 'all': return Guest.objects.all() if relation == 'grooms_side': return Guest.objects.filter(grooms_side=True) if relation == 'brides_side': return Guest.objects.filter(brides_side=True) if relation == 'friends': return Guest.objects.filter(friends=True) html block: <th colspan="4"> <label>Filter by Relation <select> <option value="all">All</option> <option value="grooms_side">Groom's Side</option> <option value="brides_side">Brides's Side</option> <option value="friends">Friends</option> </select> </label> </th> I've tried passing the value with a normal href like a regular view but that gave me a NoReverseMatch exception. urls.py: from django.conf.urls import url from . import views app_name = 'guestlist' urlpatterns = [ # /guestlist/ url(r'^$', views.indexView.as_view(), name='index'), # /guestlist/ url(r'^guestlist/$', views.guestListView.as_view(), name='guestlist'), # /guestlist/add url(r'^guestlist/add/$', views.guestCreate.as_view(), name='add'), # /guestlist/filtered url(r'^guestlist/filtered$', views.filteredListView.as_view(), name='filtered'), ] My question is how do i pass the value from the drop list's options to the view. Thanks. -
How to set length for python Faker fields
I am trying to set up UserFactory using DjangoModelFactory and Faker. Here is my code. fake = Faker('uk_UA') class UserFactory(DjangoModelFactory): class Meta: model = User username = fake.user_name first_name = fake.first_name_male last_name = fake.last_name_male email = fake.safe_email But when I try to use it I got error: DataError Traceback (most recent call last) /Users/mero/.virtualenvs/fine-hut/lib/python3.6/site-packages/django/db/backends/utils.py in execute(self, sql, params) 63 else: ---> 64 return self.cursor.execute(sql, params) 65 DataError: value too long for type character varying(30) I assume that problem is in too long fields generated by Faker. But I didn't find any way to restrict it's length in python, though found few answers for Ruby Faker. Is there way to do this in python Faker? Or maybe there is some other way to use Faker for generate locale-specific fields? -
Django and Premade mysql databases
I have two database in mysql that have tables built from another program I have wrote to get data, etc. However I would like to use django and having trouble understanding the model/view after going through the tutorial and countless hours of googling. My problem is I just want to access the data and displaying the data. I tried to create routers and done inspectdb to create models. Only to get 1146 (table doesn't exist issues). I have a unique key.. Lets say (a, b) and have 6 other columns in the table. I just need to access those 6 columns row by row. I'm getting so many issues. If you need more details please let me know. Thank you.