Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve RuntimeError - models conflicting in Django?
I am trying to connect an external mysql db to Django only for reading data. I have followed the instruction according to the Django Doc to connect multi-DB. However, when I try to makemigration/ migrate the new DB, it returns the error as follows shown. I have do some research on google and found that not many solution out there and can solve my problem. Its my first time to see this and have no idea whats the reason leading the error. I import the models by inspectdb and TotalopennumTmp is one of the models in DB. Thanks for helping me solve this problem. ERROR: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/app/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/app/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/app/venv/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/app/venv/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/app/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File … -
I just need the opposite thing of this filter code,for drop feature...(Correlation analysis filter & drop values from json using python)
I need something like.. def corr_analysis_drop(w,x,y,z): #Importing necessary csv file--- df_corr = pd.read_csv(str(w),na_values = ["NaN", 'NaT','','Missing','NA','na','N/A','n/a','nan','NAN'],encoding = "ISO-8859-1") #Finding only the numeric columns--- numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64','double'] newdf = df_corr.select_dtypes(include=numerics) # Subsetting the dataframe with selected columns--- newdf1 = pd.DataFrame(df_corr[x]) # Finding the correlation--- result_corr = newdf1.corr() test={} for i,j in result_corr.to_dict().items(): # Here j is another dictionary--- temp={} for k,l in j.items(): for m in range(len(y)) : if float(y[m]) < l <= float(z[m]) : pass else: temp[k] = l if temp: test[i]=temp # Converting to dictionary from the dataframe--- response = json.loads(json_util.dumps(result_corr)) dict1 = json.dumps(response) my_dict = json.loads(dict1) return test Here, I am dropping the values from the json according to the input. And showing rest of the values for the json element which does not lie in the given range. This one is working but not giving the correct json back. In the input, when I am providing only 1 value for the ranges, it is dropping that value from the json and showing the rest of the values. But when I am putting no of range values more than 1(say,Range1 = 0.1,0.2 , Range2 = 0.2,0.5), it is giving the whole json back, … -
Django: get_or_create() and FileField
I like the get_or_create() and update_or_create() methods a lot. They don't seem to work with FileField. If I try this: blob, created = Blob.objects.get_or_create(name='foo2', defaults=dict(content_file='my_content')) ... I get: /home/u/bin/python /home/u/src/test-filefield-get-or-create.py Traceback (most recent call last): File "/home/u/src/test-filefield-get-or-create.py", line 7, in <module> print(blob.content_new.read()) File "/home/u/src/modlink/modlink/models/blob.py", line 65, in _get_content self._cached_content = self.content_file.read() File "/home/u/lib/python2.7/site-packages/django/core/files/utils.py", line 16, in <lambda> read = property(lambda self: self.file.read) File "/home/u/lib/python2.7/site-packages/django/db/models/fields/files.py", line 51, in _get_file self._file = self.storage.open(self.name, 'rb') File "/home/u/lib/python2.7/site-packages/django/core/files/storage.py", line 38, in open return self._open(name, mode) File "/home/u/lib/python2.7/site-packages/minio_storage/storage.py", line 106, in _open "File {} could not be saved: {}".format(name, str(e)), e) minio_storage.errors.MinIOError: File x could not be saved: NoSuchKey: message: The specified key does not exist. -
Django keep database state while atomic transaction
I'm facing an issue I have no clue to solve it. The whole part of a code is encapsulated into a with transactions.atomic() ensuring that if something fails, then the database won't be modified and will be restored to the previous state. That is working. But what I'd like is during the whole execution of the code, the state of the Db is not changing, that way if I change a model during that atomic transaction, it won't be saved before the end of the atomic transaction, and I still can acces its "previous" state. Is there a way to achieve that in python/django ? I think it's kind of "idempotent" right ? Thank you a lot for your help ! -
Get binary data from Rest API (Django Rest) in React (using Axios)
I need some help to know how to do this. I have binary files on my server that countains data, I need to download them from my Django Rest API and transform into list with React to be able to use them on charts. Currently I've converted these binary data in JSON on the API side and I can get them pretty easily, but the file length is too big (30mb). If I work with binary data and process them in the frontend (converting into unsigned int and applying a constant), this should be really faster. Here my code atm on Django Rest side (I decompress data before because they are in .xz format) : f_content = lzma.decompress(bytes(open(the_file,'rb').read())) iof_content = BytesIO(f_content) filename = os.path.basename(the_file) response = HttpResponse(content_type='application/octet-stream') response.write(f_content) response['Content-Disposition'] = "attachment; filename=%s" % filename connection.close() return response And here my code on the React side : console.log(response); var array = Uint8Array.from(response.data); console.log(array); What console.log(response) print is something like this : Object { data: "����\u0006�ܜ�����I��\u001f�ҧ��h��N����ɽ����ű�å�����\u001c��������\u0006�� ��m��������@��,��������u��'��#��\t��=��K�����������\u0011��p�����K�����P��������R��\u000c��\u0008��������~��~�����h�����������������-��������M��������+�����'�����H��������2��;��������������������������2��&�����5��������9�����\u000f��>��������4�����\u0018�Ŭ�Ǥ��#�ʃ��4����ύ��.�����\u0000�������ړ�܉�ރ�����G��\u0018��T��N��\\�����������\u0005��U��������!�\u00001�\u0002\u007f�\u0004��\u00074�\t��\u000b��\u000e\u0002�\u0010v�\u0013\u0005�\u0015P�\u0017��\u001ao�\u001c��\u001f��!��$��'W�)��,��/l�2\u0007�4��7��:��=��@��D\u0010�F��I\u0015�K3�Md�ON�Q\u0006�S^�U��Y\u0002�\\_�_��b��e��h��l\u0010�o��s)�v\u001e�y\u0010�|-�\u007fF��B��!��\u0000��k��R��p��(��\u0007��6��������V��v�����������K�����������m�Ò�ƪ��\u0016�Ͱ�����%��e�����-�����E��|�����7����&��R����\u0000\u0019�\u0003��\u0007\u0018�\nx�\r��\u0011��\u0015\u000f�\u0018��\u001b��\u001fh�#\u0008�&s�)��-V�0��40�7��;��?5�B��F\u0019�I��M\u0015�P��T\u001a�W��[q�_\u001e�b��f:�i��mu�qN�t��x]�{��\u007fJ��������=�����B�����\u000f�����K�����T��\u001c�����\u0010��������[�����x����ʗ�� ��|��\u000f��\u007f��i�����V��-����>��B�����\u0011����\u0000U�\u0003��\u0007f�\u000b)�\u000e��\u0012T�\u0015��\u0019}�\u001c�� k�$\"�'��+O�.��22�5��9��=\u001d�@��DT�G��K��Os�R��U��YH�]\u000f�`��d��hI�k��oc�s\u0014�v��y��}���l��\u000b��o�����0�����1��������:�����@�����������\n�����)�����…", status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest } But when I transform into Uint8Array, I don't get the good array size and I've too many 0... Can you help me … -
module 'django.db.models.fields' has no attribute 'subclassing'
Here’s a sample model to hold a bunch of generic information related to the webhook event. I'm working on a problem in which I have to convert django code to Django rest framework. Here is a link if you want to refer: https://medium.com/@raiderrobert/how-to-make-a-webhook-receiver-in-django-1ce260f4efff Now I'm trying to write it in Django Rest Framework. After creating a serializer.py file, I'm getting this error:- class HStoreDescriptor(models.fields.subclassing.Creator): AttributeError: module 'django.db.models.fields' has no attribute 'subclassing' I don't know what I'm doing wrong here. models.py serializer.py -
Why django authenticate always return none
i have a few questions why Authenticate() always return none but when i tried using Exists() its return the user? Can we just using Exists() for user login? Im using django 1.11.7 and class based views this is my views.py class ShopLoginView(FormView): template_name = 'shop/login.html' form_class = LoginForm success_url = '/shop/' this is my forms.py class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField() def clean(self): cleaned_data = super(LoginForm, self).clean() email = cleaned_data.get("email") password = cleaned_data.get("password") user = authenticate(username=email, password=password) if user is not None: print(user) else: print(user) raise forms.ValidationError("Wrong Email or Password") this is when i use the Exists() method class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField() def clean(self): cleaned_data = super(LoginForm, self).clean() email = cleaned_data.get("email") password = cleaned_data.get("password") user = User.objects.filter(email=email, password=password) if user.exists(): print(user) else: print(user) raise forms.ValidationError("Wrong Email or Password") any ideas to what might be happening? -
Django Suit only show the second objc inline
So I have two model's Model 1 class Model1(models.Model): ........ Model 2 class Model2(models.Model): model1 = models.ForeignKey(Model1, related_name='Model1Objects',on_delete=models.CASCADE) Model1.admin class Model2Inline(admin.StackedInline): model = Model2 form = Model2Form extra = 0 max_num = 3 class Model1Admin(admin.ModelAdmin): form = Model1Form model = Model1 inlines = [Model1Inline] The problem is that when I add objec to model2, it does not appear. But if i add one more, it will appear what I previously added and always lacked 1. -
mypy returning module 'X' has no attribute 'MyClass' with django rest framework
I have the following django rest framework setup app/models.py: from django.db import models class A(models.Model): x = models.CharField(max_length=8) app/serializer.py: from .models import A from rest_framework import serializers class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = "__all__" however mypy (0.67) returns the following error: serializer.py: error: Module 'app.models' has no attribute 'A' how can I resolve this error? -
How to parse URLs queried from model?
I want to retrieve the url from FeedSource class model to save the feed in my site In models.py class FeedSource(models.Model): url = models.URLField(max_length=400, blank=True) is_active = models.BooleanField(default=False) class Feed(models.Model): feedsource = models.ForeignKey(FeedSource, on_delete=models.CASCADE, null=True) author = models.CharField(max_length=250) In apps.py from feed.models import Feed, FeedSource import feedparser d = feedparser.parse('http://feeds.feedburner.com/ycombinator/') I expect the output to retrieve the url from the FeedSource model and save the feed in my site. But I have done it with manual url that is: d = feedparser.parse('http://feeds.feedburner.com/ycombinator/') -
How can i convert this my function-based view to class-based view in django
am trying to convert my function based view to class-based view the problem is that am querying the database twice, the first one is to get all the post in the database from the Post model and the second is to get all the category in the database from the Category model here is the code view.py def newPost(request): deyCat = Category.objects.all() if request.method =='POST': myForm = NewPostForm(request.POST, request.FILES) response_data = { 'SType': 'danger', 'message': "An Error Occured, pls try again later" } if request.POST.get('deyHidden') == 'create_hidden': title = request.POST.get('title') content = request.POST.get('content') category_id = request.POST.get('category') image = request.FILES.get('image') if myForm.is_valid(): if Posts.objects.create(title=title, content=content, category_id=category_id, image=image, author_id=request.user.id): response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") elif request.POST.get('deyHidden') == 'category_hidden': CatNames = request.POST.getlist('CatName[]') for CatName in CatNames: Category.objects.get_or_create(CatName=CatName) response_data = { 'SType': 'success', 'message': "Saved Successfully" } return HttpResponse(json.dumps(response_data), content_type="application/json") context={ 'form':NewPostForm(), 'title':'Create Post', 'category': Category.objects.all() } return render(request, 'blog/form.html', context) in the models.py class Category(models.Model): CatName = models.CharField(max_length=100) def __str__(self): return self.CatName class Posts(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, default="1", on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='blog_pics') def __str__(self): return self.title pls, how can i do this -
Django naming convention for views/models as package
I split my views.py and models.py into packages views/ and models/ the module views.py is in plural. when it is split into package views/ the files have to be plural or singular? example, in the models/ we have: models/ employee.py department.py schedule.py views/ employee.py department.py schedule.py according to django, the files should be in plural, but in such situation, should i give each file name plural or singular? -
I applied filterset in drf. i didn't know why all the data is returned when i query with a field not in filterset
I don't know why all data is returned when I query with a field that not in FilterSet class This is my model class TempModel(models.Model): md5 = models.CharField() sha1 = models.CharField() and following is my filterSet class class TempFilter(filters.FilterSet): class Meta: model = TempModel fields = ("md5") and finally this is my ViewSet class TempViewSet(viewsets.ModelViewSet): queryset = TempModel.objects.all() permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] serializer_class = TempSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = TempFilter I make a request /temp/?md5=XXXX, it works very well. but /temp/?sha1=XXXX, it returns all data I think if request not specified fields, it returns not found I try to define exclude in filterset class, but it still not working, How i solve that problem?? -
Bootstrap4 in PyCharm Django project - Active navbar
I am using .html and bootstrap 4 within a Django - PyCharm project. How to make navbar active when clicking on it ? Here is my base .html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Base</title> <!--bootsrap--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> {% block content %} {% endblock %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <ul class="navbar-nav"> <li class="nav-item" id="link-football"> <a class="nav-link" href="{% url "page1" %}">page1 </a></li> <li class="nav-item" id="link-Overview"> <a class="nav-link" href="{% url "page2" %}">page2</a> </ul> </div> <!-- Content Block --> </nav> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> Here is page1.html {% extends 'base.html' %} {% block content %} <h1> This page 1 </h1> <script> $(document).ready(function () { $(".active").removeClass("active"); $("#link-football").addClass("active"); }); </script> {% endblock %} Here is my page2.html {% extends 'base.html' %} {% block content %} <h1>This is Page 2</h1> <script> $(document).ready(function () { $(".active").removeClass("active"); $("#link-Overview").addClass("active"); }); </script> {% endblock %} Here is the screenshots of both pages: The reason for added tags is to show that the contents is being loaded -
Django JS Internationalization doesn't return error message when change to another language
I'm trying to do internationalization of the text within my javascript file by following django tranlstion docs.The function raise text error whenever the order amount larger than the stock amount. I successfully created the djangojs.po within the locale folder on root and got the error message translated to english with the error.After i switch to the second language the error should show up in that language but the error didn't pop up and the shopping cart still allow the product to be add(even if the quantity in the Cart larger than in the stock) in English the error raise in english in Vietnamnese the error doesn't happen and it still allow to add products to shopping Cart My javascript knowledge in limited any help would be appreciate I have tried restarting server. I couldn't find any question or answers related to internationalization affect javascript function My urls.py: from django.conf.urls.i18n import i18n_patterns from django.views.i18n import JavaScriptCatalog from django.urls import path from . import views urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), ] javascript function : $scope.addProduct = function (id, count) { var total = parseInt($('#product-' + id).attr('total').replace(/\./g, '')); for (var index = 0; index < $scope.cart.length; index++) { var line … -
IntegrityError NOT NULL constraint failed when user submit form
I got problem with NOT NULL constraint failed, so basicly I have 3 apps in 1 project, one of apps is games app which works without any problems. Every app got own model, for example app games got model Game, app streamers got model Streamer and app shots with model Shot, all models got similar fields added_by = models.ForeignKey('auth.User', on_delete=models.CASCADE) and every view in views.py shot.added_by = request.user And now, every user is able to add Shot (if there exist atleast 1 streamer) and if form is valid, but none user can add any Game or Streamer by form because there is IntegrityError at /streamers/add_streamer NOT NULL constraint failed: streamers_streamer.added_by_id And the only one who is able to add a Streamer or Game is me from admin panel. I've made migrations, migrated them without problem but can't solve this problem. Here is a bit of my code from apps that causes the problem I was trying some ways like clearing all the database, deleting all migrations and then re-migration but still no result and I dont know what causes problem. streamers/models.py from django.db import models from games.models import Game, Genre from shots.utils import get_unique_slug from django.utils import timezone from django.contrib.auth.models … -
Changes on model instance not shown in Tempalate
I'm new to django and I'm trying to create a like buttton. When I click on the button I can see that the Like model gets updated with user and the post that the user liked. Then I also see that the total likes in the Post model gets incremented by 1. But the template it self still shows 0 likes. class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.CharField(max_length=255) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) categorys = models.ManyToManyField('Category') tags = models.ManyToManyField('Tag') likes = models.IntegerField(default=0) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(null=True, upload_to=post_image_file_path) ''' class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) ''' path('', views.home_view, name='home'), path('like/', views.like, name='like'), ''' def home_view(request, *args, **kwargs): all_posts = services.get_all_posts() all_categorys = services.get_all_categorys() all_tags = services.get_all_tags() context = {'all_posts': all_posts, 'all_categorys': all_categorys, 'all_tags': all_tags} return render(request, 'blog/home.html', context) def like(request, *args, **kwargs): if request.method == 'GET': model = get_user_model() postid = request.GET.get('postid') user = model.objects.get(id=request.user.id) post = Post.objects.get(id=postid) if Like.objects.filter(user=user, post=post).exists(): Like.objects.filter(user=user, post=post).delete() update_likes = Post.objects.get(id=post.id) update_likes.likes -= 1 # change field update_likes.save() # this will update only else: like = Like.objects.create(user=user, post=post) update_likes = Post.objects.get(id=post.id) update_likes.likes += 1 # change … -
Django - how to add another field to be search in my queryset
Currently studying django. I'm trying to add genre icontains for my existing search which only fetch title. but i wonder why i'm getting error of Related Field got invalid lookup: icontains this is my search code in views.py def Search(request): queryset = Book.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(genre__icontains=query) ).distinct() context = { 'queryset': queryset } return render(request, 'search_results.html', context) heres is my book model. class Book(models.Model): title = models.CharField(max_length=200) ```some fields``` genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', kwargs={'slug': self.slug}) here's the traceback Traceback: File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\thesis\blackink_website\catalog\views.py" in Search 73. Q(genre__icontains=query) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in filter 844. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 862. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in add_q 1263. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in _add_q 1281. current_negated, allow_joins, split_subq) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in _add_q 1287. split_subq=split_subq, File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_filter 1225. condition = self.build_lookup(lookups, col, value) File "C:\Users\admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py" in build_lookup 1087. raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) Exception Type: FieldError at /search/ … -
How do I fix this URL mapping problem? The pages are being displayed but the url is incorrect
In this django app, I am trying to go to a specific page but the route it takes is not the correct one. Can you please tell me what am I doing wrong. Ex. From http://127.0.0.1:8000 I am trying to go to http://127.0.0.1:8000/register but it takes me to http://127.0.0.1:8000/dashboard/register. The http://127.0.0.1:8000/register link is working fine though if I enter it manually. views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(request): return render(request, 'formfiller/home.html') def register(request): return render(request, 'formfiller/signup.html') def login(request): return render(request, 'formfiller/login.html') def download(request): return render(request, 'formfiller/download.html') def forgotpw(request): return render(request, 'formfiller/forgotpw.html') def learnmore(request): return render(request, 'formfiller/learnmore.html') def dashboard(request): return render(request, 'formfiller/dashboard.html') def success(request): return HttpResponse("Your account has been successfully created.") urls.py (for the app) from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('register', views.register, name='signup'), path('login', views.login, name='login'), path('download', views.download, name='download'), path('forgotpw', views.forgotpw, name='forgotpw'), path('learnmore', views.learnmore, name='learnmore'), path('dashboard', views.dashboard, name='dashboard'), path('success', views.success, name='success'), ] urls.py (for the main project) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('formfiller.urls')), path('register/', include('formfiller.urls')), path('login/', include('formfiller.urls')), path('download/', include('formfiller.urls')), path('forgotpw/', include('formfiller.urls')), path('learnmore/', include('formfiller.urls')), path('success/', include('formfiller.urls')), path('dashboard/', include('formfiller.urls')), ] -
Use of Dunder Methods in Python
Does these dunder methods works in Python like Constructor in other languages? I am getting hard to grasp this idea of dunder methods as this is my first time for Python n Django training. Please guide -
How do i use the less than or greater than signs inside html in python django
Hi am struggling using the greater than sign inside the html template. am using python 3.7.2 and django 1.8.6 I cant execute this code here gives an error {% extends "base.html" %} {% block Content %} <h1>Tags</h1> {% for instance in object_list %} <li><a href='{{ instance.get_absolute_url }}'>{{ instance.title }}</a> ({{ instance.products.count }} product{% if instance.products.count > 1 %}s{% endif %})</li> {% empty %} <li>No Tags yet.</li> {% endfor %} </ul> {% endblock %} So the > 1 is the problem here help out -
Insert for loop item in django output field
I have a for loop in my django template: {% for item in data %} {{ item.Load}} {{ item.To }} {{ item.From }} {{ item.Weight }} and I want to parse item.load in this format {{ forminput.field.value|default_if_none:"" }} but when I do this, {{ forminput.field.item.Load|default_if_none:"" }} it doesn't show my field in the django form. When I enter a static value(e.g. 3) in this it appears in the form like this {{ forminput.Load_ID.3|default_if_none:"" }} it shows the 4th object on the page. How can I insert item.Load in value ? -
How do I pass a foreign key to a formset with a model form, both forms are in the same page
I want to give a foreign key to the foreign key id in a modelformset, that was just created using model form. ie The model forms model is the foreign key to the modelformset's model. How do I go about doing this? form_object_from_modelformset.foreignkey_id= #what should I pass in here -
Wagtail create custom StreamField block from field?
I've created custom MarkdownField and MarkdownPanel classes following this tutorial: from django.db.models import TextField from django.utils.translation import ugettext_lazy as _ from wagtail.admin.edit_handlers import FieldPanel from wagtail.utils.widgets import WidgetWithScript from wagtail.core.blocks import FieldBlock class MarkdownField(TextField): def __init__(self, **kwargs): super(MarkdownField, self).__init__(**kwargs) class MarkdownPanel(FieldPanel): def __init__(self, field_name, classname="", widget=None, **kwargs): super(MarkdownPanel, self).__init__( field_name, classname=classname, widget=widget, **kwargs ) if self.classname: if 'markdown' not in self.classname: self.classname += "markdown" else: self.classname = "markdown" And they work really well as fields: My goal is to be able to make a custom Block to use it within a StreamField on a page model like this: class TestPage(Page): body = StreamField([ ('markdown', MarkdownBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body') ] api_fields = [ APIField('body') ] So I've tried to create a custom Block class as per the Wagtail docs: ... (MarkdownField and MarkdownPanel classes defined above) class MarkdownBlock(FieldBlock): def __init__(self, field_name, classname="", widget=None, **kwargs): self.field = MarkdownField() super(MarkdownPanel, self).__init__( field_name, classname=classname, widget=widget, **kwargs ) But I'm met with this error during makemigrations: File "*******/cms/home/models.py", line 65, in TestPage ('markdown', MarkdownBlock()), TypeError: __init__() missing 1 required positional argument: 'field_name' I know I'm doing something wrong here, but the documentation doesn't have much advice beyond a basic example and … -
How to fix "django.core.exceptions.FieldError:" when querying with "_startswith" filter in django views?
I am trying to get a queryset where the username starts with some name. I have implemented the following code : def searchUsers(request): if request.is_ajax(): uname = request.GET['name'] print(uname) user = User_Master.objects.filter(username_startswith = uname.title()) usr_jsn = json.loads(serializers.serialize('json', user)) return JsonResponse(usr_jsn) Ajax call is succesfully running and I'm getting the searchkeyword printed in terminal. But the error I'm getting is because of "_startswith" filter. This is the part from traceback. django.core.exceptions.FieldError: Cannot resolve keyword 'username_startswith' into field. Choices are: contact_no, created_at, created_by, department, email, id, industry_segment, password, status, updated_at, updated_by, username I have searched for my problem but none of the solutions worked.