Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add_message() argument must be an HttpRequest object, not 'str'
I am currently working on a django website which translates a dna chain into a protein. Basically, you input a group of letters divisible by three and then it gets translated into a protein. This part of the code works perfectly. However, I am experiencing some troubles the messages. If you want to see the documentation of django messages, here it is: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/. What I want to do is: when you input a group of letters which isn't divisible by three, it should raise a message with the level or error (message.error). Here's the code: class TranslatorView(View): def translate_amino(self, codon): return self.amino_mapper.get(codon, "") def build_protein(self, request, phrase): protein = [] i = 0 while i < len(phrase): codon = phrase[i: i + 3] amino = self.translate_amino(codon) if amino: protein.append(amino) else: print(f"The codon {codon} is not in self.mapper_1") i += 3 if len(phrase) % 3: messages.error(request, 'DNA CHAIN INVALID') else: return protein However, when I run the code, this error gets raised: add_message() argument must be an HttpRequest object, not 'str'. I believe this comes from the if statement where i type the message.error. However, I don't know how to solve it. PS: If you need the calling methods, don't hesitate … -
Converting Python Script to Web Tool
I am going to make a simple website that displays data from a script I made with Beautiful Soup. I already have a working Python code that scrapes the data I need. What I do not know how to do is drop this Python code into a website that scrapes data on a daily basis and displays it nicely. I am scraping daily stock prices and I want my site to store each day's price in a database and plot everything to date on a simple line graph and an accompanying table. What keywords do I use in researching this? I've started to look into Django and Javascript. Am I on the right path? -
Django how to create errors while adding new objects
See first the code. models.py class Schauspieler(models.Model): schauspieler = models.CharField(max_length=100) def __str__(self): return self.schauspieler admin.py class SchauspielerAdmin(admin.ModelAdmin): ordering = ('schauspieler',) admin.site.register(Schauspieler, SchauspielerAdmin) localhost schauspieler tables You can see i have there 2 time the name Alexander Ludwig. This is a list of actors in the admin. Because the names of the actors are too much, I do not remember which ones i have created and which ones not. If the name exists than should come a error while adding. How can i do this? -
Django DRF: custom Permission: tokenauthentication: Why to use isAuthenticated for permission
I have the following REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } How does DRF get the request.user def hello_world(request): print(request.user) return Response() I am trying curl --location --request GET "http://127.0.0.1:8000/hello-world/" \ --header "Authorization:Token ssssss28acbd550a9806c6ac9ce13f1bbc73137" \ --header 'Content-Type: application/json' so in the output i see the request.user is printed as per the token supplied i.e eg: test Then what is the use of using isAuthenticated It only checks whether Authentication header is provided or not Why cant that be checked by tokenauthentication itself -
Django Formset: Is there any chance to add missing field content in the post() method of a CreateView?
I've created a CreateView with a modelformset, added some js to add or remove additional forms. It is a view to create a booking from a bank booking entry. And as the 'from_account' is obvious (the booking is launched from a certain bank booking entry and handing over the pk from the bank booking in the url), I do not want to show this (selection-) field in the form. So I put the field as a hidden field in the formset with the objective to fill it in the post. All this works as expected until submit. Now, in the post() method, I see in formset.error correctly the errors for the missing fields 'bank_account_ta' and 'from_account'. Since I don't know the total_forms number (it might have been changed using js), I cannot prefill it while instantiating the formset class. Working around in the template with js is possible, but not the proper way... I would rather using the formset.clean() method but whatever I try, the formset.error remains as before which leads to not formset.is_valid(). My questions: What is the easiest way to complete data (cleaned_data) of a formset in post()? Another point which is still hurting me: Is it necessary … -
What is the best way to develop a database in a python script and use the database in another python script (Django app) at the same time?
I have a python script that does several analysis and develop and update a database on a regular basis non-stop. On the other hand, I am using a Django application to show the database online. What is your suggestion for the best way to shake hands between these two parts? I think of a simple text file or CSV file, but is there any better way to do this? -
Correct format to make POST requests using okhttp in Kotlin
I want to send some data from my android app to my Django backend. I have used the django-rest api framework. Suppose I want to post a JSON data with the format: {"code" : "TEST"}; So I tried this: val url = "http://myurl" val JSON: MediaType? = MediaType.parse("application/json; charset=utf-8") var body:RequestBody = RequestBody.create(JSON,"code TEST") val request = Request.Builder().post(body).url(url).build() val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { val body = response?.body()?.string() Log.d("got a response", "body") } override fun onFailure(call: Call, e: IOException) { Log.d("Failed", "FAILED") e.printStackTrace() } }) The post request reaches the endpoint. But, the moment I do anything with the request object; (such as parse it using json parser) I get a bad request error. Here is the code for the view function: @method_decorator(csrf_exempt, name='dispatch') @api_view(['GET','POST']) def DummyView(request): #print(request.POST['code']) this gives a bad request error. #print(request.POST) this gives a bad request error #data = JSONParser().parse(request) this gives a bad request error #x = DummySerializer(data=data) #------------ #Passing a dummy Response #------------ AllC = Assignment.objects.filter(course = "TR") ser = CourseSerializer(AllC,many = True) return Response(ser.data) The above code doesn't give any bad request errors, until any one of the commented lines is un-commented. This makes … -
Sending django celery task to beats worker
I am trying to create a scheduled task every 10 seconds. I've read the celery docs and applied the below, but this doesn't print anything to the beats worker console. @app.task def beat_test(): for tenant in get_tenant_model().objects.exclude(schema_name='public'): with tenant_context(tenant): print("testing celery beat") app.conf.beat_schedule = { "add-every-10": { "task": "tasks.some_beat", "schedule": 10.0, }, } In my beat worker console, all I see is the below: LocalTime -> 2020-12-04 14:14:00 Configuration -> . broker -> redis://redis:6379/1 . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2020-12-04 14:14:00,824: INFO/MainProcess] beat: Starting... Any help is appreciated. -
Redirect non super users to landing page/profile page if they try to access Django admin page
I am building a Django based website and I am facing an issue when trying to redirect users to profile/landing page if they are not super users. Only super user who is logged in should have access to admin page. Right now I am working on localhost. Logged In scenario: Non super users are still able to access http://127.0.0.1/admin and http://127.0.0.1/admin/login Not Logged In scenario: Not logged in users are still able to access http://127.0.0.1/admin/login Logged in but Non super user view when trying to access http://127.0.0.1/admin: Logged in but Non super user view when trying to access http://127.0.0.1/admin/login: Not logged in users when trying to access http://127.0.0.1/admin: Not logged in users when trying to access http://127.0.0.1/admin/login: My urls.py looks like: from imports * admin.autodiscover() admin.site.admin_view = admin_view admin.site.login = login_required(admin.site.login) admin.site.login = staff_member_required(admin.site.login, login_url=settings.LOGIN_URL) urlpatterns = [ path('', views.index, name ='index'), path('dummy', views.loggedin, name ='dummy'), url(r'^admin/login/', views.loggedin, name ='dummy'), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() What am I doing wrong here? -
Django ModelFormSet executes a single-object SELECT query per formset instance when validating (ORM inefficiency)
Conceptual summary of the issue: Let's say we have a Django app with Author and Book models, and use a BookFormSet to add / modify / delete books that belong to a given Author. The problem is when the BookFormSet is validated, ModelChoiceField.to_python() ends up calling self.queryset.get(id=123) which results in a single-object SELECT query for each book in the formset. That means if I want to update 15 books, Django performs 15 separate SELECT queries, which seems incredibly inefficient. (Our actual app is an editor that can update any number of objects in a single formset, e.g. 50+). Here are a few things I tried: First I tried passing a queryset to the BookFormSet, i.e. formset = BookFormSet(data=request.POST, queryset=Book.objects.filter(author=1)), but the ModelChoiceField still does its single-object SELECT queries. Then I tried to see where the ModelChoiceField defines its queryset, which seems to be in BaseModelFormSet.add_fields(). I tried initiating the ModelChoiceField with the same queryset that I passed to the formset, e.g. Book.objects.filter(author=1) instead of the original code which would be Book._default_manager.get_queryset(). But this doesn't help because the new queryset I defined isn't actually linked to what was passed to the formset (and we don't have a cache running). So the … -
How to create a model attribute based on another attribute?
I have a very simple Item model, when I create a new istance, let's say through the admin dashboard, I want my slug to be generated automatically based on the title attribute, for ex: if the title is "my item title" the slug should be "my-item-title". class Item(models.Model): title = models.CharField(max_length=100) @property def slug(self): slug = str(self.title).replace(' ', '-') return slug def get_absolute_url(self): return reverse('core:item_detail', kwargs={'slug': self.slug}) But slug is not a column in the db, so I cannot get an Item istance using the slug value, I have to query using the title attribute. # my view def detail_view(request, slug): item = get_object_or_404(Item, title=str(slug).replace('-', ' ')) context = {'item': item} return render(request, 'detail.html', context) # my urls path path('product/<slug>', detail_view, name='item_detail') My question is: is there a way to automatically generate a slug attribute based on title so I can query the db using slug? -
issue with passwords with special character (#) using read_default_file
I'm relatively new to Django and am looking to read my MySQL connection info from a file using the read_default_file process. I test this on Windows and it seems to work perfectly. I move to my linux pre-prod server and i get an issue access issue. Through countless hours of testing, i find that the issue seems to be with my password contains a special character # and it seems that this process is translating that to mean the start of a comment. I have no control over the password and need to be able to handle this character. on a side note, if i load the details directly into my django app (settings.py) then i have no issue and all is fine, but if i try to offload them into my conenction file, this situation arises. I have looked but cannot seem to find a way to escape the PW to handle this character (and arguably others). What am i missing and is there a way to handle passwords with special characters like my situation? Cheers! -
Django: ValueError: Prefetch querysets cannot use raw(), values(), and values_list()
I am trying to run prefetch as below and gives me error: Prefetch querysets cannot use raw(), values(), and values_list(). queryset = SymbolList.objects.prefetch_related( Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in=[1,2,3,4]).values('close','volume'))).all() DailyPriceHistory model has lot of columns, i only want close and volume Here id__in=[1,2,3,4] is just shown for example, it can go upto 10000+ ids at a time. -
How to work with an existing sql server database
I am starting my practices as a programmer, but I have a problem and that is that in the company where I am they gave me a test database that has 60 thousand data, I read the documentation where it says how to obtain the tables, I can do it, but at the moment of obtaining them these tables come with integer data in their foreign keys, is there any way to user the tables with the django orm, this my models: from django.db import models class TipoNovedad(models.Model): id_tnov = models.AutoField(db_column='Id_TNov', primary_key=True) # Field name made lowercase. nom_nov = models.CharField(db_column='Nom_Nov', max_length=100) # Field name made lowercase. desc_nov = models.CharField(db_column='Desc_Nov', max_length=250) # Field name made lowercase. manejo_tiempo = models.CharField(db_column='Manejo_Tiempo', max_length=20) # Field name made lowercase. dias = models.CharField(db_column='Dias', max_length=20, blank=True, null=True) # Field name made lowercase. estado = models.BooleanField(db_column='Estado') # Field name made lowercase. class Meta: db_table = 'Tipo_Novedad' class Novedades(models.Model): id_nov = models.AutoField(db_column='Id_Nov', primary_key=True) # Field name made lowercase. # is in the foreign key of the novelty model id_tnov = models.IntegerField(db_column='Id_TNov') # Field name made lowercase. n_identificacion = models.CharField(db_column='N_Identificacion', max_length=20) # Field name made lowercase. fec_registro = models.DateTimeField(db_column='Fec_Registro') # Field name made lowercase. fec_inicio = models.DateField(db_column='Fec_Inicio', blank=True, null=True) # … -
How to create charts in django
How to create a line chart that gives daily updates in django and js. i want to know the theory of creating a daily analysis line chart in django. That show the data of whole week, and it's max value each day. Like in any graph. -
Django -- Can I pass everything from several tables in one object?
I'm working on a website that will have different types of posts. I want to create a model for each. So I would have a table of Blog Posts, a table of Review Posts, a table of Vlog Posts, etc. On the home page, I want to pass in all of these, sorted by date an arbitrary date field. I'm aware that I can pass them in as several objects, each sorted from their own table, but that doesn't help me determine if a blog post is newer than a vlog post. Is there a way that I could say something like the following: allPosts = "SELECT * FROM BlogPosts, VlogPosts, ReviewPosts ORDER BY Date", then pass this from the view into the template? Or is there a way that I can create a table that contains all of these posts using Foreign Keys? The idea is that I want to display the newest post in a certain area, then display the rest in order. Thanks -
How to create FIle object from base64 to sent it Django
On client i have code url = 'http://127.0.0.1:8000/api/create_post/' headers = {'Authorization': 'Token c63ee5854eb60618b8940829d2f64295d6201a96'} image_string = None with open("21485.jpg", "rb") as image_file: image_string = base64.b64encode(image_file.read()) data ={ 'text':'new_post_python', 'image':image_string } requests.post(url, json=data,headers=headers) and i want to create some post with api on server i have code class CreatePostView(APIView): permission_classes = (IsAuthenticated,) def post(self,request,format=None): Post.objects.create( text=data.get('text'), author=request.user, image=..., ) return Response({'created': True}) Where from .models image = models.ImageField(upload_to='posts/', blank=True, null=True) How can i built image from base64 string on server side ? -
How to filter locations by custom area in django?
I’m to allow user to draw his custom area on frontend (flutter) and pass it to backend (django +postgis) which must return list of PointFields thats are lies inside the curve. So, in which format should I pass the curve to the backen and how do I properly filter the places queryset? -
Django media files are not showing up after IIS deployment
I am trying to deploy a webpage. My project is written in Django and I am trying to deploy it on Microsoft server using IIS. I have made static files to work successfully, however I could not do the same with media files. Can you please help? This is my IIS: This is file I used to configure static files, which I located under static folder: I tried to do the same thing with media config file in the media root folder, however it does not work: any help please? Thank you! -
Including a certain url in urls.py makes the wrong view function execute
My main application is called lpbsmain, and I have another app called dashboard. lpbsmain/urls.py includes path('main/', include('dashboard.urls')) in the urlpatterns variable. dashboard/urls.py looks like... from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ #path('', views.dashboard, name='dashboard'), path('<str:useremail>/', views.dashboard, name='main'), path('base_dash/', views.base_dashboard, name='baseDash') ] dashboard/views.py has two view functions, dashboard() and base_dashboard() import requests, json from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth import logout def base_dashboard(request): print("base dashboard view func print statement") return render(request, "base-main-dashboard.html") @login_required(login_url='/login') def dashboard(request, useremail): if request.user.is_authenticated: # removed code in this conditional because it's not relevant return render(request, "index.html", {'Past30Dates':json.dumps(past_30_dates), 'Past30Values':json.dumps(past_30_values), 'Past60Dates':json.dumps(past_60_dates), 'Past60Values':json.dumps(past_60_values), 'fullEmail':useremail, 'shortenedEmail':shortenedEmail}) else: redirect("login") The problem: So if you try to go to the url /main/base_dash, my intent is to see base-main-dashboard.html. Instead, I actually see index.html. From adding print statements, I see that whenever I go to the url /main/base_dash/, the view function dashboard(useremail) is actually being executed, not base_dashboard(). Normally, dashboard(useremail) gets executed from the url main/<useremail> as expected. But now it's also executing at that url and main/base_dash. The only way this stops is if I remove path('<str:useremail>/', views.dashboard, name='main'), from dashboard/urls.py. Then, if … -
at-rule or selector expectedcss(css-ruleorselectorexpected) on CSS code in Django on style tags[VS CODE]
<style> .button{ -moz-box-shadow: 0px 10px 14px -7px #276873; -webkit-box-shadow: 0px 10px 14px -7px #276873; box-shadow: 0px 10px 14px -7px #276873; background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #599bb3), color-stop(1, #408c99) ); background:-moz-linear-gradient( center top, #599bb3 5%, #408c99 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#599bb3', endColorstr='#408c99'); background-color:#599bb3; -webkit-border-top-left-radius:8px; -moz-border-radius-topleft:8px; border-top-left-radius:8px; -webkit-border-top-right-radius:8px; -moz-border-radius-topright:8px; border-top-right-radius:8px; -webkit-border-bottom-right-radius:8px; -moz-border-radius-bottomright:8px; border-bottom-right-radius:8px; -webkit-border-bottom-left-radius:8px; -moz-border-radius-bottomleft:8px; border-bottom-left-radius:8px; text-indent:0; display:inline-block; color:#ffffff; font-family:arial; font-size:15px; }</style> Tried including "html.validate.styles": true in my settings.json file but error still shows.I copied this code from a css generator online and edited the class name as shown. My <a> link looks like this <a class="button">href='{% url 'login' %}'</a> -
Filter query set using Django rest serializer
I have two serialiser and one of them is used in another. class CommentSerializers(ModelSerializer): class Meta: model = Comment fields = ['id','text', 'author','approved' , 'created_date'] read_only_fields = ['author' ,'approved' ,'created_date'] and then class PostSerializers(ModelSerializer): likes_count = serializers.SerializerMethodField(read_only=True) comments = CommentSerializers(source='comment_set', many=True, read_only=True) post_media = PostMediaSerializers(source='postmedia_set', many=True, required=False) class Meta: model = Post fields = [ 'id', 'text', 'likes_count', 'likes_count', 'post_media', 'author', 'approved', 'comments','created_date', ] read_only_fields = ['author', 'approved', 'comments','created_date',] As you see I get comments on a post and I nest it there so that every post comes with its comments. The challenge is getting is that I only wanted to show users approved posts. How can I filter the comments_set? -
NoReverseMatch at /Raccourcisseur/
Reverse for 'redirection' with arguments '('',)' not found. 1 pattern(s) tried['Raccourcisseur/Lien/(?P[^/]+)/$'] [About errors][1] #urls.py# from django.urls import path from . import views urlpatterns = [ path('', views.liste,name='liste'), path('nouveau/',views.afficher,name='afficher'), path('Lien/<str:code>/',views.redirection,name='redirection'), ] #urls.py(global)# from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('Raccourcisseur/',include('mini_url.urls')), ] #views.py# from django.shortcuts import render,redirect,get_object_or_404 from .models import MiniURL from .forms import MiniURLForm def afficher(request): if request.method == "POST": form = MiniURLForm(request.POST) if form.is_valid(): form.save() return redirect(liste) else: form = MiniURLForm() return render(request,'mini_url/index.html',{'form':form}) def liste(request): minis = MiniURL.objects.order_by('-acces') return render(request, 'mini_url/liste.html', locals()) def redirection(request,code): """ Redirection vers l'URL enregistrée """ mini = get_object_or_404(MiniURL, code=code) mini.acces += 1 mini.save() return redirect(mini.url, permanent=True) #index.html# {% extends 'mini_url/base.html' %} {% block title %} RaccourcisseurUrl {% endblock%} {% block body %} <h1>Raccourcir une URL </h1> <form method="post" action="{% url 'afficher' %}"> {% csrf_token %} {{form.as_p}} <input type="submit"/> </form> {% endblock %} #liste.html# {% extends 'mini_url/base.html' %} {% block title %} Page RaccourcisseurUrl {% endblock%} {% block body %} <h1>Le raccourcisseur d'URL spécial </h1> <p></p><a href="{% url 'afficher' %}">Raccourcir une url </a></p> <p>Liste des URLs raccourcies : </p> <ul> {% for mini in minis %} <li>{{ mini.url }} via <a href="http://{{ request.get_host }}{% url 'redirection' mini.code %}"> {{ request.get_host … -
Adding django celery beat using persistent scheduler
I am running a Django app that is not using django-celery-beats. At the moment I have setup a worker which starts the beats persistent scheduler. I've created the below in tasks.py: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 10 seconds. sender.add_periodic_task(3.0, test.s('hello'), name='add every 3') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print(arg) I can't see that this is working. Is there any other config I need to add. I can't use the database scheduler in my requirement so I cant use the celery beats package. Any guidance or instructions are appreciated. -
PrimaryKeyRelatedField or Nested Relationships in Django REST
My issue is I want to get this: output "counter": 1, "reference": { "ref": "a", "name": "apple", "description": "a fruit" }, "stock": 10, serializers.py with PrimaryKeyRelatedField class StockSerializer(serializers.ModelSerializer): counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) reference = serializers.PrimaryKeyRelatedField(queryset=Reference.objects.all()) class Meta: model = Stock fields = ['counter', 'reference', 'stock'] serializers.py with Nested Relationships class ReferenceSerializer(serializers.ModelSerializer): class Meta: model = Reference fields = ['ref', 'name', 'description'] class StockSerializer(serializers.ModelSerializer): counter = serializers.PrimaryKeyRelatedField(queryset=Counter.objects.all()) reference = ReferenceSerializer() class Meta: model = Stock depth = 2 fields = ['counter', 'reference', 'stock'] If I use PrimaryKeyRelatedField I have only the id but if I use Nested Relationships I have to fill all fields but it already exists I want to select among a list