Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how customize is_valid to accept empty chars
I try to sign_up User, and I want get possibility to name User with empty chars example "Mr Somebody" but method is_valid not pass my form. How can I modify method is_valid to take empty chars in User name? def sign_up(request): context = {} form = UserCreationForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'accounts/index.html') context['form'] = form return render(request,'registration/sign_up.html', context) -
F() expressions and select_for_update() in Django
When it comes to avoiding race conditions in Django, can F() expressions and select_for_update() be used interchangeably? -
How to access a MySQL server hosted on a Virtual Machine using another Virtual Machine?
I have created 2 Ubuntu 20.04 VMs using VirtualBox. I have a Django App on one VM and MySQL DB on the other VM. How do I access the MySQL DB using the first VM? I used the inet from the output of ifconfig for the IP Address What I tried: On the VM having MySQL DB: -> Change the 'bind_adress' field to '0.0.0.0' in '/etc/mysql/mysql.conf.d/mysqld.cnf' -> Created a new user using "CREATE USER 'test'@'IP_Address1' IDENTIFIED BY 'password';" -> Ran "sudo ufw allow from IP_Address1 to any port 3306" On the VM having the Django App: -> Tried to connect to the Virtual Machine using "mysql -u 'test' -h 'IP_ADDRESS2' -p" The error I'm getting: "Unknown MySQL host 'address'" -
Django3.1 error when I try to save post with tags
I have a view inside posts app where I try to save a post with tags. Whenever I add a new tag to the post, I get this error: value error at create My view is this one: class PostCreateView(CreateView): template_name = 'posts/create.html' form_class = PostCreationForm model = Post def get_success_url(self): return reverse('posts:detail', kwargs={"slug": self.object.slug}) def form_valid(self, form): form.instance.user = self.request.user form.save() # this is where the error occurs tags = self.request.POST.get("tag").split(",") for tag in tags: current_tag = Tag.objects.filter(slug=slugify(tag)) if current_tag.count() < 1: create_tag = Tag.objects.create(title=tag) form.instance.tag.add(create_tag) else: existed_tag = Tag.objects.get(slug=slugify(tag)) form.instance.tag.add(existed_tag) return super(PostCreateView, self).form_valid(form) The form I'm using is as follow: class PostCreationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PostCreationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "post" self.helper.field_class = 'form-group' self.helper.layout = Layout( Field('title', css_class="form-control", placeholder='Post title'), Field('content', css_class="form-control", placeholder='Post content'), Field('category', css_class="form-control"), Field('image', css_class="form-control"), Field('tag', css_class="form-control", placeholder='tag1, tag2') ) self.helper.add_input(Submit('submit', 'Create New Post', css_class='btn btn-underline-primary')) tag = forms.CharField() class Meta: model = Post fields = ['title', 'content', 'category', 'image', 'tag'] This is the Post model: class Post(models.Model): title = models.CharField(max_length=150, unique=True) content = RichTextUploadingField() # content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(blank=True, null=True, upload_to='uploads/') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(default="slug", editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1, … -
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 …