Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Expected view likeList to be called with a URL keyword argument named "id"
Ive been trying to create an API that would return all objects from Like model however, I received an error (Expected view likeList to be called with a URL keyword argument named "id". Fix your URL conf, or set the .lookup_field attribute on the view correctly.). Here is my model class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = models.Manager() image = models.ImageField(upload_to='post_pics') def __str__(self): return self.title @property def useremail(self): return self.author.email @property def owner(self): return self.author def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) def get_api_url(self, request=None): return api_reverse('post-detail', kwargs={'pk': self.pk}, request=request) def get_like_count(self): return self.like_set.count() class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Serializer class likeserializers(serializers.ModelSerializer): username = serializers.SerializerMethodField(read_only=True) post_title = serializers.SerializerMethodField(read_only=True) class Meta: model = Like fields = ('id','created', 'user','username', 'post','post_title') def get_username(self, obj): return obj.user.username def get_post_title(self, obj): return obj.post.title Views class likeList(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'id' serializer_class = likeserializers def get_queryset(self): return Like.objects.all() URLS urlpatterns = [ path('users/', API_views.userList.as_view(), name = 'users'), path('users/id=<int:id>/', API_views.userListbyID.as_view(), name = 'usersid'), path('posts/', API_views.postList.as_view(), name = 'post'), path('posts/id=<int:id>', API_views.postListbyID.as_view(), name = 'postid'), path('likes/', API_views.likeList.as_view(), name = 'likes'), path('likes/id=<int:id>', API_views.likeListbyID.as_view(), name = 'likesid'), path('follows/', API_views.followList.as_view(), name = 'likes'), path('follows/id=<int:id>', … -
Render The Count of filtered values through for loop in django template
I am trying to write a qyeryset that output the count of Pending and Delivered orders related to each Location throug a for loop in the Template. for example: My models are: Locations Model Class Locations(models.Model): class Meta: verbose_name_plural = "Locations" Name = models.CharField(max_length=250) Status Model class Status(models.Model): class Meta: verbose_name_plural = "Status" status = models.CharField(max_length=250) Contains three values [delivered, pending, and under process] Orders Model: class Orders(models.Model): class Meta: verbose_name_plural = "ALL Orders" Time_Registered = models.DateField(blank=False) Number = models.CharField(max_length=500) Locations = models.ForeignKey(Locations, on_delete=models.CASCADE) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Remarks = models.TextField(max_length=1000, blank=True, null=True) Time_Delivered = models.DateField(blank=True, null=True) -
PythonAnywhere image not found
Before anyone deletes this due to the question being similar to others: Neither other questions nor the documentation got my site to work as intended. The goal: Load images on my site The problem: Image not found Additional info: It works locally using python manage.py runserver What I've done to try to fix it: I've tried to follow the staticfiles guide https://help.pythonanywhere.com/pages/DjangoStaticFiles but this didn't work because I'm not using the default uploaded files handling. I've tried to enter it under the PythonAnywhere > Web > static files tab but haven't been able to get that to work. Tried a bunch of different solutions from the PythonAnywhere forum and SO forum and none got my site to work. The site: http://nasablogdeployment.eu.pythonanywhere.com/ All code available here: https://github.com/MarkdenToom/NASA-blog -
How can I replace the forms with my serializer in django
Model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,default='') # user = models.OneToOneField(User, on_delete=models.CASCADE) phone_no = models.CharField(max_length=13,unique=True) registered = models.BooleanField(default=False) spam = models.BooleanField(default=False) def __str__(self): return self.user.username Serializer.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField() class Meta(): model = User fields = ('username','email','password') class UserProfileSerializer(serializers.ModelSerializer): class Meta(): model = UserProfileInfo fields = ('phone_no',) views.py def register(request): registered = False if request.method == 'POST': user_serializer = UserSerializer(data=request.POST) profile_serializer = UserProfileSerializer(data=request.POST) if user_serializer.is_valid() and profile_serializer.is_valid(): user = user_serializer.save() user.set_password(user.password) #saving hash value of password user.save() profile = profile_serializer.save(commit=False) profile.user = user profile.registered = True profile.save() registered = True else: print(user_serializer.errors) else: user_serializer = UserSerializer profile_serializer = UserProfileSerializer return Response(request,'basic_app/registration.html',{ 'user_serializer':user_serializer, 'profile_form':profile_form, 'registered':registered }) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print(username,password) user = authenticate(username=username, password=password) print(user) if user: if user.is_active: login(request,user) return render(request,'basic_app/search.html') else: return HttpResponse('Account not active!') else: # print(username,password) return HttpResponse('Login credentials not correct!') else: return render(request,'basic_app/login.html') Now I need to make changes to my views.py such that I can parallely populate the user and the profile model having one to one field. I was using the form which was working well but now I need to convert the code to rest API. Please help how I can keep the … -
django Failed at "hello world" error: No module named 'userdash.urls'
I am trying to create a simple webroot level HttpResponse and it says my module is missing when I surf to it. $ cat exchange2/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'burp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '192.168.42.12', '192.168.42.13'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'userdash', ] 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', ] ROOT_URLCONF = 'exchange2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'exchange2.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") $ cat userdash/url.py from django.urls import path from . import views urlparterns = [ path("", views.index, name="index"), ] $ cat … -
QuerySet django returns unnecessary things
I'm doing a django app which consists in an e-commerce website. I have a profile page, and inside I show all articles bought by the connected user. So for that I do a QuerySet: class ProfileView(generic.ListView): template_name = 'eduardoApp/profile.html' context_object_name = 'order_list' def get_queryset(self): return Order.objects.filter(user=self.request.user.id,ordered=True) And in my profile page I do like this: {% for order in order_list %} <div> <p> {{ order.user }} </p> <p> {{ order.articles.all}} </p> <pl> {{ order.ordered }} </p> <p> {{ order.ordered_date }} </p> </div> {% endfor %} The order.articles.all is returning the following : <QuerySet [<OrderArticle: Bottle of Wine>]> But my question is : how do I only display 'Bottle of Wine' ? Instead of diplaying QuerySet {<....> -
IntegrityError at /notes/add NOT NULL constraint failed: notes_note.created
I have a problem when I do add function in django2 cant add new post And this code enter image description here [enter image description here][2] -
Django crypto wallets and payments library
I want to build a game and betting website with Django and cryptocurrency payments with cryptocurrencies like BTC ETH XMR LTC USDT DASH ...etc like bc.game website, and I don't know how the structure it is do I need to create wallet for each user that registered on a website to handle deposits and withdrawals? or should I make a unit wallet for example blockchain wallet for the entire website? how can I make withdrawal address different and unique for each user? Do Django libraries support this? I'm a little confused about this. -
How view file in interface django admin?
I mean, when form write into the db with file upload into folder "upload". How can i see the file in interface admin? my models.py: def user_directory_path(instance, filename): ext = filename.split() filename = "%s_%s_%s_%s.%s" % (instance.last_name, instance.first_name, instance.middle_name,instance.date_birth, ext ) return os.path.join('upload', filename) class Professional(models.Model): .... upload = models.FileField('Файл', upload_to=user_directory_path) Some screenshots with error: file correctly displayed in interface erroe when i try open the file -
Pycharm Autocomplete django,emmet etc. not working in html at <body> tags
it's working pretty well in head tags in the other hand body tags ... it's same when i try to use Emmett like h1>h2 and tab working good at head tags but in the body tag it's just making spaces -
How to run django-made venv on pythonanywhere?
I am a django beginner and I have made a django app on my PC that uses MySQL Connector. I always run it by going into django's venv's scripts folder and then opening a cmd window and giving an "activate" command. Then, I go to a web browser and run my website on http://localhost:8000.... I want this same website run on Pythonanywhere and I have uploaded all the files of django folder including the venv folder --- all of them correctly placed as in my PC. When i open a "bash console" in the "scripts" folder (placed in venv folder) and type "activate", then it says "command not found". Please help me. Thank you! -
Google Cloud Video Intelligence checking free monthy usage programatically
I have been using Google Cloud Video Intelligence succesfully with my content with the following code for some time with my Django application running on Google App Engine Flex. gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name video_client = videointelligence.VideoIntelligenceServiceClient() features = [videointelligence.enums.Feature.OBJECT_TRACKING] operation = video_client.annotate_video(gs_video_path, features=features) As explicitly stated by Google Cloud, each month the following is Feature First 1000 minutes Minutes 1000+ Label detection Free $0.10 / minute Shot detection Free $0.05 / minute, or free with Label detection Explicit content detection Free $0.10 / minute Speech transcription Free $0.048 / minute Object tracking Free $0.15 / minute Text detection Free $0.15 / minute Logo recognition Free $0.15 / minute Celebrity recognition Free $0.10 / minute How can I programatically detect that the free first 1000 minutes has been used, or the current usage for these features at that instant ? -
Open EDX lms login doesn't redirects to dashboard
Open EDX lms login doesn't redirects to dashboard, instead it goes back to homepage. Whenever I click the sign in button from any other page (like a course), it sign in perfectly, when I click the button from homepage, it returns to homepage and doesn't even show the logged in user. I think I have this code (main.html), that is sending the homepage url (or any other page when clicked from there). <%def name="login_query()">${ u"?next={next}".format( next=urlquote_plus(login_redirect_url if login_redirect_url else request.path) ) if (login_redirect_url or request) else "" }</%def> How can I make it perfect? -
How to translate form validation errors based on url?
I was creating a multi-linguistic app in Django,almost everything is done.I just have to translate the validation errors in another langauge if the user is on that. I wanna keep it simple.No external API'S and other stuff. Here's what i tried to do In my form I tried to get the current url. And then check what's the url and translate the errors based on that. def __init__(self, *args, **kwargs): current_url = kwargs.pop("url",None) print(current_url,"current_url") super(ContactForm,self).__init__(*args, **kwargs) fields = self.fields if current_url == "/nl/contact/": self.add_custom_error("name",{"max_length":"Je naam mag niet meer dan 20 tekens bevatten.", "required":"Voor het versturen van uw bericht hebben wij uw naam nodig, vul deze aub in!"}) self.add_custom_error("email",{"invalid":"Voer een geldig e-mailadres in", "required":"Voor het versturen van uw bericht hebben we uw e-mailadres nodig, vul deze aub in!"}) self.add_custom_error("subject",{"max_length":"Uw onderwerp mag niet meer dan 40 tekens bevatten.", "required":"Voer het onderwerp in om het bericht te verzenden!"}) self.add_custom_error("message",{"required":"Het berichtenblok moet worden ingevuld om een geldig bericht te kunnen verzenden!",}) elif current_url == "/en/contact/": self.add_custom_error("name",{"max_length":"Your name can't be more than 20 characters.", "required":"For sending your message we need your name.Please enter it!"}) self.add_custom_error("email",{"required":"For sending your message we need your email.Please enter it!","invalid":"Enter a valid email address!"}) self.add_custom_error("subject",{"max_length":"Your subject can't be more than 40 … -
how to iterate list in django html template
I have a list that i put in table in template in Django: <tr><th></th>{% for year in years %}<th>{{ year }}</th>{% endfor %}</tr> The years inlcude list or years from 2000-2020 whereas i wanted only print the last 5 years from the list so i tried: <tr><th></th>{% for year in years %}<th>{{ year[:4] }}</th>{% endfor %}</tr> however this way it does not work. How to iterate only 5 years from the list instead of 20. -
P5.js and Django: Saving a soundfile to a server
I am trying to record audio through the user's microphone and then save it as a wav on the server running Django. I based my code on this: https://discourse.processing.org/t/uploading-recorded-audio-to-web-server-node-js-express/4569/4 I am getting two errors: Error: [object ReadableStream] p5.js:78248 Fetch failed loading: POST "http://localhost:8000/ajax/postRecordedAudio/". The first thing my server code does is print out a message that "postRecordedAudio was reached", so I know it's getting to that url. I tried using a blobURL and passing that as a string. I tried using a form and attaching the soundblob to a file input field in the form. I tried making the soundblob into a file by adding a name and date attribute and then attaching it to the form. Any help is greatly appreciated! Here is the code, It just starts recording for one second and then tries to post it. <!DOCTYPE html> <html lang="en" dir="ltr"> <head> {% load static %} <script src="{% static '/js/p5.js'%}"></script> <script src="{% static '/js/addons/p5.sound.js'%}"></script> <script src="{% static '/js/addons/p5.dom.js'%}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> let soundFile; function setup() { mic = new p5.AudioIn(); mic.start(); soundRec = new p5.SoundRecorder(); soundRec.setInput(mic) soundFile = new p5.SoundFile(); button = createDiv(""); button.position(100,100); button.size(100,100); button.style('background-color', 'grey'); button.mouseClicked((mouseEvent)=>{ getAudioContext().resume(); console.log("recording...."); soundRec.record(soundFile); … -
Getting date value from django queryset
I have a Models like below class Member(models.Model): memberid = models.AutoField(primary_key=True, editable=False) memberdate = models.DateTimeField(default=timezone.now) fname = models.CharField(max_length=25) mname = models.CharField(max_length=25) lname = models.CharField(max_length=25) mobile1 = models.CharField(max_length=15) email = models.CharField(max_length=150) dob = models.DateTimeField(default=timezone.now) I am fetching data to display in the html template. For the view below is the code def updateMemberView(request, id): searchmem= id member = Member.objects.filter(memberid=searchmem).values() print(member[0]) return render(request, 'Member/member_update_form.html', {"member": member}) Now in print(member[0]) I am getting {'memberid': 13, 'memberdate': datetime.datetime(2020, 4, 11, 0, 0, tzinfo=<UTC>), 'fname': 'Akash', 'mname': 'chimanbhai', 'lname': 'khatri', 'mobile1': '', 'email': 'kashkhatri@yahoo.com', 'dob': datetime.datetime(2020, 4, 3, 0, 0, tzinfo=<UTC>)} But when I try to print the value of dob in template using member.0.dob it gives me error. Also when I try to execute command print(member[0].dob) this also give me error 'dict' object has no attribute 'dob' So How could I get the dob value in view and also in template. -
Django/Python Dynamic Microservices
I am trying to build a microservice architecture based on Python language and specially around Django and Flask. We were working on JHipster, which is based on SpringBoot and provides a set of library and "out-of-the-box" microservices. Now we moved to Python, we are looking for some packages, such as: A Gateway: an entrypoint with dynamic routing feature. A discovery server: allowing microservice to register and unregister (realtime) Of course, we can develop our stack but we think that it should already exists? -
Why does Requests' Session.get() raise an requests.exceptions.ConnectionError instead of requests.exceptions.Timeout, when a timeout occurs?
I'm sending a Requests GET request using a Session as follows: with requests.Session() as rs: with rs.get(url, params={}, headers={}, auth=self.auth, verify=self.ssl_verify, timeout=30) as r: ... I was expecting a requests.exceptions.Timeout error to be raised, when the timeout=30 had elapsed, but instead a requests.exceptions.ConnectionError was raised: Traceback (most recent call last): File "/Users/nlykkei/projects/atlassian-watchdog/confluence/confluence.py", line 118, in __producer with rs.get(url, params={}, headers={}, auth=self.auth, verify=self.ssl_verify, timeout=30) as r: File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 543, in get return self.request('GET', url, **kwargs) File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 530, in request resp = self.send(prep, **send_kwargs) File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 683, in send r.content File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/models.py", line 829, in content self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b'' File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/models.py", line 758, in generate raise ConnectionError(e) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='confluence.danskenet.net', port=443): Read timed out. The documentation clearly states that: If a request times out, a Timeout exception is raised. So, why is a requests.exceptions.ConnectionError raised in my case? -
Why I can't install pillow with pip
I created a ImageField in model.py file and when I tried to run Python gave me an error. It says I have to install pillow . So I typed pip install pillow command. Then it started installing and after some time (though I thought it was successfully installed) it gave another error and said that it was not successfully installed. It gave me bunch of red colored text that I didn't understand. -
How can I update sqlite3 after any time login in Django 2.2?
I use from django.contrib.auth.models import User in Django for Authentication. I want update 1 column of auth_user table when any user login. @login_required def showmap(request): return render(request,'index.html') -
Django pass a filtered query set between class based views
I have a Django class based ListView, which is filtered within its get_queryset function, using url parameters from a filter form, that returns an object_list. Now I want to export the filtered content of the ListView by using a button that calls a second class based view for exporting the list to a .csv file. Both views are not the problem, but how do I get the data from the ListView, after its filtered, to the export view. Tried something with sessions, but did not get that to work. Perhaps it is possible to hand over the filter parameters but I always ran into problems with the request.session cache, which seems not to be available, even if everything necessary is enabled in the settings. Any ideas for a good approach on this? Everything I read so far about sessions did not help especially with class based views. -
Django. Submitting form with valid data returns http 405 after submission with invalid data
trying to implement crud with ajax and got stuck with this error. When I fill the form with correct data it works perfectly fine, but if I try to submit the form with an invalid data to verify error handling and then re-submit it I get 405 error returned. The only thing what comes into my mind is problem with repeatable csrf_token verification, but I guess I'm incorrect... Here is my view for processing request: def create_employee(request): data = dict() if request.method == "POST": form = AddEmployee(request.POST) if form.is_valid(): form.save(commit=False) form.instance.works_for = request.user.works_for form.instance.property_id = request.user.property_id form.save() data.update({'form_is_valid': True}) employees = User.objects.filter(property_id=request.user.property_id) data.update({'html_single_employee': render_to_string('single_employee.html', {'object_list': employees})}) else: data.update({'form_is_valid': False}) else: form = AddEmployee() context = {'form': form} data.update({'html_partial_employee_create': render_to_string('partial_employee_create.html', context, request=request )}) return JsonResponse(data) Here is HTML with js: {% extends "base.html" %} {% block content %} <!-- Button that triggers modal with form to add an employee --> <div class="row mt-1 ml-3"> <button id="OpenCreateEmployeeModal" type="button" class="btn btn-dark btn-sm open-modal"> Add employee </button> </div> <!-- Modal itself --> <div class="modal fade" id="CreateEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> {% include "partial_employee_create.html" %} </div> </div> </div> <!-- Personell display section --> <div class="container"> <div class="row justify-content-center"> <table … -
Is it possible to change the management/commands directory in Django?
In Django it's possible to write custom management commands. These are stored by default in the proj/app/management/commands directory of your application. Is there a way to change this location to a custom directory? E.g. /proj/cmd/? For example, to change the migrations directory you can use the MIGRATIONS_MODULES setting. Is there an equivalent for management commands? It doesn't appear to be documented. -
Retrieve a python list from external python file(Django)
I'm trying to retrieve a python list that generates from an external python file(algorithm.py). In algorithm.py has a set of functions that used to generate a python list. There is no issue with algorithm.py file and it generates the python list as I expect. I followed the below steps to get the python list which generates in algorithm.py into views.py. 1.) Pass a variable(lec_name) from a function in views.py to algorithm.py and retrieve the output by using stdout as the below statement. lec_name = request.POST['selected_name'] result = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) 2.) And then when I print(result.stdout), I receive the output(the python list which I expect) as an array of byte as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]\r\n" 3.) Then I used print((result.stdout).strip()) to remove \r\n and It gives output as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]" This gives the python list which I expect as an array of byte So what I need, retrieve the output(the python list which I expect) as a python list. How can I solve this? I tried lot of things, but none succeeded. I'm using Python 3.7.4, Django 3.0.1