Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django absolute __in query
I have a list of UUIDs that represent users in a DB table. I want to fetch all the users that match this criteria so I use the __in filter: users = User.objects.filter(user__in=uuids) I would like to raise an exception if not all of the UUIDs appear in the table. In other words, I expect to get a result back for each uuid such that len(users) == len(uuids). Is there an easy Django way to do it? If not, is there an easy way for me to create this behavior? -
Getting distinct objects of a queryset from a reverse relation in Django
class Customer(models.Model): name = models.CharField(max_length=189) class Message(models.Model): message = models.TextField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="messages") created_at = models.DateTimeField(auto_now_add=True) What I want to do here is that I want to get the queryset of distinct Customers ordered by the Message.created_at. My database is mysql. I have tried the following. qs = Customers.objects.all().order_by("-messages__created_at").distinct() m = Messages.objects.all().values("customer").distinct().order_by("-created_at") m = Messages.objects.all().order_by("-created_at").values("customer").distinct() In the end , I used a set to accomplish this, but I think I might be missing something. My current solution: customers = set(Interaction.objects.all().values_list("customer").distinct()) customer_list = list() for c in customers: customer_list.append(c[0]) -
Django `python manage.py runserver` does not support asyncio&aiohttp
In my Django app, I need to proxy a request from the user to other servers. And I use asyncio/aiohttp client. #user->request ..... loop = asyncio.get_event_loop() future = asyncio.ensure_future(self.run(t1, t2, t3)) loop.run_until_complete(future) ...... # response When my django server is started with python manager.py runserver,the following error occurs when the user requests. RuntimeError: There is no current event loop in thread 'Thread-1'. But when I start with Gunicorn, everything is ok. Maybe I should use new_event_loop? Why there is no problem with Gunicorn? -
Create new tag and add it to a specified article
I want to add tags to an article, the model table structured as: class Tag(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=Tre) def __str__(self): return self.name class Meta: ordering = ("id",) class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) ... I retrieve the latest article, then create a tag record using forward query and add it to the article, In [45]: a = Article.objects.all().last() In [46]: a Out[46]: <Article: learn django> In [47]: a.tags.create(name="django") It throw exception: IntegrityError: (1048, "Column 'owner_id' cannot be null") So, I have to repeat the article inside the article's manager In [48]: a.tags.create(name="djang", owner=a.owner) Out[48]: <Tag: django> I guess it's a replicated job, since I am working exactly inside a particular article but have to declare which article I am in to create a tag. How to do it in DRI principle? -
Database Api Python/django
I am working on a tutorial on Django When I invoke the interactive shell to access the database API using the command python manage.py shell, I receive the following prompt In [1]:from music.models import Album, Song In [2]: Album.objects.all() Then the next line gives me this OperationalError: no such table: music_album -
unable to install Django in win 10
I am trying to install Django in windows 10 through - pip install django command but getting the error -- " -- "Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) - skipping". I have tried using the proxy server also but none worked. ". I have tried installing using the proxy also but none worked. -
Django : Previous and next week button
I am creating a timesheet application. I want to display timesheet on a weekly basis, which I am able to do. I have create previous and next week button. what approach should I use, so that when someone clicks on previous week, it shows timsheet for previous week and same for next week. note - I have a timesheet table that contains one entry per day for time entry. models.py -- class TimeRecords(models.Model): emp_id = models.IntegerField(verbose_name = 'Employee ID') ts_date = models.DateField(null=False, blank=False,verbose_name = 'Time Sheet Date') ts_effort = models.PositiveIntegerField(default=8,verbose_name = 'Hours worked') ts_desc = models.CharField(max_length=200,verbose_name = 'Time Description') class Meta: verbose_name = 'Time Records' verbose_name_plural = 'Time Records' unique_together = (("emp_id", "ts_date"),) ordering = ["-emp_id"] def __str__(self): return self.ts_desc forms.py --- class CreateTimeSheetForm(forms.ModelForm): emp_id = forms.IntegerField(widget=forms.HiddenInput(), initial=123) class Meta: model = TimeRecords fields = '__all__' labels = { "ts_desc": "Task Description" } widgets = { 'ts_date': forms.TextInput(attrs={'readonly': True}), } views.py --- def dateEnds(): date=datetime.date.today() year, week, dow = date.isocalendar() if dow == 1: start_date = date else: start_date = date - timedelta(dow) end_date = start_date + datetime.timedelta(days=7) return start_date ,end_date def daterange(): start_date, end_date=dateEnds() for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) def timeEntryList(request): start_date, end_date=dateEnds() time_records=TimeRecords.objects.filter(emp_id=emp_id,ts_date__range= … -
How to create a unique reference for the result each time?
In general, I make a page on the site. The meaning is this: a person comes in, loads an xml file, selects several parameters, and outputs the result. I did not find how to handle the xml file at once. So I upload its file with the parameters to the database, and then redirect us to the page with the result. Everything works fine, but there is a problem. I have not figured out how to create a unique link for the result each time. Now I have one link for the results and it just shows the last one ... views.py of uploader def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('lessons:index') else: form = DocumentForm() return render(request, 'templates/upload/upload.html', {'form': form}) downloader views.py of handler def lessons_view(request): a = keker() return render(request, 'templates/lessons/ocenki.html', {'ocenki': a}) keker if handler function -
Django-REST-framework Concrete-View-Classes not returning json?
I'm working on a new app using React and DRF in which React must get the data from DRF in JSON and parse the data. But I think some of my Generic View Classes do not return JSON correctly. For Example, a "ListCreateAPIView" class returns this: [{"id":5,"name":"5 Storey I=1.3","Value":1399511075,"NSt":5},{"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5},{"id":7,"name":"5 Storey I=1","Value":1363157800,"NSt":5}] While a "RetrieveUpdateDestroyAPIView" class returns this: {"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5,"jRatio":"[0.2,0.4,0.4]","jEDR":"[0.02,0.1,0.5,1]","jStrDrSL":"[0.3826667,0.6046667,0.78,0.8666667]","StrDrB":0.8,"jNStrDrSL":"[0.4,0.8,2.5,5]","NStrDrB":0.75,"jNStrAccSL":"[0.25,0.5,1,2]","NStrAccB":0.5,"jPGA":"[0.141,0.374,0.550,0.822]","jRePr":"[75,475,975,2475]","NNTH":7,"jP_CL":"[ 0 , 5 , 6 , 7 ]","jMIDR":"[[[0.014488,0.021893,0.010635,0.029521,0.009106,0.013556,0.034016], [0.019524,0.022306,0.013733,0.041172,0.012122,0.019027,0.027467], \r\n[0.018057,0.019549,0.01485,0.034628,0.010172,0.022447,0.02065], \r\n[0.018057,0.015954,0.009193,0.024401,0.006838,0.022809,0.017592], \r\n[0.017192,0.012215,0.009257,0.016268,0.005854,0.019945,0.012777]], \r\n\r\n[[0.016604,0.025492], \r\n[0.026047,0.03113], \r\n[0.02794,0.02432], \r\n[0.024571,0.01748], \r\n[0.023962,0.014474]], \r\n\r\n[[0.040325], \r\n[0.044064], \r\n[0.035164], \r\n[0.024971], \r\n[0.020532]], \r\n\r\n[[1], \r\n[1], \r\n[1], \r\n[1], \r\n[1]]]","jMAcc":"[[[0.081014271,0.126595311,0.094557594,0.094250765,0.068444444,0.088719674,0.118411825], \r\n[0.06911213,0.091793068,0.097146789,0.11106422,0.056927625,0.118172273,0.103258919], \r\n[0.076614679,0.077261978,0.120961264,0.144769623,0.055780836,0.08214475,0.123833843], \r\n[0.082191641,0.08675739,0.129832824,0.13788685,0.04724159,0.071845056,0.091466871], \r\n[0.18904791,0.111108053,0.098691131,0.13933945,0.052319062,0.198410805,0.117994903]], \r\n\r\n[[0.184002039,0.156264016], \r\n[0.18011213,0.122554536], \r\n[0.24753211,0.136911315], \r\n[0.292653415,0.120941896], \r\n[0.255610601,0.127876656]], \r\n\r\n[[0.201146789], \r\n[0.173687054], \r\n[0.17719368], \r\n[0.172267074], \r\n[0.187479103]], \r\n\r\n[[1], \r\n[1], \r\n[1], \r\n[1], \r\n[1]]]"} Notice that the data doesn't start with a bracket "[" and because of this I'm not able to parse it in React. I need to know where the problem is. Should I not use GenericViewClasses? views.py: class BuildingsList(ListCreateAPIView): queryset=Building.objects.all() serializer_class=BuildingSerializerList class BuildingDetails(RetrieveUpdateDestroyAPIView): queryset=Building.objects.all() serializer_class=BuildingSerializerDetails urls.py: urlpatterns=[ path('', BuildingsList.as_view()), path('<int:pk>/', BuildingDetails.as_view()),] serializers.py: class BuildingSerializerList(serializers.ModelSerializer): class Meta: model=Building fields=['id','name','Value','NSt'] class BuildingSerializerDetails(serializers.ModelSerializer): class Meta: model=Building fields='__all__' -
How do I upload photos to django media root directory using a completely different python script?
I am using django 1.9 and I have created a website with it. The database I am using with django is MySQL (django.db.backends.mysql). Everything in the website works fine. I can retrieve, delete and put files in the MEDIA_ROOT directory using the website's interface that I have successfully designed. Now, I am making a desktop app version of the website. The whole thing is created using python. I can connect to the same database as my website using the python program and I want my python program to be able to upload images to the mysql database in a way so that they are stored in the django MEDIA_ROOT directory. Also, I want to be able to retrieve images from the MEDIA_ROOT directory so that I can save it in the same directory as my python program. How do I upload and download media files from the MEDIA_ROOT directory of django assuming that it is not locally hosted but hosted on the internet using a python script? -
Django custom dictionary response
I am using Django rest framework and I have a view that returns information but in dictionary format. Here is the model I have: class Child(models.Model): name = models.CharField(max_length=50, unique=True) age = models.IntegerField(null=False, blank=False) height = models.IntegerField(null=False, blank=False) I want to return the following response as dictionary where the name field is the key: { "Alice Allen": { "age": 3, "height": 98 }, "Bob Brady": { "age": 4, "height": 105 } } I know I can use the GenericAPIView and implement the logic in 'get' method (get the data and parse into a dictionary) but I wonder if there is another solution using Django serializers. Thanks. -
ElasticSearch_dsl issue
I am trying to integrate elastic within the django existing db. but within the site packages i am facing Errors on running the local server or to view the respective commands. Below is the versions of packages i m using, django-elasticsearch-dsl==0.5.0, elasticsearch==6.3.0 and elasticsearch-dsl==6.2.1. File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/__init__.py", line 3, in <module> from .documents import DocType # noqa File "/home/pacewisdom-31/Desktop/envs/elas_envs/lib/python3.6/site-packages/django_elasticsearch_dsl/documents.py", line 8, in <module> from elasticsearch_dsl.document import DocTypeMeta as DSLDocTypeMeta ImportError: cannot import name 'DocTypeMeta' Thanks in advance. -
How to imitate new app in Django admin
I have few models in my Django app. How do I imitate another app to create app section for one of my models in admin interface? -
Django: Cannot download generating file
I am trying to generate a text file and download it from link in the template but nothing happen after I click a link. This is my link in template. <a href="{% url 'download' %}"><h2>{{ fname }} {{ lname }}</h2></a> And this is my views def report_generate(request): f = open("test.txt", "w+") for i in range(10): f.write("This is line %d\r\n" % (i + 1)) response = HttpResponse(f.read(), content_type='text/plain') filename = "guru99.txt" response['Content-Disposition'] = 'attachment; filename="%s"' % filename return response What happen? Why the file not downloaded? -
FieldError while using Q objects- cannot resolve keyword __ into field
Fairly new to django. contructign view for index page . using 'complex lookups using Q objects' as in documentation. Coming across the following error Request Method: GET Request URL: http://127.0.0.1:8000/music/?q=wretched Django Version: 1.11.12 Exception Type: FieldError Exception Value: Cannot resolve keyword 'album_title_icontains' into field. Choices are: album_favorite, album_logo, album_title, artist, genre, id, song, user, user_id Exception Location: /usr/lib64/python2.7/site-packages/django/db/models/sql/query.py in names_to_path, line 1352 Python Executable: /usr/bin/python Python Version: 2.7.15 the function view causing problem is index() (given below) def index(request): if not request.user.is_authenticated(): return render(request, 'music/login_form.html') else: albums= Album.objects.filter(user=request.user) songs=Song.objects.filter(album=albums) num= Album.objects.filter(user=request.user).count() req= request.GET.get("q") if req: albums= albums.filter( Q(album_title_icontains=req) | Q(artist_icontains=req) ).distinct() songs=songs.filter( Q(song_title_icontains=req) ).distinct() context={ 'object_list': albums, 'num': num, 'songs': songs } return render(request, 'music/index.html', context) the models.py file file is as given below from __future__ import unicode_literals from django.contrib.auth.models import Permission, User from django.db import models from django.core.urlresolvers import reverse class Album(models.Model): user= models.ForeignKey(User, default=1) artist= models.CharField(max_length=100) album_title= models.CharField(max_length=200) genre= models.CharField(max_length=50) album_logo= models.FileField() album_favorite= models.BooleanField(default=False) def get_absolute_url(self): return reverse('music:detail',kwargs={'pk':self.pk}) def __str__(self): return self.album_title+' by '+ self.artist class Song(models.Model): album= models.ForeignKey(Album, on_delete=models.CASCADE) song_title= models.CharField(max_length=200) audio_file= models.FileField(default='') is_favorite= models.BooleanField(default=False) def __str__(self): return self.song_title def get_absolute_url(self): alb= self.album return reverse('music:detail',kwargs={'pk':alb.pk}) Help would be much appreciated. Thanks in advance. -
Getting dropdown list id and save into view.py file
models.py This is my models.py file class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) join_date = models.DateField(default=datetime.today()) end_date = models.DateField(default=datetime.today() + timedelta(days=7)) package_status = models.BooleanField(default=True,blank=True) phone_number = models.CharField(max_length=30, blank=True) idboard= models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.pyThis is my forms.py file class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') phone_number = forms.CharField(help_text='Required. Format: 03001234567') idboard = forms.ModelChoiceField(queryset=Board_TB.objects.filter(pk__in=b[1,2]),required=False) class Meta: model = User fields = ('username', 'email','password1', 'password2','phone_number','idboard') views.py This is my views.py file def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.phone_number = form.cleaned_data.get('phone_number') user.profile.idboard = form.cleaned_data.get('idboard') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('index') else: form = SignUpForm() return render(request, 'accounts/signup.html',{'form' : form,}) but I am facing this error: IntegrityError at /accounts/signup/ ('23000', "[23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'idboard', table 'edxlinkdb.dbo.accounts_profile'; column does not allow nulls. UPDATE fails. (515) (SQLExecDirectW); [23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The statement has been terminated. (3621)") -
creating records in a model with multiple foreign keys Django
So i have a model with multiple foreign keys fields class Designations(models.Model): designation_id = models.AutoField(primary_key=True) curriculum = models.ForeignKey(Curricula, on_delete=models.CASCADE) role = models.ForeignKey(Roles, on_delete=models.CASCADE) staff = models.ForeignKey(Staffs, on_delete=models.CASCADE) class Meta: db_table = "arc_designations" unique_together = ('curriculum', 'role', 'staff') verbose_name_plural = "Designations" ordering = ['designation_id'] def __str__(self): return '%s of %s %s (%s)' % (self.role.role_name, self.curriculum.course_period.course.course_abbreviation, self.curriculum.module_period.module.module_abbreviation, self.staff.staff_full_name) i want to create a record in this model, so how do i do so in a function view -
Python, Facebook Graph API — AttributeError: 'GraphAPI' object has no attribute 'put_objects'
graph=facebook.GraphAPI(auth.extra_data['access_token']) graph.put_objects('me','feed',message=status.message) Traceback (most recent call last): File "", line 1, in AttributeError: 'GraphAPI' object has no attribute 'put_objects' -
How to send zip file in httpresponse attachment in python
I am making a jquery ajax POST request and passing the data to backend python code in Django framework. I need to return the zip file as httpresponse which should be automatically downloaded in browser. object_body = request.body.decode('utf-8') loaded_json = json.loads(object_body) json_obj = ast.literal_eval(str(loaded_json)) zip_file_path = importexport.download(json_obj,user) zip_filename = os.path.basename(zip_file_path) with open(zip_file_path, 'rb') as zip: response = HttpResponse(zip.read(), content_type = 'application/x-zip') response['Content-Disposition'] = 'attachment; filename=' + zip_filename return response -
Group by query django
Can I obtain something like this in Django? Teacher has multiple evaluations, this evaluations has multiples "grades", so, I would like to obtain every evaluations given by each teacher. Until now, I can obtain every grade by every teacher, but I would like to group this grade by teacher. Is it possible? Thanks a lot -
how to update request using signals in django when db saved using update_fields
i am using django 1.8 h_user = Hi.objects.get(username=request.user.username) h_user.first_name = request.data.get('first_name') #edit f_name h_user.middle_name = request.data.get('middle_name') #l_name h_user.save(update_fields=('first_name', 'middle_name')) in this case db and table updated but my other function request still showing old name, so how to solve using signals (now request has=old f_name and l_name and instance in signal has new f_name and l_name) this i tried to update the request(contains old names) with instance(it contains new edited names) def save_profile(sender, instance, **kwargs): instance.save() post_save.connect(save_profile, sender=h_models.Hi) it is not working -
django PasswordChangeView always redirect to login
i use django PasswordChangeView to change password, but the url always redirect to login view , can anybody help me? in views.py: from django.contrib.auth import views as auth_views class PasswordChangeView(auth_views.PasswordChangeView): template_name = 'accounts/registration/password_change_form.html' in urls.py: urlpatterns = [ path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('password_change/', views.PasswordChangeView.as_view() , name='password_change'), ] but when i goto password_change url, it redirect to login ??? [18/Jul/2018 13:17:53] "GET /accounts/password_change/ HTTP/1.1" 302 0 [18/Jul/2018 13:17:53] "GET /accounts/login/?next=/accounts/password_change/ HTTP/1.1" 200 4772 -
Not able to upload django admin form image into specifc folder and display it in webpage
My project structure is as follows project | |---app1 | | | |---models.py | |---views.py | |---templates | |---index.html |---media | | | |---images | | |--- (i want to save uploaded images here) I want to upload images from /admin page to the project/media/images directory. Then I want to use it from project/app1/templates/index.html. I am using the following code: def content_file_name(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (instance.name, ext) return os.path.join('images', filename) ... class Alpha(models.Model): image = models.ImageField(verbose_name="thumbnail", default=os.path.join('images','defthumb.png'), upload_to=content_file_name) And using the following in index.html: <img src="{{ dataset.image.url }}" If the upload directory is correct, the webpage <img> src url becomes inside app1 folder. How to make both upload and serving url at same location? -
Django REST Browsable API Template Change
I want to customize the Django REST Framework Browsable API template (simply to change the branding to a different name and link). I have read the documentation on how to achieve this and did the following initially in the following path: hints(project)->hints1(app)->templates->rest_framework->api.html api.html: {% extends "rest_framework/base.html" %} {% block title %} Handy Dev Hints - API {% endblock %} {% block branding %} <span> <a class='navbar-brand' rel="nofollow" href="{% url 'html' %}"> -----HTML View----- <span class="version">1</span> </a> </span> {% endblock %} I also modified my settings.py as follows, specifically the DIRS section: settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] From the tutorials I've watched and the docs I read this should have been enough to implement the change. However, it did not work. So then I decided to just change the base.html directly in the site-packages library. base.html: <!DOCTYPE html> . . . {% block body %} <body class="{% block bodyclass %}{% endblock %}"> <div class="wrapper"> {% block navbar %} <div class="navbar navbar-static-top {% block bootstrap_navbar_variant %}navbar-inverse{% endblock %}" role="navigation" aria-label="{% trans "navbar" %}"> <div class="container"> <span> {% block branding %} <a class='navbar-brand' … -
How to structure django admin for multiple users
I'm still a complete newbie on Django, so now I'm a little bit lost on what I could do to structure my server to suit my needs. The situation is like this: my Django admin could be accessed by the admin and multiple users. Each user can add multiple item to the server, and the server will only allow them to retrieve, modify and delete item added by them and not the other users. They will also have some custom option they can pick: like receiving notifications through emails or another channels. Meanwhile, admin can see all items, and have a filter to see all items added by one user and all users's custom option. Any help would be appreciated.