Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework get user profile data for logged in user
I have created Models UserProfile, serilzers and ModelViewSet like below. From below models I want to fetch loged in User profile details like state, city and adress etc class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile'); state= models.CharField(max_length=200) city= models.CharField(max_length=200) add1= models.CharField(max_length=200) add2= models.CharField(max_length=200) postalcode= models.IntegerField() country= models.CharField(max_length=200) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('state','city','country') class UserProfileViewSet(viewsets.ModelViewSet): queryset=UserProfile.objects.all() serializer_class=UserProfileSerializer def get(self, request): userProfileObj = queryset.objects.filter(user_id=request.user.id) serializer = self.get_serializer(userProfileObj) return Response(serializer.data) But for some reason, I am getting all user profile data instead of logged in user data, please let me know where I am doing wrong. -
Django url pattern name not working
I'm trying to use url names to send a custom arg to my TemplateView. Urls.py urlpatterns = [ url(r'^$', index.as_view(template_name='index.html', gotodiv='whatis'), name='whatis'), url(r'^$', index.as_view(template_name='index.html', gotodiv='whybepartofit'), name='whybepartofit') ] Views.py class index(TemplateView): template_name = "index.html" gotodiv = '' def get_context_data(self, **kwargs): context = super(index, self).get_context_data(**kwargs) context['gotodiv'] = self.gotodiv return context Template <li> <a href="{% url 'whatis' %}">What is it?</a> </li> <li> <a href="{% url 'whybepartofit' %}">Why be part of it?</a> </li> The problem is that it doesn't care about the url name, because the patterns match in both cases. So it always goes to the first pattern (in this example, the one with the "whatis" gotodiv arg. Is there a way to configure the pattern so it only care about the name?. Thanks -
Extending tastypie API with related objects
I'm new to Django, Tastypie and asking questions here, so please bare with me :-) I've got a Django application with an API using Tastypie. If I make a GET request to /api/v1/ou/33/ my API returns the object with the id==33, which is totally cool. { "child_ou_uri": "/api/v1/ou/33/child_ou/", "displayname": "Mother", "id": 33, "inherit": true, "name": "Mother", "resource_uri": "/api/v1/ou/33/" } The thing is, I'm trying to extend the API so that it returns related objects via the child_ou_uri URI from the above object. The children are the same type of objects as their parents. The model has an attribute parent_id pointing to the pk of its parent. My OuResource looks like this... class OuResource(ModelResource): class Meta: queryset = OU.objects.all() resource_name = 'ou' list_allowed_methods = ['get'] detail_allowed_methods = ['get'] filtering = { 'name': ['icontains'], } authentication = SessionAuthentication() authorization = OperatorLocationAuthorization() def get_child_ou(self, request, **kwargs): self.method_check(request, ['get', ]) ous = OuResource().get_list(request, parent_id=kwargs['pk']) return ous def prepend_urls(self): return [ url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/child_ou%s$' % (self._meta.resource_name, '/'), self.wrap_view('get_child_ou'), name='api_get_child_ou') ] def dehydrate(self, bundle): kwargs = dict(api_name='v1', resource_name=self._meta.resource_name, pk=bundle.data['id']) bundle.data['child_ou_uri'] = reverse('api_get_child_ou', kwargs=kwargs) return bundle When I navigate to /api/v1/ou/33/child_ou/ i'd like to get the list of child objects which have their attribute parent_id set to 33, but … -
Can't get Celery task result in Django 1.11
I want to get some Celery task result in django with AJAX. I have view like this: def ajax_brand_count(request, task_id): extra_data = brand_count.AsyncResult(task_id) print("1", extra_data.state) print("2", extra_data.get()) if extra_data.ready(): print("3", extra_data) return HttpResponse('') On print 1 I get SUCCESS On print 2 I get None On print 3 I get a string which = task_id I have Redis instance running. I have Celery instance running with SETTINGS: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' What am I doing wrong? -
Render HTML inside a string
Okey, so I want to send an email with django. The HTML code contains multiple Django tags {% if .. %} dosmth.. {% endif %} This needs to be fed with data with the render_to_string function from django. However, the html is stored in a string. Is there a way to use the render_to_string function on this HTML string? I don't want to store the file as a HTML file I just want to send the email and forget about the file -
Implementing ChartJs
I am building a web application that will allow users to compare the amount of calories they have burned during exercise vs the amount they have consumed in a meal. To do this I am using ChartJS. Just to start i am hard coding in data to get an idea of hoe the graph works/looks on the page. The problem is that when i run the app the chart page is blank. Below is how I have tried to implement the chart: Views This is where I am creating the Chart view. The data is hard coded in for the time being. class ChartView(View): def get(self, request, *args, **kwargs): return render(request, 'nutrition/chart.html', {"users": 10}) def get_data(request, *args, **kwargs): data = { "calories_in": 200, "calories_out": 300 } return JsonResponse(data) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs_count = User.objects.all().count() labels = ["Users", "Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [qs_count, 12, 22, 13, 11, 15] data = { "labels": labels, "default": default_items, } return Response(data) HTML Here is my html page that I am using to display the chart. I have added all the relevant imports that are need for chartjs javascript. <script> {% block jquery … -
Generic relationship many to one or many to many?
I am facing the following problem: I want to create a Consequence Model (Aka : Pros and Conts model) that can be associated to different models (Generic Relationship Django) and contains the following info: Consequences : Boolean (Positive or Negative) Of : Model_Primary_Key Reason : Text Author : User_Primary_Key Users_likes : List<Users> An object (Of attribute) can have many consequences but a consequence will only belong to one consequence , so it should be a many to one relationship. The problem is that I don't know if the relation between the consequence model and the other models are many to one or many to many. Usually when you have a one to many , the part that has the many contains a foreign key to the other, but here if i do that the foreign key will be Author and Of and the set will be the composite primary key , but if I do that here , a user cannot have more than consequence per object and it should be possible. So the only solution that I found is to add to consequence an id as primary key , so at the end it works like a many to … -
app-celery: ERROR (no such file)
I've followed the tutorial on how to implement celery on my django production server, using supervisor. I've done this successfully, however when I try to start supervisor with sudo supervisorctl start app-celery - it returns: app-celery: ERROR (no such file) Here is my config in the folder /etc/supervisor/conf.d (app-celery.conf): [program:app-celery] command=/home/app/bin/celery worker -A draft1 --loglevel=INFO directory=/home/app/draft1 numprocs=1 stdout_logfile=/var/log/supervisor/celery.log stderr_logfile=/var/log/supervisor/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 Any idea what the problem is? -
Django Unittest 302 response
I am trying to do a unit test for my django application. Whenever i try a get request to a particular page, it redirects me to the login page. I have logged into the web app once in setUp. Below is my code. I have referred to many questions such as 22208821 but cannot get it working. Below is my code. from django.test import TestCase,Client from django.contrib.auth.models import User import unittest class SimpleTest(TestCase): def setUp(self): self.client = Client() self.username='testuser' self.email = 'test@test.com' self.password='12345' self.user = User.objects.create_user(username=self.username,email=self.email,password=self.password) login = self.client.login(username=self.username,password=self.password) self.assertEqual(login,True) def test_details(self): response = self.client.get('/dashboard/') print(response["location"]) self.assertEqual(response.status_code, 200) The output i get is Creating test database for alias 'default'... System check identified no issues (0 silenced). /admin/login/?next=/dashboard/ F ====================================================================== FAIL: test_details (interview.tests.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "path", line 22, in test_details self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.181s Thanks for any help! -
How to popolate a recursive m2m field
I have a class in my model with a recursive m2m field My model.py: class Person(models.Model): name = models.CharField(_('name'), max_length=64) slug = models.SlugField(primary_key=True) friends = models.ManyToManyField('self', related_name='nation_friends', symmetrical=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Person, self).save(*args, **kwargs) I populate my database with a script. The problem comes when an istance has references to not yet created istances My script.py: john = add_person('John', ['marc', 'philip']) #john = add_person('John', [marc, philip]) #this gives immediately error: marc is not definited marc = add_person('Marc', []) philip = add_person('Philip', []) def add_person(name, friends): p=Person.objects.get_or_create(name=name)[0] lista_friends = [] for f in friends: lista_friends.append(f) p.friends.set(lista_friends) This is the error (my translation, below the original) django.db.utils.IntegrityError: ERROR: the INSERT or the UPDATE on the table "core_person_friends" break the constrain of external key "core_person_friends_to_person_id_ab3c358a_fk_core_person_slug" DETAIL: The key (to_person_id)=(marc) is not present on the table "core_person". original: django.db.utils.IntegrityError: ERRORE: la INSERT o l'UPDATE sulla tabella "core_person_friends" viola il vincolo di chiave esterna "core_person_friends_to_person_id_ab3c358a_fk_core_person_slug" DETAIL: La chiave (to_person_id)=(marc) non ?? presente nella tabella "core_person". Maybe the problem is because the slug field? -
Django db.sqllite-3 ,auto delete databse error
When i put my django web app in production hosted on digital ocean platform . Problem is when i update the database the database is updated for few minute and then it automatically delete the data which is in database i am not able to understand the probem.plz Help Thanks in advance. -
Django: Generating dynamic inlines with pre-filled field?
Newbie django user here. I'm using class-based views for all my forms. But in one, I want to create a Parent Model and Child Models. I've started with an inlineformset_factory and specify the 'extra' models I need. Then I moved to having just one and adding new inlines dynamically with a jquery pluging. All was working fine. I'm using (for this form) this models: class Entry(models.Model): Client = models.CharField(max_length=20) description = models.TextField() class Box(models.Model): weight = models.IntegerField() material = models.ForeignKey(Material,...) Right now, it's working. I can add boxes, get the context data, validate it, all the good stuff. But it's tedious. If the user wants to add 20 Material A boxes and 30 Material B boxes, that's 50 'Add box' click, 50 'select A/B' material and input the weight 50 times. This is how admin section looks What I want is to have every box grouped by Material, so I would have 2 TabularInline-admin like groups, one of each Material. Ideally, with a small form specifying the material and the number of boxes. The user then, would select Material A, 20 boxes, then 20 boxes inlines would be created. So my question is: How I can create groups of inlines … -
MongoEngine : cannot connect to database
I have been using mongoengine for connecting my Django app with MongoDB database. While following everything that is there in the docs: https://mongoengine-odm.readthedocs.io/guide/connecting.html and https://staltz.com/djangoconfi-mongoengine/#/ I am getting the following error: mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST) File "/usr/local/lib/python3.6/dist-packages/mongoengine/connection.py", line 164, in connect return get_connection(alias) File "/usr/local/lib/python3.6/dist-packages/mongoengine/connection.py", line 126, in get_connection raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e)) mongoengine.connection.ConnectionError: Cannot connect to database default : [Errno -2] Name or service not known This is in my settings.py DATABASES = { 'default': { 'ENGINE': '', }, } _MONGODB_USER = 'aayush' _MONGODB_PASSWD = 'password' _MONGODB_HOST = 'thehost' _MONGODB_NAME = 'abcde' _MONGODB_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME) mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST) When I just specify an empty Engine and mongo.connect('abcde') I get an ImproperlyConfigured: settings.DATABASES is improperly configured error. Any help is appreciated. Thanks -
connect to Django DB SQLite from different computers
I have a Database on django in sqlite3 i want to get access to those tables from different computers with python script to get data update data ect... How do i connect in python to those table? Tnx for the help -
Change model in jwt django REST
I want to use jwt for authentication, but I don't want use User model. How can I do this. I know, I should override JSONWebTokenSerializer and set obj in jwt_payload_handler, but display this error message: object has no attribute 'username' -
str object has no attribute get ,view not rendering the form
enter image description here ://i.stack.imgur.com/nwIsS.png ps://i.stack.imgur.com/wWiIv.png -
Django- Postgres: raise TypeError("Model instances without primary key value are unhashable")
Now I'm working on Django project with postgresql. When I did python3 manage.py migrate, I got following error. raise TypeError("Model instances without primary key value are unhashable") I have no idea, where I got this error and how to solve this. -
Django : Error 'str' object has no attribute 'get' when populating model with csv file
I'm trying to populate a model with an csv file like this : if form.is_valid(): #form.save() print("form1 valid") csvfile = request.FILES['myfilebase'] print(csvfile) try: f=open(csvfile,"rt") #print(csvfile) my_data = csv.reader(f) for row in my_data: print(row) except: msg = "Cannot open file - is it CSV?" print("not opened") return msg else: print("not valide form") but I'm getting this error : 'str' object has no attribute 'get' this problem is in the csvfile variable , because when I replace csvfile with the full path, my code works perfectly. I guess I'm missing something when get the file name from my FileField Any help how can I handle this error. Thank you so much -
Convert multiple python files into one that will run it (from Python Django)
At the moment I have a python application that relies on multiple python .py files, folders, .html files etc. to run. I need to convert it to an .exe application for delivery, but most of the converters I see can only do it when the application runs from one .py file. How to I convert all these files into one .py file? I've been using python django to this point, which requires it run from multiple files. I'm new to python, so maybe this is a really easy answer, but I can't find anything on it. The file structure at the moment looks like this: /todolist/ /__pycache__/ __init__.py settings.py urls.py wsgi.py /todos/ /__pycache__/ /migrations/ (migrations to mysql server) /static/ (css files) /templates/ (html files) __init__.py admin.py apps.py models.py tests.py urls.py views.py manage.py -
NoReverseMatch at /groups/14/ Reverse for 'join' not found. 'join' is not a valid view function or pattern name
I have a M2M relationship between User and Group. Currently, I am trying to add the join group functionality. These are the steps I did: 1: (groups/models.py) from django.db import models from django.contrib.auth.models import User # Create your models here. class Group(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True, default='') image = models.ImageField(upload_to='images/') members = models.ManyToManyField(User) def __str__(self): return self.name 2: (urls.py) urlpatterns = [ path('create/', views.create, name='create'), path('index/', views.index, name='index'), path('<int:group_id>/', views.detail, name='detail'), path('<int:group_id>/join/', views.join, name='join'), ] 3: (views.py) def join(request, group_id): if request.method == 'POST': group = get_object_or_404(Group, pk= group_id) group.members.append(request.user) group.save() return redirect('/groups/' + str(group_id) ) else: group = get_object_or_404(Group, pk= group_id) return render(request, '/groups/detail.html', {'group': group}) 4: (groups/detail.hmtl) {% block content %} <div class="row"> <div class="col-4"> <h1>{{group.name}}</h1> </div> <div class="col-6"> <p>{{group.description}}</p> </div> <div class="col-2"> <a href="javascript:{document.getElementById('join').submit()}"><button class="btn btn-primary btn-lg btn-block"> Join {{product.members.count}}</button></a> </div> </div> <div class="row"> <div class="col-4"> <img src="{{group.image.url}}" alt=""> </div> </div> <form method ='POST' id= 'join' action="{% url 'join' group.id %}" > {% csrf_token %} <input type="hidden" > </form> {% endblock %} firstly, I am getting a error when I try to render the detail page with the join button. the error is as follows: "NoReverseMatch at /groups/14/ Reverse for 'join' not found. 'join' … -
How to get values from a linked model for validation?
I don't now how get other fields, linked by OnetoOne witch User model, in method clean. I have models Profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) books = models.CharField(max_length=25) And I want validation in method clean: class ProfileForm(UserCreationForm): class Meta: fields = '__all__' def clean(self): cleaned_data = super().clean() get_books = cleaned_data.get('books') #this I get error I get only default user model fields (username, first_name..) How get value from the field 'books'? -
Django Rest Framework : Access primary key of field in serializer.is_valid -> serializer.errors
When I get an errors while validating data in django REST Framework, how can I get the id value of the piece of data which failed ? Here is a simple use case of my problem. I got a simple model : class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) And a basic serializer : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('__all__') Now, sometime, when adding a list of users with the following function, I get errors : def add_users(data): serializer = UserSerializer( data=data, many=True) if serializer.is_valid(): serializer.save() else: for index in range(0, len(serializer.errors)): logger.error("Validation failed: {0}".format(serializer.errors[index])) Errors looks like : Validation failed: {'name': ['This field may not be null.']} Validation failed: {'name': ['This field may not be null.']} But I have 100 different users in my list. I would like to know the PK/id values of the ones who have no "name" attribute. How can I do that ? -
Django UpdatingProfile form
I am building an application that allows users to view and edit their own personal profile. Users are able to view their profile and the profile is editable from the admin side. However when a user tries to edit their own info, they are getting a NameError telling them that args is not defined. Below is how I have tried to implement the editing functionality: forms class UpdateProfile(forms.ModelForm): username = forms.CharField(required=False) email = forms.EmailField(required=False) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) age = forms.IntegerField(required=False) height = forms.IntegerField(required=False) weight = forms.IntegerField(required=False) class Meta: model = User #These are the fields that i want to be made editable. fields = ('username', 'email', 'first_name', 'last_name', 'age', 'height', 'weight') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): super(UpdateProfile, self).__init__(*args, **kwargs) #Here i am trying to add the new data to the users profile if commit: user_profile.user.save() return user_profile Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('account/profile.html')) else: form = UpdateProfile() args['form'] = form return render(request, 'account/edit_profile.html', args) -
One-to-many inline select with django admin 2018 UPDATED
I faced with the same issue as described here or here. In short: I have 2 models. Book and Shelf. In admin form ("add shelf") I would like to select from the books that are already in the library. By default is not available. I used the solution (from links above) and everything works until I try to "save" new object . Error: Unsaved model instance (Shelf: ShelfAlpha) cannot be used in an ORM query. #models.py class Book(models.Model): shelf = models.ForeignKey(Shelf, blank=True, null=True, related_name="in_shelf") #admin.py class ShelfForm(forms.ModelForm): class Meta: model = Shelf books = forms.ModelMultipleChoiceField(queryset=Book.objects.all()) def __init__(self, *args, **kwargs): super(ShelfForm, self).__init__(*args, **kwargs) if self.instance: if self.instance.in_shelf: self.fields['books'].initial = self.instance.in_shelf.all() else: self.fields['books'].initial = [] def save(self, *args, **kwargs): instance = super(ShelfForm, self).save(commit=False) self.fields['books'].initial.update(shelf=None) self.cleaned_data['books'].update(shelf=instance) return instance It seems like in 2014 was working but now it's not. I would appreciate for help! -
You must install the FeedParser python module
erreur installation dasbord collectorenter image description here