Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django change Boolean after POST
I'm trying to clone linkr.ee just for learning django A page looks like this: Each user User has a page On this page one user can have multiple links A link can have a password field to unlock the link if a user setted the password to True/False I created the model here: class Field(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) url = models.CharField(max_length=255) creator_adress = models.GenericIPAddressField(null=True) password_secured = models.BooleanField(default=False) password = models.CharField(max_length=100, blank=True, null=True) So if password_secured is checked (True/False), the link will have the password field aswell. My Problem: I'm having issues with giving each link one the page the which is password secured a form. If one link has password_secured True (and password) -> Form needed for each link which has password -> if password correct (form valid) -> password_secured False -> link unlocked The Template: #here just a for loop to display every object of the specific user into the html template <a {% if i.password_secured == False %} href="{{i.url}}{% endif %}"></a> #for loop end Simple Template meaning: If password secured False -> put the href in the Link(Button) If password secured True -> Password form must be correct -> set … -
Placement input text no showing
When I add another CRSF Token, it will not show the placeholder texts. Without this second token. It will not allow for me to save the form. I do not know how to make this last placeholder visible again when adding the token. Any Help would be appreciated. If any other files are needed such as the views class. I can provide this however I believe its to do with something in the html document. <!DOCTYPE html> <html> <head> <title>Register</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <style> body, html { margin: 0; padding: 0; height: 100%; background: #7abecc !important; } .user_card { width: 350px; margin-top: auto; margin-bottom: auto; background: #74cfbf; position: relative; display: flex; justify-content: center; flex-direction: column; padding: 10px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -webkit-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); -moz-box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); border-radius: 5px; } .form_container { margin-top: 20px; } #form-title{ color: #fff; } .login_btn { width: 100%; background: #33ccff !important; color: white !important; } … -
can't install modified pafy version in heroku django
I made a django app with pafy (I used the modified version, because the official one gives errors check this https://github.com/mps-youtube/pafy/pull/305) and when I push it to heroku I get errors here's the requirements.txt file # asgiref @ file:///tmp/build/80754af9/asgiref_1625643473416/work beautifulsoup4==4.10.0 certifi==2021.10.8 dj-database-url==0.5.0 # Django @ file:///tmp/build/80754af9/django_1625585912945/work django-bootstrap-datepicker-plus==4.0.0 django-bootstrap4==21.2 django-heroku==0.3.1 Faker==11.3.0 gunicorn==20.1.0 # psycopg2 @ file:///tmp/build/80754af9/psycopg2_1612298595717/work python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 soupsieve==2.3.1 # sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work text-unidecode==1.3 # typing-extensions @ file:///tmp/build/80754af9/typing_extensions_1631814937681/work whitenoise==5.3.0 # pafy==0.5.5 # youtube_dl==2021.12.17 youtube-dl==2021.6.6 pafy -e git+git://github.com/Cupcakus/pafy.git@develop#egg=pafy I tried removing pafy, tried other versions but it doesn't solve it here's the log -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip Obtaining pafy from git+git://github.com/Cupcakus/pafy.git@develop#egg=pafy (from -r /tmp/build_9f9c42b0/requirements.txt (line 24)) Cloning git://github.com/Cupcakus/pafy.git (to revision develop) to /app/.heroku/src/pafy Running command git clone --filter=blob:none -q git://github.com/Cupcakus/pafy.git /app/.heroku/src/pafy Resolved git://github.com/Cupcakus/pafy.git to commit 45f0deb067bf7c420cdf83a0529fd5274c12de18 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] … -
Django stuck on Watching for file changes with StatReloader
So at first I tried opening up a site and it did work perfectly, then i modified the files to create an app and then after following a tutorial it got stuck on that message and the local host site went down, I've tried specifying the command to be on 8000 but it still would not open and i also tried opening up a new terminal but it was still stuck in that same message. Here are my files and terminal: terminal urls file Home html Lookup file views file -
Django media uploads to Amazon S3 and restricting access to certain users
I am creating a flutter application with Djano backend where users can create/join groups and upload files (pictures, videos etc) to the group. I set up AWS S3 storage to handle media file uploads. However, now I'm at a point where I want only members of a group in the app to be able to see those files/pictures and restrict access to those files/pictures where you are not a member of the group. right now My bucket settings is set to public and anyone that has a link to the URL can access/view that file in the browser. How would I implement if someone grabs a hold of that URL , they shouldn't be able to access the file by going to the link. essentially, some content like profile pictures can be public and anyone can access that but no one can just go to their browser and type in a URL for a certain file link and access it. How would I go about doing this? Are there any good tutorials that you can link me or documentation that discusses this? -
I cannot post data - Django
I am currently building a Django React app and I want the users to be able to create an instance of a model (listing) from the frontend. I was trying to build the backend, but when I try on Postman I get an error : "detail":"Method "POST" not allowed." My model : class Listing(models.Model): artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) slug = models.CharField(max_length=200, unique=True) title = models.CharField(max_length=150) photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', default='photos/default.jpg') description = models.TextField(blank=True) def __str__(self): return self.title My view : class CreateListingView(APIView): parser_classes = [MultiPartParser, FormParser] queryset = Listing.objects.all() serializer_class = ListingSerializer def post(self, request, format=None): print(request.data) serializer = ListingSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) else: return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) My app Urls : from django.urls import path from .views import ListingsView, ListingView, SearchView,CreateListingView app_name = 'listings' urlpatterns = [ path('', ListingsView.as_view(),name='listings'), path('search', SearchView.as_view(),name='listingssearc'), path('<slug>', ListingView.as_view(),name='listingsdetails'), path('create', CreateListingView.as_view(),name='listingscreate') ] My project urls : urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/accounts/', include('accounts.urls')), path('api/artists/', include('artists.urls')), path('api/listings/', include('listings.urls', namespace='listings')), path('api/contact/', include('contact.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] So what did I do wrong? I don't understand why I get a 405 error. Thanks for reading! -
Cannot assign "<django.contrib.auth.models.AnonymousUser object:
I've been trying to write a test using the following code: class ViewTestCase(TestCase): def setUp(self): self.user = User.objects.create_user(first_name='tester', username='test1', password='123', email='testuser@something.com') def test_room_creation(self): c = Client() payload = {"titlePlanning": "Teste1","styleCards": "Fibonnaci","deck": ["1","2","3"]} c.login(username='test1',password='123') request = c.post('/room', payload, content_type='application/json') response = BeginRoom.as_view()(request) self.assertEqual(response.status_code, 200) print(request) the view that I'm testing needs the following data: class BeginRoom(APIView): permissions_classes = (IsAuthenticated,) def post(self, request, format=None): data= self.request.data user = request.user name = data['titlePlanning'].strip() styleCards = data['styleCards'] cards = data['deck'] This is the Model that the view access to do the POST: class PokerRoom(models.Model): status = models.CharField(max_length=1,choices=STATUS, verbose_name=_('status') name = models.CharField(max_length=200,verbose_name=_('name of the room')) styleCards = MultiSelectField(choices=CHOICES, default=FIBONACCI) user = models.ForeignKey(User, on_delete=DO_NOTHING) deck = models.ForeignKey(Pack, on_delete=models.CASCADE) active_story = models.OneToOneField('Story', on_delete=models.SET_NULL,verbose_name=_('active_storys'), related_name='active_in', null=True) My problem is that whenever I run my test I get the following error: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fbfb77ca3d0>": "PokerRoom.user" must be a "User" instance. I thought that I only needed to login with my user and after that it would be instantiated but its not working. Can someone help me? -
How to get only the last month's records present in the database, using queryset django?
I need to get only the objects of the last month present in the DB. I don't mean the last 30 days or the last calendar month, but the most recent month recorded in the database... I've seen that django has the latest() function that returns the most recent object in the table based on in the given field(s), however I want it to return multiple objects based on the given month. revisoes = Revisao.objects.filter(apicultor__in=apicultores).order_by('-data_registro') This is the queryset I'm using, only it returns all revisions for a given beekeeper. I need it to return only revisions based on the last month of the "data_registro" field -
Slugify and PIL images not working simultaneously inside Django Model Save method
models.py def rand_slug(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6)) class Product(models.Model): """ The Product table contining all product items. """ title = models.CharField( verbose_name=("title"), help_text=("Required"), max_length=255, ) image = models.ImageField( verbose_name=("image"), help_text=("Upload a product image"), upload_to="rental_equipments", default="default-equipment.jpg", ) description = models.TextField(verbose_name=("description"), help_text=("Add a detailed description"), blank=True) model = models.CharField(verbose_name=("Model"), max_length=25,null=True) serial_number = models.CharField(verbose_name=("Serial Number"),null=True, max_length=25) warrenty = models.DateField(verbose_name=("Warrenty Upto"),null=True, max_length=25) is_active = models.BooleanField( verbose_name=("Post Publically"), help_text=("---Remove tick mark and save for later"), default=True, ) slug = models.SlugField(max_length=255,unique=True) created_at = models.DateTimeField(("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(("Updated at"), auto_now=True) posted_user = models.ForeignKey(User, related_name="posted_by", on_delete=models.CASCADE,blank=True, null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img=img.resize((640,480)) img.save(self.image.path) if not self.slug: self.slug = slugify(rand_slug() + "-" + self.title) in my Save method, when I use image-resize without slugify function, it works perfectly, similarly slugify without image resize also works fine.. why do both work at the same time? please help!! this problem haunting me for hours! -
taggit href doesn't show up class views django
I'm making a blog type of app and when I click on the username on a post, it shows me the posts created by that user. I'm trying to do the same thing about locations for example if "daniel" posted a post in Paris and "sean" posted a post in Paris as well when I click Paris on any of these people's posts I wanna see all the posts created in Paris. and I tried to do this with taggit in Django, only the location part. when i search from the browser like http://127.0.0.1:8000/tag/paris/ i do get those posts i just cant make it like a link in the post like username, instead it just says no tags. overexplained but anyways lol. I'll try to put only the relevant parts. from django.urls import path from .import views from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, TagIndexView url patterns = [ path('user/<str:username>', UserPostListView.as_view(), name="user-posts"), path('tag/<slug:slug>/', TagIndexView.as_view(), name='tagged'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.db import transaction from django.db.models import F, Max from taggit.managers import TaggableManager class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author … -
HTML form , not responsive while inside a div
I'm creating a web page and if i put my div inside a form it makes it non-responsive but if i put that same form outside the div, everything works just fine. I wanted to have a div called container-2 and 2 forms inside, one is on the left as you can see and the other one is a card payment method. If i try to resize my screen, the second form goes under the first one because i've set the flex-wrap:wrap; but the first form stays non-responsive. Here is the code and thanks in advance. <div class="container-2"> <form method="POST">- <div class="item" id="payment"> <div class="row"> <h4>Možnost nakupa 1: Plačilo po povzetju <small><i>(Za plačevanje s kartico je treba izbrati samo količino in vrsto izdelka!)</i></small></h4> {% csrf_token %} {% if form %} <div class="input-group"> <div style="color: red;">{{ form.name.errors }}</div> {{ form.name }} </div> <div class="input-group"> <div style="color: red;">{{ form.last_name.errors }}</div> {{ form.last_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.street_name.errors }}</div> {{ form.street_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.city_name.errors }}</div> {{ form.city_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.email.errors }}</div> {{ form.email }} </div> <div class="input-group"> <div style="color: red;">{{ form.number.errors }}</div> {{ form.number }} </div> {% endif %} </div> … -
Django: tie two redirects to a single Update button depending on where the user came from
So, i have a rather usual "update item" page that is a class-based view which inherits UpdateView. (in views.py it looks like "class ItemUpdateView(UpdateView) and it has method get_success_url(self) defined which contains the redirect url where user will be taken after clicking "Update" button. My problem is that in my application, there are two different pages that could lead me to this "Update item" page, and depending on the page that user comes from - i want to take the user back to either pageA or pageB upon the successful update of the item. I wasn't able to find the best-practices of how to handle this anywhere on the web, so - would really appreciate the help. My guess is that I need to create an additional parameter that will be a part of the url and will contain A or B depending on the pageA or pageB that user came from, i.e. the url itself would be something like '/itemUpdate/int:pk/sourcepage' => '/itemUpdate/45/A'. Does that sound like a correct aproach or is there a better way? -
Django migrate won't work due to Postgres InsufficientPrivilege error provisioned by terraform and helm
We're are hitting a issue with our Django app and are unable to find the underlying problem. Our Django app runs on Kubernetes and is managed by Helm. When we upgrade the app, a Helm upgrade job is triggered that makes sure that a manage.py migrate is run. The migrate job runs with database admin privileges, not the customers postgres role. The error we're getting is: InsufficientPrivilege: permission denied for table RouteInstance This error must have something to do with creating a reference from a new table to a existing table, but we can't find it. Maybe it's in the Terraform resources config, or are the grants not sufficient. We don't use any extra grants since the admin account should be a real admin (Digitalocean doadmin). Any help would be awesome, we're stuck at the moment. Some context on our app deployment: The Helm template is being deployed by Terraform, the application deployment consists of: Create a subdomain record Create a namespace Create S3 buckets and a account Deploy the Helm chart (helm_release), here we use a values list with a templatefile. Between these values there are variables: postgres_user_username (used to run the app) postgres_user_password postgres_admin_username (used to perform the … -
How to prechoose an option in django form
I made a project in Django, on one page I have a list of buses with a button for each. I would like these buttons to lead to another page with ride cost calcutor, but there is one catch. One of the option in this form is a bus type, so I would like the button to lead to the form but with already chosen proper option. So if i push the button next to Volvo bus it will take me to the form and Volvo option will be chosen, if I push the button next to Setra it will be chosen in the form and so on. I tried giving every option unique id, and then in a tag href="{% url 'base_app:calc' %}#Volvo" but it only shows me the form, without choosing option. How should I go about it? -
DRF: Full Example of ListSerializer like Django's Admin-Inline?
I'm trying to wrap my mind around DRF's ListSerializer in combination with a foreignkey-model. The aim is to have something similar to Django's admin-inline Formula. Unfortunately, I can not find a full example on the documentation or SO examples: two models, two serializers and a viewset. Suppose we have a model bit like in the SO example DRF ListSerializer and ListField : class Musician(models.Model): name = models.CharField(max_length=50) comment = models.TextField(blank=True) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) So I try to put them in serializers like that: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = 'artist', 'title' model = Album class MusicianSerializer(serializers.ModelSerializer): class Meta: fields = 'name', 'comment', 'albums' model = Musician albums = serializers.ListSerializer(child=AlbumSerializer(), source='album_set') And then I want to build a ModelViewSet on it, so that I can work with it, just like in Django-Admin-Inline. But this is not working just like that: class MusicianViewSet(viewsets.ModelViewSet): queryset = Musician.objects.all() serializer_class = MusicianSerializer But it's difficult to test, the HTML front-end does work, and in the tests I got (in a slightly different situation) an error message something like: {'album_set': [ErrorDetail(string='This field is required.', code='required')]} which I could not understand, not even after digging hours in the source code. So … -
Fusioncharts touch scrolling on mobile
I'm actually working on a project where I use Django as Web framework to build an App which use Fusioncharts for charting ! Here is my issue, I found it very difficult to navigate througt the app when i'm using it a mobile devices as chart capture gesture from the finger, and it stop the scroll.. Does someone have any ideas on how to prevent this behaviour ? I did not find something on internet already ! Thank you ! -
Nested Values Json and Python
I have a JSON output im getting from an API and im trying to extract the nested values from 'rows' and to access 'cells' key within rows. Here is the JSON output "rows": [ { "id": 6770063759566724, "rowNumber": 1, "expanded": true, "createdAt": "2022-01-27T17:04:11Z", "modifiedAt": "2022-01-27T17:04:11Z", "cells": [ { "columnId": 2775064444725124, "value": "Smith", "displayValue": "Smith" }, { "columnId": 7278664072095620, "value": "John", "displayValue": "John" }, { "columnId": 1649164537882500, "value": 12.0, "displayValue": "12" }, { "columnId": 6152764165252996, "value": "Gilbert", "displayValue": "Gilbert" }, { "columnId": 3900964351567748, "value": "Webhook Test", "displayValue": "Webhook Test" } ] }, Here is my code I need each columnID within cells and the value within cells. These values will then be recorded into my Django project. Appreciate the help. This is the output of of print(cells) {6770063759566724: [{'columnId': 2775064444725124, 'value': 'Smith', 'displayValue': 'Smith'}, {'columnId': 7278664072095620, 'value': 'John', 'displayValue': 'John'}, {'columnId': 1649164537882500, 'value': 12.0, 'displayValue': '12'}, {'columnId': 6152764165252996, 'value': 'Gilbert', 'displayValue': 'Gilbert'}, {'columnId': 3900964351567748, 'value': 'Webhook Test', 'displayValue': 'Webhook Test'}]} for r in response_info ['rows']: try: row_id = r['id'] rowNumber = r['rowNumber'] if SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id): print("Updating Sheet rows") print('<--Row ID-->%s' %row_id) print('<--Row Number-->%s' %rowNumber) SmartSheetData.objects.filter(sheet_id = sheet, row_id = row_id).update(row_number = rowNumber) # GETS CELL VALUES print('Getting … -
Modifying the root folder only for one view or specific template (django, jquery, html)
I am trying to figure it out for several days, I am running out of time. I would need to make this works without changing the "<a href='/about'>About Text</a>" part (please, see code below). Basically, once the content is parsed, the link will reference to https://www.myhost.com/about, I would need to change that to https://www.myhost.com/something_more/about. I can not change the site root, I would to do it inside this specific view, the HTML template, or the jquery used (if there is a way to do it). I tried different things but without success. This is the code of the template: <div id="contents"></div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function () { var iframe = document.createElement("iframe"); $('#contents').append(iframe); iframe.contentWindow.document.open(); iframe.contentWindow.document.write("<a href='/about'>About Text</a>"); iframe.contentWindow.document.close(); }); </script> This is the view: def this_view(request): return render(request, 'my_app/this_view.html') Thank you, I appreciate any help. -
Django + Ajax: why does it redirect to a new URL and renders the response on browser?
Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong? My Django code looks like this: views.py: def projects(request): if request.method == 'POST': task_id = request.POST.get('task_id') myUser = User.objects.get(pk=request.user.id) myTask = Task.objects.get(pk = task_id) myTask.claimed.add(myUser) #add the user to the task return JsonResponse({'status': 'ok'}) projects = Project.objects.all() tasks = Task.objects.all() open_tasks = tasks.filter(status='Created') proj_dict = {} context = { 'projects' : projects, 'tasks' : tasks, 'open_tasks' : open_tasks, } return render(request, 'projects/projects.html', context) My HTML: <form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'> {% csrf_token %} <input type="hidden" name="task_id" value={{task.id}}> <button type="submit" class=" claim-font claim-button"> Join </button> </form> Tha ajax call: <script> $(document).ready(function () { $('#join-form').on('submit', function (e) { e.preventDefault(); e.stopPropagation(); const url = $(this).attr('action'); console.log("here we are"); const task_id = $(this).attr('id'); $.ajax({ type: 'POST', dataType: "json", headers: { 'X-CSRFToken': csrftoken }, url: url, data: { csrfmiddlewaretoken: '{{ csrf_token }}', task_id: task_id, }, success: function (response) { alert(data); console.log("here we are"); }, error: function (response) { console.log('error', response); alert("shit") } }) return false; }); … -
django Admin site wrong foreign key values
I have 2 models listing and profile defined as below. Owner and location both are supposed to be taken from Profile. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True, unique=True) class Listing(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) location = models.ForeignKey(Profile, blank=True, null=True, on_delete=models.CASCADE, related_name='rel_location') However, Whenever I am trying to create a new listing record, the location field only displays values from Owner column. How do I efficiently reference both columns add listing -
BrowsableAPI not working with functional views
How do I make BrowsableAPI work with functional views? For example, let's say I have @api_view(['GET', 'POST']) @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) When I register in the url and acces it, the browser gives me the raw json, not the browsableapi version of it. How can I make it work? I looked up the documentation and posts but couldnt find anything, everyone is either using classes based or generics. I know this way of making views is not ideal, but I still want to know how to make a functional view "Browsable". -
Django: Set many-to-many value to a model
I am trying to test my Models Project, Category and Tag. I'm running into an issue when trying to add tags to my project model. It won't allow me to do it in the Project model itself for eg. self.project = Project.objects.create( ... tags=Tag.objects.create("HTML5"), ) Django docs suggest the I do it as below. However I can't "add" the Tag without saving the model and I can't save the model without adding the Tag Tests class ProjectTests(TestCase): def setUp(self): self.tag = Tag.objects.create(name="HTML5") self.project = Project( title="Oaks on Main Shopping Center", url="www.oaksonmain.co.za", image=SimpleUploadedFile( name="test-image.jpg", content=open( "static\\images\\test_images\\florian-olivo-4hbJ-eymZ1o-unsplash (1).jpg", "rb" ).read(), content_type="image/jpeg", ), description="Beautiful website created for Oaks on Main Shopping Center in Knysna!", category=Category.objects.create(name="Website"), ) self.project.save() <- Problem here self.project.tags.add(self.tag) <- Problem here def test_project_model(self): self.assertEqual(f"{self.project.title}", "Oaks on Main Shopping Center") self.assertEqual(f"{self.project.url}", "www.oaksonmain.co.za") self.assertEqual( f"{self.project.description}", "Beautiful website created for Oaks on Main Shopping Center in Knysna!", ) self.assertEqual(self.tags.count(), 3) self.assertEqual(self.category.count(), 1) self.assertEqual(self.image.count(), 1) def test_project_listview(self): resp = self.client.get(reverse("index")) self.assertEqual(resp.status_code, 200) self.assertContains(resp, self.project.title) self.assertTemplateUsed(resp, "page/index.html") Models class Project(models.Model): class Meta: ordering = ["-id"] # Always show latest projects first verbose_name_plural = "Projects" title = models.CharField(max_length=50) url = models.URLField() image = models.ImageField(upload_to=f"{title}/") description = models.TextField() category = models.ForeignKey("Category", on_delete=models.PROTECT, related_name="categories") tags = models.ManyToManyField("Tag", verbose_name="tags") … -
Why queryset.only() is ignored when using serializers?
Could you give me a hand with this issue please? I am using Django and REST Framework for my app. I want to retrieve distinct values of 1 column in a django model, for that I use a queryset with chained filters and a serializer with the option many=True. Here is my code: Specified queryset: queryset = CollectedCompaniesInfo.objects.all() queryset = queryset.only('branch').distinct('branch') Expected result: [{ "id": 16, "branch": "McDonald's" }, { "id": 80, "branch": "Wendy's" }] I am getting: [ { "id": 16, "branch": "McDonald's", "latitude": "35.94905003", "longitude": "-81.18771815", "state": "North Carolina", "address": "561 W Main Ave Taylorsville NC 28681 United States", "open_hours": "Mon-Sun 5 am - 11pm", "coordinate_x": 35.94905003, "coordinate_y": -81.18771815 }, { "id": 88, "branch": "Wendy's", "latitude": "35.24987478", "longitude": "-80.95769756", "state": "North Carolina", "address": "5501 Birmingham Pkwy Concourse A Charlotte NC 28208 United States", "open_hours": "Sun - Thu 6:30am -2am/Fri-Sat 6:30am -3am", "coordinate_x": 35.249874778495084, "coordinate_y": -80.95769756353488 }] Serializer code: serializer = CollectedCompaniesInfoModelSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
radio buttons with simple input
dear stackoverflow! Professionals, please help. i need to implement a form like this in Django: If a user enters something in the "another amount" field, the radio buttons become disabled. I really have no idea. my html: <div class="payment__amount"> <div class="payment__amount__1"> <div class="form-check payment__amount__check"> {{ form.amount_select.0 }} </div> <div class="form-check payment__amount__check"> {{ form.amount_select.1 }} </div> </div> <div class="payment__amount__2"> <div class="form-check payment__amount__check"> {{ form.amount_select.2 }} </div> <div class="form-check payment__amount__check"> {{ form.amount_select.3 }} </div> </div> </div> {{ form.amount_input }} my forms.py CHOISES = [ ('50', '50'), ('100', '100'), ('200', '200'), ('500', '500') ] class CheckoutForm(forms.Form): amount_select = forms.IntegerField(widget=forms.RadioSelect(choices=CHOISES)) amount_input = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': "another amount"})) Thank you very much! -
read from database and display as dictionary, not list
I've got a simple database with this table structure: ---------------- | A1 | A2 | A3 | |--------------| | B1 | B2 | B3 | | C1 | C2 | C3 | ---------------- Using this function and djangorestframwork: @api_view(['GET']) def read(request, source): if source not in sources: return Response({'error': f'{source} not found', 'allowed sources': sources, 'help': address}) with connect(f'{source}/news.db') as conn: cmd = '''SELECT * FROM newstable''' cur = conn.execute(cmd) results = cur.fetchall() rand_id = randrange(len(results)) return Response(results[rand_id]) the contant is displayed in json like this: [ 'B1', 'B2', 'B3 ] However, I want to get this: { 'A1': 'B1', 'A2': 'B2', 'A3': 'B3 }