Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing test inside function
I have two functions running at the same time(simultaneously). I want to write my test inside one of them. I mean I want to run my test's simultaneously with my other function. Because my other function creates fake data such as it creates votes if that turn is "night". So my test file is stated below. How can I run my test simultaneously with other function. def function1(): call_command('fake') def function2(): # some codes here # I also want to write my tests here because I need to fake command is running # while my test's running thread1 = Thread(target=function1) thread2 = Thread(target=function2) thread1.start() thread2.start() time.sleep(10) fake data generator is stated below while room.status != 'Finished': if turn and turn.type == 'Day' sleep(0.5) to_be_killed = RoomPlayer.objects.filter( room=room).filter(alive=True).order_by("?")[0] Vote.objects.create( day=turn, voter=room_players[j], voted=to_be_killed) -
Django channels3 Testing calling sync from async
I'm having a problem with Django Channels 3. I want to call the http test client from an async function. Here is my function def broadcast_message(client, message): return client.post( reverse("message-broadcast"), message, content_type="application/json") Here is the async function @pytest.mark.asyncio @pytest.mark.django_db(True) async def test_end_to_end(client): http_response = await loop.run_in_executor( None, broadcast_message, client, test_message) RuntimeError: Task <Task pending name='Task-1' coro=<test_end_to_end() running at /usr/src/app/tests/test_consumer_and_view.py:62> cb=[_run_until_complete_cb() at /usr/local/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.8/asyncio/futures.py:360]> attached to a different loop tests/test_consumer_and_view.py:62: RuntimeError I want to understand what is going on and how to fix it. Thanks. -
How to create a custom interface for django orm from legacy odbc
I'm accessing an application backend with a proprietary odbc driver provided by the platform vendor (Progress DataDirect ODBC, customized SDK build). This odbc works with pyodbc but not django's orm. Is there a guide for building a custom interface and adding that to django's list of databases? Or is there a way to inject the pyodbc connection or override the queryset's connection? Or is there a way add a pyodbc (not sqlserver) in the DATABASES section of settings.py? -
Is this the right way to use <> inside path()? [closed]
The code inside urls.py: from django.urls import path path('web/edit<str:webname>', views.edit_web), The code inside views.py: @login_required def edit_web(request, name): return render(request, 'edit.html') -
Custom query to or from a Serializer in djang rest framework
Given I have this enum in my model: MEDIA_TYPES = ( ('A', 'Acrylic'), ('W', 'Watercolor'), ('MM', 'Multimedia'), ('G', 'Gouache'), ('O', 'Oil'), ('P', 'Pencil'), ('C', 'Charcoal'), ('PS', 'Pastel'), ('CO', 'Conte Crayon'), ) These could be selected for artwork objects in my admin. I want to create a serialized json for only the ones used. Let's say I have a number of objects, but they only use Watercolor, Oil and Charcoal and not the other media. How do I return an object that looks like this: [ { "W": "Watercolor" }, { "O": "Oil" }, { "C": "Charcoal" } ] -
NoReverseMatch at /property/city/city/
I am developing a web commerce Django app and keep running into this bug. Below are some screenshots. Any help appreciated. Models.py Urls.py Views.py Template -
How to make full page tabs that act as webpages?
Sorry I'm showing a lot of code but I cant convey my meaning well enough. So my first page works perfectly, you type in a URL, information from that product shows up then the user clicks it then the name of the product become the tab name and the url path. I want to make this work with tabs where each time you press a new tab it takes you to the starter page and each tab acts as an individual page. How could I do this using JavaScript. HTML var className = document.getElementsByClassName('tabs'); var itemcont = document.createElement("div"); itemcont.id = "itemcont"; var imgcont = document.createElement("div"); imgcont.id = "imgcont"; var prodcont = document.createElement("div"); var title = document.createElement("h1"); prodcont.id = "prodcont"; imgcont.innerHTML = '<a onclick="move()"><img id="image" src="https://cdn.searchenginejournal.com/wp-content/uploads/2019/11/2.3-5dbd10f9530fc-480x360.png"></a>'; title.innerHTML = '<a onclick="move()"><h1>Razer Huntsman Mini Mercury Mercury Ed. (Red Switch) - Compact Gaming Keyboard (Compact 60 Percent Keyboard with Linear Opto-Mechanical Switches, PBT Keycaps, Detachable USB-C Cable) US Layout , White</h1></a>'; itemcont.appendChild(imgcont); prodcont.appendChild(title); itemcont.appendChild(prodcont); document.getElementById("myTextInputID") .addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); var input = document.getElementById("myTextInputID") .value; if (input.includes("")) { document.getElementsByClassName("containFORM")[0] .insertAdjacentElement("beforeend", itemcont); document.getElementById("prodcont") .insertAdjacentElement("afterbegin", imgcont); document.getElementsByClassName("containFORM")[0] .style.backgroundColor = "white" } else { var URLerror = document.createElement("p"); URLerror.classList.add("error"); var urlerror = document.createTextNode("This … -
Heroku Error Deploying, Conda Related Error
I am deploying my first application to Heroku and am receiving the following error. It is a Django application remote: ERROR: Could not find a version that satisfies the requirement conda==4.6.14 (from -r /tmp/.../requirements.txt (line 17)) (from versions: 3.0.6, 3.5.0, 3.7.0, 3.17.0, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.0.4, 4.0.5, 4.0.7, 4.0.8, 4.0.9, 4.1.2, 4.1.6, 4.2.6, 4.2.7, 4.3.13, 4.3.16) remote: ERROR: No matching distribution found for conda==4.6.14 (from -r /tmp/.../requirements.txt (line 17)) Line 17 of requirements.txt is /Downloads What exactly does this error mean? -
Trying to download pyhton and django
i've just tried to download python but i keep getting the same message, Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I'm not sure on how to fix it, i tried to diasble the shortcut from setting but it then said "The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." If there is any help out there it is greatly appreciated. Thanks. -
In Django if we use google oauth why the email address are not added in the User model?
In my Django app, I have a used google oauth2 for login, so when a user signs up, the first_name, last_name and username are automatically added to the User model and can be viewed through the admin panel. But the email addresses of the user are not being added, why is it so? Is there any way we can add the email address to the User model when the user signs up using OAuth? -
Should I set up all the logging messages in every page of my django project?
Should I use all of these in views and models and urls in my django project?: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') I mean, should I just paste these at the end of the files in my project or should I do something different? Would that be enough? (I'm new to logging). -
How to Fixed Django Database Error On Apache Server
The Best Way To Permission Apache Server http://coder-i.com/Digital-Ocean-Apache-To-Django-Database-Operational-Error -
Docker Airflow within Fedora issue on LDAP
can anyone assist with an Docker Airflow within Fedora issue on LDAP , I'm getting the following error after configuring ldap within airflow.cfg File ldap3/strategy/base.py line 147 in open raise LDAPSocketOpenError(unable to open socket exception_historyldap3.core.exceptions.LDAPSocketOpenError: ('unable to open socket', [(LDAPSocketOpenError("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)',)",), ('ldaps://', 636))]) Any idea how this can be resolved all certs (.cer .key & CA) have been loaded successfully and airflow is running on https://hostname:8080/ -
Clean method is calling another clean method if ValidationError is raised
In my forms.py I have two forms. One is a called a SeriesForm which gets it fields from Series model in models.py, another one is called a SeasonsForm which gets it fields from Seasons model in models.py. If ValidationError is raised in SeasonsForm it calls SeriesForm clean method which is what I don't want if no ValidationError is raised SeriesForm clean method isn't called and everything works fine. The reason I don't want this behavior is because I am rendering both forms in the same page and this behavior causes the other form(SeriesForm) to display values that I've entered in SeasonsForm (when I submit the form). The SeriesForm is like a user editing his profile page, in simple words it gets it instance from the database to fill the values so I do something like this in views.py: series = Series.objects.get(...) SeriesForm(request.POST, instance=series) # notice the instance parameter Maybe because the Seasons model has a foreign key that references Series model it calls the SeriesForm clean method is it because of that? Complete Code I've provided comments in code to help to focus on the important things. models.py class Series(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) SeriesName = models.CharField(max_length=30, default="") slug … -
Allow GET request for only certain Group of Users Django Rest Framework
I am just getting started with Django Rest framework and want to create a feature such that it allows superuser to create a message in admin.py and allow it only to be seen by a certain group(s) ie. "HR","Managers","Interns" etc. in other words, only a user belonging to "HR" group will be allowed to get data from view assigned to "HR" group by admin. I would like to have only one view that appropriately gives permission. Something like #views.py class message_view(APIView): def get(request): user = request.user group = get_user_group(user) #fetches user's respective group try: #if message assigned to 'group' then return API response except: #otherwise 401 Error I need some guidance with this. -
HTML - Create multiple forms out of one form template
I currently have multiple forms that are similar but have small changes. First, the user choses the form from a drop-down menu and then the form is shown below. My forms looks like this. Form 1 Customer Name Phone Number Address Form 2 Customer Name Is married? Form 3 Customer Name Social Security Number Address My code looks something like this. <select onchange="changeOptions(this)"> <option value="" selected="selected"></option> <option value="form1">f1</option> <option value="form2">f2</option> <option value="form3">f3</option> </select> <form class="className" name="form1" id="form1" style="display:none"> ---form--- <form class="className" name="form2" id="form2" style="display:none"> ---form--- <form class="className" name="form3" id="form3" style="display:none"> ---form--- <script> function changeOptions(selectEl) { let selectedValue = selectEl.options[selectEl.selectedIndex].value; let subForms = document.getElementsByClassName('className') for (let i = 0; i < subForms.length; i += 1) { if (selectedValue === subForms[i].name) { subForms[i].setAttribute('style', 'display:block') } else { subForms[i].setAttribute('style', 'display:none') } } } </script> Is there any way to create a 'main' form that has all the form elements and then specify which element to use in each form? The method I'm using right now works fine but there is too much repeated code and probably won't scale correctly if I try to make a change in one of the elements (since I would have to change each one of them and it … -
How to match 2 fields in html (django)
I have a question answer quiz. When I put it in html I get such a result current result (image) I have to manually select the question but I do not want to. I want the question and its corresponding form to appear automatically. what i want (image). I can't guess exactly but I think I have a view to change this is code --> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> {% for i in e %} <form method="POST" novalidate> {% … -
Field 'id' expected a number but got 'favicon.ico'
I am building a blog app. AND i am using Django 3.8.1 Version. I am stuck on a Problem Traceback (most recent call last): File "C:\app\so\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value return int(value) The above exception (invalid literal for int() with base 10: 'favicon.ico') was the direct cause of the following exception: File "C:\app\so\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\app\so\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\app\so\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\app\mains\views.py", line 261, in detail_view data = get_object_or_404(Post,pk=id) File "C:\app\so\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\app\so\lib\site-packages\django\db\models\lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "C:\app\so\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File … -
Django Rest Framework Auth backend JSON Web Token not generating tokens
Hello everyone I'm new to Django Rest Framework I just want token based authentication backend in my project. I follow this REST framework JWT Auth and saw another token based authentication backend Simple JWT both looks same I am totally confused and get demotivated please guide me how can i acchive this task and how these two backends(REST framework JWT Auth & Simple JWT) are different to each other and which one i should choose. Here is my code for UserRegistration in DRF using REST framework JWT Auth backend and it gives me this error. Its because of get_token(self, obj) in serializer.py file raise DecodeError("Invalid token type. Token must be a {0}".format( jwt.exceptions.DecodeError: Invalid token type. Token must be a <class 'bytes'> Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ] } import datetime JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': # 'rest_framework_jwt.utils.jwt_response_payload_handler', 'users.api.utils.jwt_response_payload_handler', # 'JWT_SECRET_KEY': settings.SECRET_KEY, # 'JWT_GET_USER_SECRET_KEY': None, # 'JWT_PUBLIC_KEY': None, # 'JWT_PRIVATE_KEY': None, # 'JWT_ALGORITHM': 'HS256', # 'JWT_VERIFY': True, # 'JWT_VERIFY_EXPIRATION': True, # 'JWT_LEEWAY': 0, # 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300), # 'JWT_AUDIENCE': None, # 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } serializers.py class UserRegistrationSerializer(serializers.ModelSerializer): password1 … -
Django comparing string value from model with int
I'm working on a project and got stuck while trying to figure out how to compare int value that I get from my form with the string value in my model. *Project is a tech shop and I'm creating filters for it. Among them are number of cores and amount of RAM. The thing is when I'm comparing the values for cores (also string, models are below) everything works fine, but with RAM it just doesn't wanna work. models.py class Specs(models.Model): product = models.ForeignKey(Product, ...) spec_name = models.CharField(...) [for amount of ram it is 'ram', for number of cores is 'cpuc'] spec_value = models.CharField(...) [for RAM or number of cores it would be just a number(still string)] Now in my views.py I get the GET data and do the following: **results is the filter from Product model num_of_cores= str(request.GET['num_of_cores']) results = results .filter(Q(specs__spec_name__iexact='cpuc') & Q( specs__spec_value__gte=num_of_cores)) This works fine, but the one bellow, for some reason just doesn't work: ram_amount= str(request.GET['ram_amount']) results= results.filter(Q(specs__spec_name__iexact='ram') & Q(specs__spec_value__gt=ram_amount)) I have no idea what the deal is. The variables are all the same type and it works for one but not the other. I don't understand... -
Getting duplicate users in leaderboard
I'm trying to make a leaderboard for the most liked users by counting the likes of their post and ordering them. However if the user has 2 or more post, it will duplicate the user in the leaderboard with the total likes that he has. Is there a way to fix this? Thank you. models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.TextField(max_length=1500, verbose_name='Content') likes = models.ManyToManyField(User) views.py: def top_user(request): top_user = Post.objects.annotate(total_likes=Count('user__post__likes')).order_by('-total_likes') context = {'users': top_user} return render(request, 'blog/top_user.html', context) html: {% for top in users %} <h5>{{ top.user }}</h5> <p>Upvotes: {{ top.total_likes }}</p> {% endfor %} -
ProgrammingError at / relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c
while deploying on Heroku I am getting this error. I did local migrations already. My website is running on localhost:8000. It's working perfectly and no complaints there. My heroku website is running, but my database isn't there on my heroku server. I suspect that it's a Django migrations problem, but I can't fix it. I tried the following code: heroku run python manage.py migrate. Same error as before. I tried add, commit and push for the heroku server. git add 'theblog/migrations/* git commit -am 'Heroku' git push heroku It was successful, however 'heroku run python manage.py migrate' was not sucessful. Same message as before. Possible, delete the heroku server and I could try again ~ $ ./manage.py makemigrations Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line … -
RingCentral OAuth with Django
I'm working through RingCentral's Authorization Flow Quick Start App using Django. This required making a few changes to the Flask code provided, but most of the flow is working. The index page sends me to RingCentral login, which then sends me back to the test page as it should. But when I click on any of the three links on that page I get the same error: AttributeError at /test/ 'bytes' object has no attribute 'get' Here's the Django view that handles the test page (slightly modified from the Flask code provided): def test(request): platform = SyncConfig.rcsdk.platform() platform.auth().set_data(request.session['sessionAccessToken']) if platform.logged_in() == False: return index(request) api = request.GET.get('api') if api == "extension": resp = platform.get("/restapi/v1.0/account/~/extension") return resp.response()._content elif api == "extension-call-log": resp = platform.get("/restapi/v1.0/account/~/extension/~/call-log") return resp.response()._content elif api == "account-call-log": resp = platform.get("/restapi/v1.0/account/~/call-log") return resp.response()._content else: return render(request, 'sync/test.html') And sync/test.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <b><a href="/logout">Logout</a></b> <h2>Call APIs</h2> <ul> <li><a href="/test?api=extension">Read Extension Info</a></li> <li><a href="/test?api=extension-call-log">Read Extension Call Log</a></li> <li><a href="/test?api=account-call-log">Read Account Call Log</a></li> </ul> </body> </html> Has anyone setup a Django authorization flow for RingCentral and can show me where this is breaking? -
Transform function view in Class Based View in Django
I have an archive page with a form that has 2 select option inputs with year and months and I want to select from the database the objects that were created at the year and month selected from the page, I have this function view that works fine but I need the CBV version, I tried with View but it's not working, please a little of help. def archive(request): if request.method == 'POST': year = datetime.strptime(request.POST.get('year'), '%Y') month = datetime.strptime(request.POST.get('month'), '%m') incomes = Income.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) spendings = Spending.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) else: incomes = Income.objects.filter(user=request.user) spendings = Spending.objects.filter(user=request.user) year, month = False, False context = { 'title': 'Archive', 'spendings': spendings, 'incomes': incomes, 'currency': Profile.objects.get(user=request.user).currency, 'total_incomes': round(assembly(incomes), 2), 'total_spendings': round(assembly(spendings), 2), 'total_savings': round(assembly(incomes) - assembly(spendings), 2), 'year': year, 'month': month, } return render(request, 'users/archive.html', context) -
how can i fix django form validation error?
I created a login view and i have this user in database(email:john@gmail.com,password:123) when i filled out my form i got message error means this user wasn't exist, but i have this user in database. what do i do to fix it? my views.py: class User_Login(View): def get(self,request): form = UserLoginForm() return render(request,'login.html',{'form':form}) def post(self,request): form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,email=cd['email'],password=cd['password']) if user is not None: login(request,user) messages.success(request,'شما با موفقیت وارد شدید','success') return redirect('product:home') else: messages.error(request,'نام کاربری و یا رمز عبور اشتباه است','danger') return redirect('users:login') my forms.py: class UserLoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), label="ایمیل") password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),label='رمز عبور')