Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Toggle does not display. Django
I am currently following this tutorial but with my own template that I got from w3layouts. I am using it as a practice project to better learn Django. I am currently trying to implement a user login/signup page. When you click on the icon/image that represents the user, you are supposed to be treated with a drop down lift of, My account, my favorites, my cart etc. etc. As I am using a different template from the one in the video, I understand that there may be issues. The following is the Lecturers( guys tutorial I'm following) drop down for user functionality. <li class="header-account dropdown default-dropdown"> {% if user.id is not None %} <div class="dropdown-toggle" role="button" data-toggle="dropdown" aria-expanded="true"> <div class="header-btns-icon"> <img src="{{ request.session.userimage }}" style="height: 40px; border-radius: 30%"> </div> <strong class="text-uppercase">{{ user.first_name }} <i class="fa fa-caret-down"></i></strong> </div> {% else %} <a href="{% url 'login' %}" class="text-uppercase">Login</a> / <a href="{% url 'signup' %}" class="text-uppercase">Sign Up</a> {% endif %} <ul class="custom-menu"> <li><a href="{% url 'user_index' %}"><i class="fa fa-user-o"></i> {% trans "My Account" %}</a></li> <li><a href="#"><i class="fa fa-heart-o"></i> {% trans "My Favorits" %}</a></li> <li><a href="{% url 'user_orders' %}"><i class="fa fa-exchange"></i> {% trans "My Orders " %}</a></li> <li><a href="{% url 'user_comments' %}"><i class="fa fa-check"></i> … -
Derive a schema version of a model class?
I have a use case where I want to serialize list of model instances and store it. Along with it, I want to store a "schema version" Now when I deserialize these model instances, I want to be sure that the model schema didn't change. If it didn't change I'll use the deserialized models. if it did change, I'll fall back to query from the database Roughly something like this from django.core import serializers def serialize(instances): return json.dumps({ "data": serializers.serialize('json', instances), "version": schema_version_for(MyModel) }) def deserialize(serialized): data = json.loads(serialized) version = data["version"] instances = serializers.deserialize('json', data["data"]) if version != schema_version_for(MyModel): # fall back to query from database return MyModel.objects.filter(id__in=[o.id for o in instances]) else: return instances Whats the best implementation of schema_version_for(ModelCls) I'm thinking around using the field names and field types to generate some sort of version. If you know of a better way to implement this, I'd love to hear. -
django filter with pagnition
Actually I have two inquiries. I looked a lot for answers, but I could not find. 1 _ How to add multiple pagination to same view ? 2 _ How to add options to the filter, such as dropdown ? this is my view.py: def Multimedia_Software(requset): category = Categorie.objects.all() Multimedia_Software = Apps.objects.filter(category=category[6]).order_by('App_title') myFilter = AppsFilter (requset.GET,queryset = Multimedia_Software) Multimedia_Software = myFilter.qs paginator = Paginator(Multimedia_Software,15) page = requset.GET.get('page') try: Multimedia_Software=paginator.page(page) except PageNotAnInteger: Multimedia_Software=paginator.page(1) except EmptyPage: Multimedia_Software=paginator.page(paginator.num_pages) context = { 'page':page, 'Multimedia_Software':Multimedia_Software, 'myFilter':myFilter, } return render( requset , 'windows/Multimedia_Software.html' , context ) this my filter.py: import django_filters from .models import Apps class AppsFilter (django_filters.FilterSet): App_license = django_filters.CharFilter(label='Filter the license' ) class Meta: model = Apps fields = ['App_license'] this is my model.py: App_license = models.CharField(max_length=100 , null=True) I used pagination with first queryset and I want to use it too with filter.How is this done? and How can I add options to the filter? -
Case/When Annotation on m2m field relationship is duplicating results
I am trying to annotate the existence of a m2m relationship onto a model's queryset. Models class Dog(models.Model): text = CharField(max_length=10) class Animal(models.Model): member = ManyToManyField(Dog, related_name='members') I want to build a query for Dog that annotates a BooleanField of whether Animal contains an M2M relationship for that Dog. This is what I've come up with so far, but it is returning a duplicate result for every relationship_exists = True (so one record with True, one with False) Current Query animal_id = Animal.objects.get(id=1).id queryset = Dog.objects.all().annotate( relationship_exists = Case( When(members__in=[animal_id], then=Value(True)), When(~Q(members__in=[animal_id], then=Value(False)), default=Value(False), output_field=NullBooleanField() ) ) Which would return not only all records where relationship_exists=True, but also for each of those True records, it would have a corresponding record of the same Dog with relationship_exists=False. I've tried setting the default to None and Coalescing the value, I've tried eliminating my second When clause and setting default value to None. None of it is working, and I'm not sure why this is the case. -
Django 3: Forgotten Password Reset: Is there a way to block password reset view to appear when ther user is logged in?
I have implemented a built in Django password reset procedure using django.contrib.auth.views. It works, but there is a problem, when the user is logged in he/she still can type in password reset url and then reset the password. I would like to prevent password reset view to appear when the user is logged in. What is the best way to achieve this? -
python elasticsearch error in modifying and adding doc during remote access
Hello I have some questions.. I developed django website on Windows 10 and changed OS to ubuntu for publishing On Windows, there were no problems but problems appeared on ubuntu My website uses a remote access on EleasticSearch and also uses elasticsearch, elasticsearch_dsl python lib. There was no error searching the document in index from an external connection, but an error occurs when adding update_by_query or a new document. There are no other settings except for modifying network.host in elasticsearch.yml to 0.0.0.0 Do I need special permissions or other settings to modify or create documents from outside? I am so stressed because of this. If anyone knows, I'm sure you're busy, but please give me a detailed explanation or a link. Thank you. -
Django loader while waiting for api response
I'm trying to put a loader while I'm waiting for the response from an api, because the loading time sometimes is high. The flow is the following: I made a form that leads to a payment api, and after the payment, the web app invokes another api which tries to do something, and that something sometimes takes too much time and the user may think something went wrong. So, my question is how could I put a spinner, or a loader, when waiting for the respose, and after the response is fetched, it redirects the user to the normal flow (a landing page that shows success or fail) -
ImportError: cannot import "url" from "app's" directory to project's urls.py
I am using Django==3.1.4. this is folder structure: - backend - urls.py - base - urls - order_urls.py - user_urls.py - product_urls.py - views inside backend/urls.py, i have this: from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), // user_urls, order_urls, product_urls are inside base/urls directory path('api/users/', include('base.urls.user_urls')), path('api/orders/', include('base.urls.order_urls')), path('api/products/',include('base.urls.product_urls')), ] urlpatterns +=static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if i call python3 manage.py runserver, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/my-desktop/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/my-desktop/anaconda3/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/my-desktop/Documents/projects/next.js/django-bingology/myenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in … -
Django Rest Framework how to set error_messages on models.CharField
Hi! summarize the problem I have a Django Rest Framework backend, on which I want to do a simple thing: change default validation message: 'max_length': _('Ensure this field has no more than {max_length} characters.'), To a custom one like 'max_length': 'I am happy to see you {max_length}.' methods that failed are on the bottom of this post minimal example: from django.contrib.auth.models import ( AbstractBaseUser, PermissionsMixin, ) from django.db import models from rest_framework import serializers class User(AbstractBaseUser, PermissionsMixin): name = models.CharField("Name", max_length=42, null=True, error_messages={'max_length':"I am happy to see you {max_length}."}) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name"] extra_kwargs = { "name": {"required": True, "allow_blank": False, "allow_null": False}, } error messages seem to be ignored. What failed: error_messages as a CharField argument (as shown in example) based on this issue, I tried setting up a validatior argument for CharField, like: validators=[MaxLengthValidator(42, message="I am happy to see you {max_length}.")] based on a very similar stack question I tried adding a custom CharField class. Maybe I didnt understand their solution, because inheriting from fields.CharField didnt allow me to set stuff into init method (I use model.CharField, they use field.Charfield. It didnt work either way. Based on this issue I started wondering … -
Get key-value pairs of specific fields from Many-to-many related models without duplication
I want to get the keys and values of the specific fields from two models with one queryset. I use a many-to-many relationship between them. I use this queryset: Article.objects.values('title', 'topic__title')[:9] My models (shotlisted most of the fields for simplicity): class Article(models.Model): title = models.CharField('Title', max_length=99) topic = models.ManyToManyField('Topic', related_name='articles') body = RichTextField(blank=True, null=True) class Topic(models.Model): title = models.CharField(max_length=150) body = RichTextField(blank=True, null=True) This queryset returns one Article object multiple times if that Article object has multiple topics. How can I get only specified keys without sacrificing performance (with one query if possible)? I want queryset to return a list of dicts like this (anything near to it is acceptable as well): [ { "title": "Hello world", "topic__title": ["Programming", "Tutorial"] }, { "title": "Let's start coding", "topic__title": "Tutorial" } ] Please provide your code with an explanation and your suggestions are very welcome and highly appreciated. -
show only one type of user in forms using django
I'm trying to create an appointment app using Django but when I add the form it show me all the users how can i change that to only one type of user and make the user who register the appointment him self this is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False class Appointement_P(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointement') patient = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='paitent_app') doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.Field(null=True, blank=True, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) and this is my fomrs.py class AppointementForm(forms.ModelForm): class Meta: model = Appointement_P fields = ('doctor', 'date', 'start_time',) and this is my fucntion in the views.py def create_appointement_p(request): user = User() form_appointement = AppointementForm() if request.method=='POST': if request.user.is_paitent(): form_appointement = AppointementForm(request.POST or None) if form_appointement.is_valid(): form_app = form_appointement.save(commit=False) form_app.save() messages.success(request, 'appointement added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement1.html',) else: return HttpResponseRedirect(reverse("create_appointement_D")) return render(request,'appointement/add_appointement1.html',{'form':form_appointement}) and this is the html file <body> <div class="container"> {{ … -
Django Query - Get list that isnt in FK of another model
I am working on a django web app that manages payroll based on reports completed, and then payroll generated. 3 models as follows. (ive tried to limit to data needed for question). class PayRecord(models.Model): rate = models.FloatField() user = models.ForeignKey(User) class Payroll(models.Model): company = models.ForeignKey(Company) name = models.CharField() class PayrollItem(models.Model): payroll = models.ForeignKey(Payroll) record = models.OneToOneField(PayRecord, unique=True) What is the most efficient way to get all the PayRecords that aren't also in PayrollItem. So i can select them to create a payroll item. There are 100k records, and my initial attempt takes minutes. Attempt tried below (this is far from feasible). records_completed_in_payrolls = [ p.report.id for p in PayrollItem.objects.select_related( 'record', 'payroll' ) ] -
Django. How to send non english word in url?
The project is a dictionary of Russian terms that can be translated into any other language. Here are a few Django models to be aware of. class Term_rus(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) class Term_foreign(models.Model): term_rus = ForeignKey(Term_rus, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) name = models.CharField(max_length=128) definition = models.TextField() image = models.ImageField(default='', blank=True) The hosting I use is provided by MySQL 5.7. Here is the database setup in the settings.py file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dictionary_db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES';", 'charset': 'utf8', 'use_unicode': True, }, } } I also configured Server connection collation and Database collation to utf8_general_ci in the database settings on the server. The site should be able to search for terms in any language. Here is the URL path to redirect to when searching. urlpatterns = [ ... path(r'<str:language>/search/<str:search_string>', views.search_results, name='search_results'), ] And here is a method search_results. def search_results(request, language, search_string): if request.method == 'POST': search_string = request.POST.get('search_string') return redirect('search_results', language, search_string) else: ... terms search ... Also, if you need a search form and html code: class SearchForm(forms.Form): search_string = forms.CharField(label='', widget=forms.TextInput(attrs={'class': 'input', 'placeholder': 'Найти'})) … -
How to set the language for the whole session after login in Django
I'm stuck, trying to set the language for an entire session, so that the menus, forms, etc. are displayed according to the language entered during login. For this I have defined the following: In the settings.py file add the middleware: 'django.middleware.locale.LocaleMiddleware', MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Also add the context renderer: 'django.template.context_processors.i18n' And I defined my 3 languages: LANGUAGE_CODE = 'es' LANGUAGES = [ ('es' _('Spanish')), ('en', _ ('English')), ('it', _ ('Italian')), ] This is my view: class LoginFormView(FormView): form_class = UserLoginForm template_name = 'login.html' success_url = reverse_lazy('index') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect(self.success_url) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): login(self.request, form.get_user()) user_language = self.request.POST.get('language', None) translation.activate(user_language) self.request.session['django_language'] = user_language self.request.session[translation.LANGUAGE_SESSION_KEY] = user_language return HttpResponseRedirect(self.success_url) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Iniciar sesión' return context Despite this, the language after login does not change and always remains in Spanish. All templates have the tag: {% load i18n %} I also tried to force the language change by placing a button in the navigation bar, in order to test if the translation works and is indeed working well: <button type="button" class="btn-shadow p-1 btn btn-primary btn-sm"> {% include 'change_language.html' … -
How to fix it Django, Jquery, AJAX and JSON HTTP 500
I am creating the app which books a vizit time. I am trying to show if the time is reserved in my template. I take this code from a working project. But it doesnt work in my project. When I choose any date I have this error Failed to load resource: the server responded with a status of 500 () html {% block content %} <div class="container"> <h3>{{service.name|safe}}</h3> <div align="center"> <form action="" class="form-inline" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <table class="table table-borderless"> <tr><th>{{form.date.label}}</th><td>{{form.date}}{{form.date.errors}}<br><br></td></tr> <tr><th>{{form.time.label}}</th> <td> <table class="table table-bordered"> <tr> <td align="center" valign="center" class="time">9:00</td> <td align="center" valign="center" class="time">10:00</td> <td align="center" valign="center" class="time">11:00</td> </tr> <tr> <td align="center" valign="center" class="time">12:00</td> <td align="center" valign="center" class="time">13:00</td> <td align="center" valign="center" class="time">14:00</td> </tr> <tr> <td align="center" valign="center" class="time">15:00</td> <td align="center" valign="center" class="time">16:00</td> <td align="center" valign="center" class="time">17:00</td> </tr> </table> {{form.time.errors}} </td></tr> <tr><th> {{form.name.label}}</th><td>{{form.name}}{{form.name.errors}}<br><br></td></tr> <tr><th>{{form.info.label}}</th><td>{{form.info}}{{form.info.errors}}<br><br></td></tr> </table> {{form.time}} <div style="padding-left:20%;"><button id="submit" class="btn btn-success">Запись</button></div> </div> </form> </div> </div> <script type = "text/javascript"> $("#id_date").datepicker({ dateFormat: 'yy-mm-dd', }); $(document).ready(function() { //the date is sent via Ajax to the server for comparison // a list with the reserved time for receiving is returned, for comparison with the table var checkUnavailableTime = function() { var date_data = { service_id: {{service.id}}, date_from_ajax: $("input[name=date]").val(), csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").attr('value') … -
how can store ForienKey from get method in django
I am trying to assign the product and category id to vendor, but after creating vendor successfully. When i select category and products for vendor and submit button nothing happened. It just redirect the menu after submit. Even after submit no error shown.When i debug the code and use break points it just only execute the get function and skip the post View.py class Vendor(TemplateView): template_name = 'purchase/vendor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: data = self.request.POST.get vendor = VendorModel( name=data('name'), email=data('email'), Contact_No=data('Contact_No'), address=data('address') ) vendor.save() request.session['Vendor_id'] = vendor.id return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products} return render(request, self.template_name, args) def post(self, request): if 'Vendor_id' in request.session: categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.GET.get('SelectProduct') try: vendor = VendorCategory( vendor_id=request.session['Vendor_id'], category_id=categoryobj, product_id=productobj, ) vendor.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% extends 'auth/home.html' %} {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} </option> {% endfor … -
ajax returns information that are removed from database
I have created a live chart by chart.js and Django. when I remove chart data from the MySQL database, my chart still shows the old data! I don't know how this is possible. I use AJAX to update the chart every 3 seconds. thanks -
Python Django Beginner: can't open manage.py
Trying to get started with Django on pycharm. (venv) C:\Users\Vince\PycharmProjects\assignment>python manage.py runserver But I get this error message whenever i run manage.py: C:\Users\Vince\AppData\Local\Programs\Python\Python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory I do have a django directory opened with a manage.py file in it. Can anyone assist me on what to do? I have tried other solutions, like: python -vvvvv manage.py runserver python manage.py migrate -
How to upload using post in Django?
I am trying to make an API that enables to upload using multipart in Django. I have two files to upload. I can see the data in the Viewset: 'file': [<InMemoryUploadedFile: file.jpg (image/jpg)>], 'thumbnail': [<InMemoryUploadedFile: thumbnail.jpg (image/jpg)>]} However it does not pass or it fails from the serializer. I get an error since the serializer is not valid. I am getting this error: {'thumbnail': [ErrorDetail(string='The submitted file is empty.', code='empty')]} class Product(models.Model): name = models.CharField() file = models.FileField( upload_to=settings.PRODUCT_PATH, null=True, blank=True, max_length=500) thumbnail = models.FileField( upload_to=settings.PRODUCT_PATH, null=True, blank=True, max_length=500) class ProductSerializer(serializers.ModelSerializer): file = serializers.FileField() thumbnail = serializers.FileField() class Meta: model = Product fields = ('__all__') class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser,) def create(self, request): data = request.data.copy() data['file'] = self.request.FILES.get('file') data['thumbnail'] = self.request.FILES.get('thumbnail') serializer = ProductSerializer(data=data) print('validity', serializer.is_valid(), serializer.errors) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ProductPost(APITestCase): fixtures = ['fixtures/initial', 'fixtures/test_capture_groups'] def setUp(self): self.file = open('file.jpg', 'rb') self.thumbnail = open('thumbnail.jpg', 'rb') self.data = { 'name': 'new product', 'file': self.file, 'thumbnail': self.thumbnail, } def test_post_product(self): response = self.client.post( '/admin/login/', {'username': 'username', 'password': 'password'}) response = self.client.post('/data_management/products/', data=self.data, format='multipart') -
Nuxt js (vue js) post to django rest error
When u try post data ftom my app created in Nuxt js (vue js) post to django rest i have error [error][1] [1]: https://i.stack.imgur.com/UgxFH.png I use axios var params = { message: this.emial_name, name: this.emial_email, email: this.emial_message } const config = { headers: { 'Content-Type': 'application/json', 'Authorization': 'Token XXX', 'Access-Control-Allow-Origin': '*', } } let res = await this.$axios.$post(`/email/`, params, config) -
Mocking cleaned_data Django Form
How I mocking django cleaned data? with mock.patch('ReporteForm.is_valid') as mock_form: mock_form.return_value = True mock_form.return_value.cleaned_data = {} -
I'm having a problem with getting this webs crawler to initiate on django. There is an error in terminal when I enter "python manage.py runserver"
Error: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is the code for: settings.py INSTALLED_APPS = [ 'news.apps.NewsConfig', 'news.models.Headline.NewsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Here is the code for: apps.py from django.apps import AppConfig class NewsConfig(AppConfig): name = 'news' Here is the code for: models.py from django.db import models from django.db import models class Headline(models.Model): title = models.CharField(max_length=200) image = models.URLField(null=True, blank=True) url = models.TextField() def __str__(self): return self.title This one finally is for: views.py from django.shortcuts import render import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup as BSoup from news.models import Headline def scrape(request): session = requests.Session() session.headers = {"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"} url = "https://www.theonion.com/" content = session.get(url, verify=False).content soup = BSoup(content, "html.parser") News = soup.find_all('div', {"class":"curation-module__item"}) for artcile in News: main = artcile.find_all('a')[0] link = main['href'] image_src = str(main.find('img')['srcset']).split(" ")[-4] title = main['title'] new_headline = Headline() new_headline.title = title new_headline.url = link new_headline.image = image_src new_headline.save() return redirect("../") def news_list(request): headlines = Headline.objects.all()[::-1] context = { 'object_list': headlines, } return render(request, "news/home.html", context) -
Setup React/DRF without using CORS or CSRF tokens
I have seen a great tutorial on YouTube where react was manually setup with DRF. Throughout the tutorial csrf tokens and django-cors-headers were not used at all. I am trying to achieve the same using npx create-react-app however csrf tokens and cors become an issue doing it this way. How am I able to avoid CSRF and CORS with my drf/react app! This is the tutorial: https://www.youtube.com/watch?v=6c2NqDyxppU&t=1s -
Django Like mechanism. Database performance question
I have CustomUser model and Post model. I consider adding a lightweight like mechanism to the posts. What comes to my mind is defining a Like model in such fashion to connect the models to each other: class LikeFeedback(models.Model): likingUser = models.ForeignKey(CustomUser) note_liked = models.ManyToManyField(Post) But this design produces a new row in the database with each like. Another option is to define CustomUser and Post models in a way that: class Post(models.Model): ... users_liked = models.ManyToManyField(CustomUser) class CustomUser(models.Model): ... posts_liked = models.ManyToManyField(Post) I am not sure if this approach creates a new row or a different indexing mechanism, but it looks tidier. In terms of DB performance what approach is the fastest? Do I need to define the ManyToMany connection in both models to speed up DB processes? Because 15 posts are to be displayed on the webpage at once and and with every post it is necessary to check if the visitor already liked the note. Also, with each like and takeback a write operation is to be performed on the DB. -
Django passing variables to Jquery
I am struggling to understand this. I have a dictionary titled alldicts that I am passing from Views in Django into the HTML. How do I then reference that dictionary to Jquery to autofill in input values in my HTML? My code in Views: mydict1 = { 'one' : 1 'two' : 2 'three' : 3 } mydict2 = { 'one' : 4 'two' : 5 'three' : 6 } mydict3 = { 'one' : 7 'two' : 8 'three' : 9 } alldicts={ 'mydict1': mydict1, 'mydict2': mydict2, 'mydict3': mydict3 } return render(request, self.template_name, alldicts) In the HTML section of my code, I have a select dropdown with the options "mydict1","mydict2", and "mydict3". Below it I have three inputs (number of inputs will be dynamic, but wanted to give a simple example) that I want to auto fill to match the selected option. (IE if I select mydict2 in the dropdown, the inputs (#one, #two, and #three) will fill to be 4,5, and 6 respectively). In html, if I try something like this, it doesn't work: $("#hselect").change(function() { var a = "{{alldicts}}"; var selectedValue = $(this).val(); $.each( a, function(idx, obj) { $.each( obj, function(key, value){ if (selectedValue == idx) { …