Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
404 Not Found with nginx/apache2/django for static files on ubuntu
I'm setting up a Django project to run on apache web server (ubuntu) on port 80, which is working fine. To serve static content, I have set up nginx as a reverse proxy server operating on port 81. However, I keep getting 404 errors (from nginx) when trying to access the static content. My configurations are as follows. nginx: server { listen 81; listen [::]:81; server_name <my server's IPv4 address>; location ^~ /static/ { root /root/project-dir; proxy_pass http://localhost:80; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } apache (relevant part): <VirtualHost *:80> Alias /static/ /root/project-dir/static/ ProxyPass /static http://localhost:81/ ProxyPassReverse /static http://localhost:81/ </VirtualHost> Django settings.py (relevant part): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.normpath(os.path.join(BASE_DIR, 'myapp/static')), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") I also noticed that if I adjust my nginx configuration to: server { listen 81; listen [::]:81; server_name <my server's IPv4 address>; location ^~ /static/ { root /root/project-dir; } } then I am able to access the static content through my browser at <my server's IPv4 address>:81/static/path/to/content.jpg. However the static content doesn't load in my Django templates (using {% static <name> %}). My directory structure is: root - project-dir --- static <static root> ----- <collected static content here> --- … -
comparing two JSON API responses requested by two different users. Spotify API
The goal is to create a platform where two users can request Spotify data then responses are compared. I already have one piece of the puzzle solved, ie. for a single user, to access their spotify data, implemented the OAuth flow and all. The logic for comparison, I havent really looked at that piece yet. Firstly, was wondering how I'd be able to access one endpoint for a response{which I have already implemented), save that response and use the same endpoint for another user, and perform logic comparison of both responses. I was thinking about using sessions but I got lost. This is what I have so far. urls.py urlpatterns = [ path("", views.home, name="home"), path("login/" , views.login , name="login"), path("authorize/", views.callback, name="redirect"), path("liked/" , views.liked, name="liked"), ] views.py def login(request): authorize_url = oauth.get_authorize_url() return redirect(authorize_url) def callback(request): code = request.GET.get("code") if code is not None: token = oauth.get_cached_token()["access_token"] request.session["token"] = token return redirect(reverse("liked")) else: return redirect(reverse("login")) def liked(request): sp= Spotify(auth=request.session.get("token")) results = [] iter = 0 while True: offset = iter * 50 iter += 1 curGroup = sp.current_user_saved_tracks(limit=50, offset=offset)['items'] #yet to complete logic for display def home(request): template_name="display.html" return render(request, template_name) display.html <a href="{% url 'login' %}">LOGIN</a> -
Testing exception handling with Django models
I have a model named MyModel. I want to get an instance of the model from the database. If it's not there, get throws an exception, which I plan to catch, and then create a new instance to push into the database. Here's an example piece of code: 1: try: 2: my_model = MyModel.objects.get(keyval=something) 3: except MyModel.DoesNotExist: 4: my_model = MyModel(keyval=something, moar=data) 5: my_model.save() 6: do_something_with(my_model) I'm writing unit tests, and I don't want this function to ever hit the database (I'm not testing the database, I'm testing the function). I would expect this to work, but it doesn't: mock_myob = Mock() with patch('mymodule.models') as mock_models: mock_models.MyModel.objects.get.side_effect = mock_models.DoesNotExist() mock_models.MyModel.return_value = mock_myob with patch('django.utils.timezone.now', return_value=testdate2): testee = testfunc(something, data) mock_myob.save.assert_called_with(something, data) Unfortunately, when it hits line 2, above, it tells me "TypeError: 'Mock' object is not iterable" I couldn't possibly be the first person to run into this. What am I doing wrong? -
Django in digitalocean
With django running on digital ocean, how could i download a file that is on amazon web services and then manipulated. Is there a / temp folder or something, which frees that access for manipulation? -
why its showing empty path didnt match any of these
Using the URLconf defined in My_Ecom_Project.urls, Django tried these URL patterns, in this order: admin/ account/ ^static/(?P.)$ ^media/(?P.)$ The empty path didn't match any of these. -
Django: jQuery to trigger a form submit onchange of checkbox and retain the values on the reload
When one or more of the checkboxes in hostform are checked, I want to trigger a form submit. This is triggered successfully with the code below. However, the page reloads on the form submit, making any box that is checked go immediately back to being unchecked. I thought the localStorage.input line would fix this, but apparently not. Any suggestions? HTML: <div class="container-lg"> <!-- section for checkboxes --> <div class="row justify-content-center"> <div class="col-6"> <h2>Host</h2> <form id="hostform" class="form-inline" role="form" action="" method="post"> {% csrf_token %} <input type="checkbox" class="form-control" id="one" name="hm" value="one" onchange="triggerPost('one')"> <label for="one">One</label> <br> <input type="checkbox" class="form-control" id="two" name="hm" value="two" onchange="triggerPost('two')"> <label for="two">Two</label> <br> </form> </div> .... </div> jQuery: <script> function triggerPost(idnum) { $('#hostform').on("submit", function () { localStorage.input = $("#"+idnum).checked; }); $('#hostform').submit() }; </script> -
django DRF: custom permission class: function based views: how to pass or access some params from view
I have from rest_framework import permissions class CheckPermission(permissions.BasePermission): def has_permission(self, request, view): # access the allow parameter from view # if request.user.subscription type matches the value in allow array i.e [0,1,2,3] # then ok @api_view(['GET']) @permission_classes([CheckPermission]) def hello_world(request): allow=[0,1,2,3] print(request.user) return HttpResponse( JSONRenderer().render({"message": "Hello, world!"}), status=200, content_type="application/json" ) @api_view(['GET']) @permission_classes([CheckPermission]) def hello_world2(request): allow=[0,3] print(request.user) return HttpResponse( JSONRenderer().render({"message": "Hello, world2!"}), status=200, content_type="application/json" ) Here i am using a custom permission class. It will check if the request.user.subscription value matches any in the allow array values I saw in class based views we can access params using getattr(view, "allow", []), but in function based view its not working, In class based views i found this answer which does that. https://stackoverflow.com/a/19429199/2897115 -
How to update in ModelViewSet, Django Rest Framework
It is possible to update in ModelViewSet? I want to do an update in the ModelViewSet, not in the Serializer MySerializer in serializers.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' # I know the update will do here def update(self, instance, validated_data): pass MyViewSet in views.py class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer # I would like to do the update here, # because before updating I will do more things def update(self, request, *args, **kwargs): # Before updating, do something ... ... return Response(response) Any idea or suggestion? -
Django anonymous user when I fetch data on mobile but on PC the user is authenticated
I have a view which in which I make an ajax request to so that I fetch some data. On PC the ajax request is successful, it returns some data. On mobile the ajax request returns me 302 redirect. This is because I have protected this view so that only logged in people will get this information. The code is below. document.addEventListener("DOMContentLoaded", function() { //Make a request fetch(`${ACHIRONET_PROTOCOL}://${ACHIRONET_HOSTNAME}/sell/fetch-revenue-data/`) .then(response => response.json()) .then(data => { salesData = JSON.parse(data.data) console.log(salesData) }); }) The django view @login_required(login_url="/accounts/login") def get_revenue_data(request): context = {} sales = (request.user.sellerprofile.sales.all().order_by('created') .values('month', 'products_sold', 'sales')) sales_list = [revenue for revenue in sales] # Now serialize into json data = json.dumps(list(sales_list), cls=DecimalEncoder) context['data'] = data return JsonResponse(context) What could be causing the problem? -
Creating a view with primary key and distinct column values produces bizarre result
CREATE VIEW VBrand As select distinct (sBrand), idPartner from tblProduct: Produces this: +------------------------+-----------+ | sBrand | idPartner | +------------------------+-----------+ | PLANTERS | 45933 | | SARGENTO | 45933 | | TOTINOS | 45933 | | TRU MOO | 45933 | | VANITY FAIR | 45933 | | WOOLITE | 45933 | | YOPLAIT | 45933 | But CREATE VIEW VBrand As select distinct sBrand, id, idPartner from tblProduct; Produces this: +------------------------+----------+-----------+ | sBrand | id | idPartner | +------------------------+----------+-----------+ | NULL | 13774056 | 45933 | | PLANTERS | 13774362 | 45933 | | NULL | 13774430 | 45933 | | NULL | 13774764 | 45933 | | NULL | 13774768 | 45933 | .... The view is based on tblProduct: +------------------------+---------------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------------+---------------------+------+-----+-------------------+-----------------------------+ | id | bigint(20) unsigned | NO | PRI | NULL | auto_increment | | idPartner | int(10) unsigned | NO | MUL | NULL | | | sBrand | varchar(512) | YES | | NULL | | Why is "distinct COLUMN_NAME" returning a different result when I include the reference table primary key? I need a primary key because the API Resource expects … -
Reference ForeignKey in Django DetailView
I am struggling to reference my ForeignKey from a basic DetailView in Django. The models.py I am using: class Posts(models.model): url = models.URLField() class Comment(models.model): post = models.ForeignKey(Posts, related_name='comments', on_delete=models.CASCADE) content = models.CharField(max_length=500, blank=False) views.py: class PostDetailView(DetailView): model = Posts context_object_name = 'posts' I am trying to reference the comments in my posts detail page. posts_details.html: {% for comment in posts.comments.all %} {{comment.content}} {% endfor %} I have also tried changing posts.comments.all to posts.comments_set.all and still am getting no results. I feel like it is something small that I am missing, but I can't figure it out. The data is there, and it was input correctly with the foreign key reference, but I cannot reference it through the detail view. -
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) # …