Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reorganise a Django Model for django_tables2
I am trying to build a app that displays some subset of a database I have, however it is not exactly in the format I want to display. e.g. The current data (and model) is organsed as such: id value a1 3 a2 3 a3 4 b1 5 b2 4 b3 4 But I want to display it as: id a b 1 3 5 2 3 4 3 4 4 I can easily make this change if I switch to pandas dataframe but this issue suggests django_tables2 can't do this. Are there other options I can explore? Below are my models, tables, and views file. The columns in the example relate to Parameter_ID and Forms. models.py class Forms(models.Model): id = models.TextField(db_column='ID', blank=True, null=False, primary_key=True) # Field name made lowercase. local_id = models.IntegerField(db_column='Local_ID', blank=True, null=True) # Field name made lowercase. language_id = models.TextField(db_column='Language_ID', blank=True, null=True) # Field name made lowercase. parameter_id = models.TextField(db_column='Parameter_ID', blank=True, null=True) # Field name made lowercase. value = models.TextField(db_column='Value', blank=True, null=True) # Field name made lowercase. form = models.TextField(db_column='Form', blank=True, null=True) # Field name made lowercase. segments = models.IntegerField(db_column='Segments', blank=True, null=True) # Field name made lowercase. comment = models.TextField(db_column='Comment', blank=True, null=True) # Field name made lowercase. … -
How to Handle CSRFToken Authenticity with Django REST and React.js Relation?
I am creating a Django REST project. I created a custom user model in which I used rest-knox for token authentication. For the login and register user endpoints I used custom views where I authenticate the user's by their knox token. For password_change endpoint I used django auth's views. Here is the problem I am facing: When I try password_change endpoint in browsable API; it redirects me again to login page and does nothing. However Knox token for the user is created and returned in JSON. When I try the endpoint in Postman it gives CSRF token error since I cannot get the CSRF token. I tried to create my own front-end page for changing password and sometimes the 'csrftoken' was returned in cookie table of chrome but not all the time. Since I get the user token with JSON response I set it to cookies on React.js and reach anytime I want. Yet, get method of react-cookie doesn't work for csrftoken and it is being set as undefined. Finally I tried to use axios library for my post request and set default header for 'csrftoken' but couldn't see any results. The front-end 'localhost:3000/change_password/' page just redirects to itself by … -
Django 2.0 - fail to load in tests fixtures i made with dumpdata
Basically, it seems i have the same problem elaborated in this question here. However, in that question they did not elaborate about the solution.. only worte you need to change the encoding of the file which Django generates itself to UTF-8. However, as commented there, it's not solving the problem (i export the file in XML which is already in UTF-8 format). I have Mysql 5.7 db. On one of my tables i i have column with charset - 'utf8mb4'. My django project and db works fine. However, when i try to load fixtures i made with datadump on tests, i get this error msg: could not load web.Off(pk=672): (1366, "Incorrect string value: '\xC2\x96Lag ...' for column 'name' at row 1") my datadump statement: python3 manage.py dumpdata --format=xml -o web/fixtures/tests.xml my tests.py fixtures statement: class WebPagesTests(TestCase): fixtures = ['tests'] i tried changing the settings t allow 'utf8mb4' but it didn't worked: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', .... 'HOST': 'db', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, 'TEST_CHARSET': 'utf8mb4', } } It's worth mentioning that i getting no errors when i try to load this same fixture with loaddata command (not in tests.py): python3 manage.py loaddata -
Why is Web Deploy code python django rest framework
"detail": "JSON parse error - Expecting property name enclosed in double quotes: line 11 column 5 (char 300)" } -
How to implicitly assign value to DRF serializer read_only field?
Example code # models.py class Profile(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) ... class Photo(models.Model): image = models.ImageField(upload_to='photos') profile = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name='photos') ... # serializers.py class ProfileSerializer(serializers.ModelSerializer): photos = serializers.HyperlinkedRelatedField(many=True, view_name='photo-detail', read_only=True) class Meta: model = Profile fields = '__all__' class PhotoSerializer(serializers.ModelSerializer): # How to assign this implicitly from view? profile = PrimaryKeyRelatedField(read_only=True) class Meta: model = Face fields = '__all__' My solution # views.py class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer @action(methods=['GET', 'POST'], detail=True, serializer_class=FaceSerializer) def photos(self, request, *args, **kwargs): profile = self.get_object() if request.method == 'GET': ... elif request.method == 'POST': serializer = self.get_serializer(data=request.data) serializer.is_valid() # accessing validated_data # explicitly set profile read_only field serializer.validated_data['profile'] = profile self.perform_create(serializer) return Response(serializer.data) Example call curl -X POST http://localhost:8000/profiles/4/photos/ --form image=@photo_image.jpg Expected behavior HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 123, "profile": 4, "image": "http://localhost:9000/media/photos/photo_image.jpg", .... } When passing photo image to endpoint /profile/<int:pk>/photos/, Photo's (read_only=True) profile field have been set by extracted <int:pk> view parameter. Question Is there more elegant way to achieve this? I don't feel comfortable accessing serializer.validated_data and explicitly set profile value... -
problem when deploying vuejs app on heroku
I have a vuejs app that calling api from django website. I've already deployed django app on heroku successful but when I deploy vuejs and have access to my website. Something went wrong and when I looked at logs, some issues occur. Here is the logs 2020-04-19T14:49:31.711749+00:00 app[web.1]: sh: 1: vue-cli-service: not found 2020-04-19T14:49:31.716381+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2020-04-19T14:49:31.716381+00:00 app[web.1]: npm ERR! syscall spawn 2020-04-19T14:49:31.716382+00:00 app[web.1]: npm ERR! file sh 2020-04-19T14:49:31.716509+00:00 app[web.1]: npm ERR! errno ENOENT 2020-04-19T14:49:31.717484+00:00 app[web.1]: npm ERR! frontend@0.1.0 serve: `vue-cli-service serve` 2020-04-19T14:49:31.717565+00:00 app[web.1]: npm ERR! spawn ENOENT 2020-04-19T14:49:31.717683+00:00 app[web.1]: npm ERR! 2020-04-19T14:49:31.717772+00:00 app[web.1]: npm ERR! Failed at the frontend@0.1.0 serve script. 2020-04-19T14:49:31.717842+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above. 2020-04-19T14:49:31.725202+00:00 app[web.1]: 2020-04-19T14:49:31.725472+00:00 app[web.1]: npm ERR! A complete log of this run can be found in: 2020-04-19T14:49:31.725649+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-04-19T14_49_31_718Z-debug.log 2020-04-19T14:49:31.737139+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2020-04-19T14:49:31.737481+00:00 app[web.1]: npm ERR! errno 1 2020-04-19T14:49:31.739147+00:00 app[web.1]: npm ERR! frontend@0.1.0 start: `npm run serve` 2020-04-19T14:49:31.739368+00:00 app[web.1]: npm ERR! Exit status 1 2020-04-19T14:49:31.739629+00:00 app[web.1]: npm ERR! 2020-04-19T14:49:31.739829+00:00 app[web.1]: npm ERR! Failed at the frontend@0.1.0 start script. 2020-04-19T14:49:31.742569+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There … -
Easy way to encrypt model data in Django?
I am using mySQL database in my Django project and I want to make the .idb file that database creates to store data unreadable. I want that file to be unreadable. I don't need big and advance encryption, simple can work. Thank You. -
Django ManyToManyField is updated in admin but not through the CreateView (user side) form
I am trying to make a tag function for a post with ManyToManyField in django. If I add tags through admin, they are updated properly, but through the createview form, it is not updated. Below are the code of the related classes in model.py class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) picture = models.BinaryField(null=True, blank=True, editable=True) content_type = models.CharField(max_length=256, null=True, blank=True, help_text='The MIMEType of the file') text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #foreign key from django setting category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) tags = models.ManyToManyField(Tag, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return self.title And, CreateView class in view.py class PostCreateView(LoginRequiredMixin, View): template = 'cfis/post_form.html' success_url = reverse_lazy('cfis:all') def get(self, request, pk=None) : form = PostCreateForm() ctx = { 'form': form } return render(request, self.template, ctx) def post(self, request, pk=None) : form = PostCreateForm(request.POST, request.FILES or None) if not form.is_valid() : ctx = {'form' : form} return render(request, self.template, ctx) # Add owner to the model before saving pic = form.save(commit=False) pic.owner = self.request.user pic.save() return redirect(self.success_url) Lastyl, form class … -
Django display value text in formset
I wanna display the text value of a foreign key on the templante, in a way that the user cannot change it. Template: {% for form in formset %} <div class=""> {% for field in form %} {{ field }} {% endfor %} </div> {% endfor %} HTML render: <select name="form-0-semestre_solicitacao" id="id_form-0-semestre_solicitacao"> <option value="">---------</option> <option value="5">2020/1</option> <option value="4">2019/2</option> <option value="3" selected="">2019/1</option> <option value="2">2018/2</option <option value="1">2018/1</option> </select> I tried {{ field.initial }} and {{ field.value }} but it displays 3 and i would like it to display the text: 2019/1 -
Possible to create ArrayField for Django SQLite3 default DB?
I am working on my first Django project and right now I want the ability for the user to add multiple items to a model. It will look something like this in the admin panel. Expected Values [______________] + [______________] [______________] Each time they click the "+" it will open another line for them to add anything. From what I have came across so far is ArrayField is possibly what I want. However it seems that is not for the default Django DB SQLite3. I am trying to find a way to do what I want, while staying on SQLite3. Is it worth staying on SQLite3? Does switching to Postgres make what I want possible? Thanks -
How to override help_text and label for password form in django
I have the following form in my forms.py. For some reason the override of label and help_text for username field WORKS and (both) the password fields doesn't. class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] labels = { 'username': 'My Username Label', 'password1': 'My Password1 Label', 'password2': 'My Password2 Label', } help_texts = { 'username': 'My username help_text', 'password1': 'My password1 help_text', } When rendered the default django label/help_texts are showed for password fields: Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. ... I've already read those answers, but they weren't helpful: Q1 Q2 Q3 I've also read the docs, and there is a note here (green note lowering the page) that seems to be related, but I don't really understand it. It mentions Fields defined declaratively, which I'm not doing. Also wouldn't explain why it works for username and not for password1. -
AWS redis server config for django
I am following this tutorial and I am confused with the following code: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(<REDIS ELASTICACHE HOSTNAME>, 6379)], }, }, } here, what 'REDIS ELASTICACHE HOSTNAME' refers to? I created redis instance using AWS ElastiCache, I didn't find 'HOSTNAME' anywhere in the AWS console of redis instance. I tried to replace it with the name of the instance but after testing it in the shell, I was unable to send message over the layer. The error in testing the layers was: File "C:\Users\Nouman\AppData\Local\Programs\Python\Python37\lib\socket.py", line 748, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed Can any body help? -
unable to connect to localhost in creating a django blog
I have written the following code in my urls.py : from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/$', views.about), url(r'^$', views.homepage), ] and I created a views.py in my project folder and wrote the following code in it: from django.http import HttpResponse def homepage(request): return HttpResponse("homepage") def about(request): return HttpResponse('about') but when i use 127.0.0.1:800 for seeing my changes in browser i ocuured with unabling to connect and my internet connection does not have any problem what should I do? -
How do I use operators in Django {% if %} template tag?
so I'm trying to do simple calculation as my condition statement in {% if %}{% endif %} tag in Django. But somehow it doesn't work. Here's my code : {% for i in range %} {% if i/2 != 1 %} <!- Do something -> {% elif i/2 == 1 %} <!- Something else -> {% endif %} {% endfor %} I keep getting error that says "Could not parse the remainder: '/2' from 'i/2'" So there must be another way of using the operators in if statement, but I can't figure out what that is. I would very much appreciate your help! :) -
how to validate field already exist on form update
I add a validation on form.py to exclude the same record at the time of update so I check the username already exist or not, but self.instance.pk is getting None. I know there are also another way to do this but I want to know why self.instance.pk did not work, I will use this approach to other Forms also so I need to fix this using self.instance.pk here is my code so could you please review the code what is I am missing and why self.instance.pk not working. forms.py from django import forms from .models import CustomUser class UserForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = CustomUser fields = '__all__' exclude = ["is_admin", "is_verified", "last_login"] def clean_username(self): username = self.cleaned_data.get("username") print(self.instance.pk) user_obj = CustomUser.objects.exclude(pk=self.instance.pk).get(username=username) if user_obj: raise forms.ValidationError("username already exist") return username views.py def edit_profile(request): context = { "form": UserForm() } user_obj = request.user form = UserForm(instance=user_obj) context["form"] = form return render(request, "account/profile.html", context) -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' - ecommerce
It says that int argument must be a string, however in trying to do that i received more errors. any solutions? i was following an online tutorial which doesn't seem to have this error, so not sure where mine is wrong. views.py def update_cart(request, slug): request.session.set_expiry(120000) try: qty = request.GET.get('qty') update_qty = True except: qty = '' update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) if created: print("yes") if int(qty)== 0 and update_qty: cart_item.delete() elif update_qty: cart_item.quantity = qty cart_item.save() else: pass #if not cart_item in cart.items.all(): # cart.items.add(cart_item) #else: # cart.items.remove(cart_item) new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, name='fuisce-subscription'), path('oneoff/', views.oneoff, name='fuisce-oneoff'), path('about/', views.about, name='fuisce-about'), path('contact/', views.contact, name='fuisce-contact'), path('cart/', cart_views.view, name='cart'), path('cart/<slug>/', cart_views.update_cart, name='update_cart'), path('cart/<int:id>', cart_views.remove_from_cart, name='remove_from_cart'), path('checkout/', order_views.checkout, name='checkout'), ] view.html {% extends "fuisce/base.html" %} … -
Is there a way I can run a web scraper on flask without blocking the server?
I have a web app written in Flask, a user will log in and input some search keywords, these keywords will be passed to a web scraper function I wrote and fetch the data, the web scraper function can take takes some minutes to return the data and render it to the user in a template, while the web scraper is running, the server is blocked, is there a way I can run the web scraper function in a separate thread or background and in some way render the data to the user without blocking the server, My code looks like this @app.route("/", methods=["GET", "POST"]) @login_required def home(): if request.method == "POST": search_phrase = request.form.get("search_term") data = run_scraper(search_phrase) for d in data: print(d) return render_template("index.html", results=data) else: return render_template("index.html") -
Django server deployment sucessful but shows some error on CMD
First I've created a Virtual environment... then I've created a Project called crm when I type python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 19, 2020 - 19:03:25 Django version 3.0.5, using settings 'crm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. then when i go to this http://127.0.0.1:8000/ on Firefox I get the error (click the link to get the image) but the server runs well Can anyone explain me why i got this error?? -
Axios Post Request return Error 400 when that same data and url works with Postman (Django DRF ReactJS)
I am creating an application that uses Django as the backend, and ReactJS as the front end. I am using DRF for the api calls from ReactJS to Django, but am facing an issue with sending a post request. When i send a post request with the relevant data in JSON format using axios in ReactJS, it returns an error code of 400. However, when I copy that same JSON data and use it to send a post request in Postman, there was no error and the code was 201 (created). I am not too sure why there is this issue, and I have already set the neccessary settings in the Django settings.py to ensure that permission is granted (for testing purposes I just set it to 'allow all'). I managed to print out the error message behind the failed post request, but I do not really understand what the error message is talking about. If there is any other way to print out more error messages to sort of let me know where to start, please let me know, thanks! Any help is appreciated! REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for … -
How to display Foreign Key related models fields values in HTML with Django?
I passed a list from Views.py to HTML in a dictionary value. I loop through the fields. There's one column which is Foreign key to another model. Only that model realted information is not displaying in HTML. How to solve this? The following is the code. The Foreign key column "Course" is not showing but others. Screenshot attached here Views.py def Student_Main(request): objs= Students.objects.values().all() template_name = 'genius/students.html' context = {'head_title': 'Little Genius Students', 'students':objs} return render(request, template_name, context) HTML <table class="table table-hover"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">DOB</th> <th scope="col">Age</th> <th scope="col">Gender</th> <th scope="col">Grade</th> <th scope="col">School</th> <th scope="col">Course</th> <th scope="col">Address</th> </tr> </thead> <tbody> {% for i in students %} <tr> <th scope="row">{{i.id}}</th> <td><a href=''>{{i.name}}</a></td> <td>{{i.dob}}</td> <td>{{i.age}}</td> <td>{{i.gender}}</td> <td>{{i.grade}}</td> <td>{{i.attending_school}}</td> <td>{{i.course.class_name}}</td> <td>{{i.address}}</td> </tr> {% endfor %} </tbody> </table> -
how to allow svg in django 3.0 in models
I want to upload the svg images from admin models, how I can enable it? or allowed specific extensions like other .webp ,.docx and pdf etc. -
Django Testing Existence of File as URL
I am trying to figure out how to test for existence of files as URLs in Django. The version below version produces a failure: self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 Here is the code for the test. from django.test import Client from django.utils import translation class ExistenceTest(TestCase): def test_static_css_directory_exists(self): C = Client() response = C.get('/static/css/clean-blog.min.css') self.assertEqual(response.status_code, 200) Any help is appreciated. -
Django Filters - Edit queryset based on slug from url
So I have a simple model called Pages. Every Page belongs to a certain category, since this is a ForeignKey relation, a Page can only belong to a single category. Besides categories we also use tags to furthermore filter the different pages. We use a category view to display all pages belonging to a certain category, easy peasy. The thing is, we use django-filters to filter the pages by selecting different tags. The list of tags is increasing by the amount of pages. Therefore I would like to only show related tags to the category. urls.py path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'), views.py class PageByCategoryView(FilterView): logger.info("Category view is called") model = Page filterset_class = PageByCategoryFilter strict = False queryset = Page.published_objects.all() template_name = 'pages/page_by_category.html' filters.py class PageByCategoryFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter( queryset=Tag.objects.filter(page__category_id='2'), <-- actually works! conjoined=True, widget=forms.CheckboxSelectMultiple() ) class Meta: model = Page fields = [ 'tags__slug' ] So the tags used in the filter actually get filtered by page__category_id = 2, this is exactly what I want to achieve though I want to do this dynamically. I tried to define the qs like so; @property def qs(self): queryset = super(PageByCategoryFilter, self).qs current_category = self.request.GET.get('category_slug') if current_category: logger.info("Current category is in url") return queryset.filter(category__slug=current_category) … -
request.method == 'POST' not working properly
i have created quiz app in which i created three models ( Quiz, Question ,Answer) ,Question have Foreignkey to Quiz and Answer have Foreignkey to Question.i have provided booleanfield to correct ans. Now i created view which redirect to next question if user choose correct ans or else redirect to start But its not properly working. Here is my code Views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk = quiz_id) que = Question.objects.get(pk = question_id) count = q.question_set.count() if request.method == 'POST': selected = que.answer_set.get(pk=request.POST['choice']) if selected is True : try: come = que.rank came = come +1 later_question = q.question_set.get(rank=came) except: come = que.rank came = come later_question = q.question_set.get(rank=came) else : come = que.rank later_question = q.question_set.get(rank=come) return render(request,'app/question_detail.html',{'count':count,'que':que,'later_question':later_question}) else: return render(request,'app/result.html') -
Django ManyToMany Field in forms.CheckboxSelectMultiple: how scroll the records in the template?
I have two models with a ManyToMany Relationship and in the form, I would render this with a list of checkboxes. But I have a lot of records displayed! models.py class Categoria(models.Model): NomeCategoria = models.CharField(max_length=50,blank=True,null=True) class Prodotti(models.Model): ''' tabella Prodotti a catalogo ''' NomeProdotto = models.CharField(max_length=70,blank=True,null=True) CategoriaProdotto = models.ManyToManyField(Categoria, related_name='prodotti_categoria') ... forms.py class ProdottoModelForm(forms.ModelForm): class Meta: model = Prodotti fields = "__all__" widgets = { 'CategoriaProdotto': forms.CheckboxSelectMultiple() } HTML template ... <div class="card-body"> {{ form.CategoriaProdotto|as_crispy_field }} </div> ... A list with a lot of checkboxs Is there a way to have a list of ten checkboxes and a vertical scrollbar? I've tried with rows or size, but don't resolve the question: ... widgets = { 'CategoriaProdotto': forms.CheckboxSelectMultiple(attrs={'rows':10}) } ... Thanks