Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't install mysqlclient on Mac OS Catalina
I am using Mac OS Catalina 10.15.7, and I want to install mysqlclient on my virtualenv-django directory but I couldn't. I've tried all possible suggestions but I am still getting the same massive error. Please help me out.. I tried >> pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/capstone1/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-wheel-wrv_jpbq cwd: /private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/ Complete output (27 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.8 creating build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb creating build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.14-x86_64-3.8 creating build/temp.macosx-10.14-x86_64-3.8/MySQLdb clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/opt/openssl/include -Dversion_info=(2,0,1,'final',0) -D__version__=2.0.1 -I/usr/local/opt/mysql-client/include/mysql -I/usr/local/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/sqlite/include -I/Users/capstone1/include -I/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c MySQLdb/_mysql.c -o build/temp.macosx-10.14-x86_64-3.8/MySQLdb/_mysql.o xcrun: … -
How to pass a variable/value with DeleteView in django urls
is there any way to pass a variable with DeleteView in Django? This is my code: path('category/<int:pk>/delete/', DeleteView.as_view( model=Category, success_url=reverse_lazy('expenses:category-list') ), name='category-delete'), I need to pass a number of related elements in database. I would use queryset.filter() and then pass it to the DeleteView. Is there any way of passing that variable directly to the rendered html or I need to make new view in views.py? I know that I can do {{object}}, but nothing more. -
djrestauth customizing password reset email template does not display template variables
I want to customize the contents of the password reset email template and after doing a lot of searches I have found this. serializers.py from dj_rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'email_template_name': 'account/email/password_reset_key_message.txt' } password_reset_key_message.txt {% load i18n %}{% autoescape off %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hello fro {{ site_name }}! You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %} {{ password_reset_url }} {% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %} {% endif %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you for using {{ site_name }}! {{ site_domain }}{% endblocktrans %} {% endautoescape %} settings.py REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'accounts.serializers.CustomPasswordResetSerializer' } Email that I receive Hello fro ! You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. Thank you for using ! So the template variables are not being … -
Adding custom field to django-notifications always returning none on notify.send()
I am trying to add a new field to the Notification model in django-notifications-hq. Currently in my main/models.py i have: class Notification(AbstractNotification): # custom field example unique_uuid = models.CharField(max_length=255,unique=True, null=True) class Meta(AbstractNotification.Meta): abstract = False app_label = 'main' Now in my settings.py file I have: NOTIFICATIONS_NOTIFICATION_MODEL = 'main.Notification' NOTIFICATIONS_USE_JSONFIELD=True I am trying to generate a notification in my views.py by using: notify.send(sender=user, recipient=post.author, verb=message, target=post, \ unique_uuid = notification_create_uuid(...)) However, the notification is not being created correctly and the field is returning "None". How can I set this field in notify.send(), so that the notification is created with that field set? -
Send email from view when testing in Django
So I have a view that sends an emails when it store some data on the database, currently I'm testing but the test returns The email can't be sent that happens when there is an error sending the email, I have checked some answers here but so far no positive results. My code: views.py def update_inventory(self): # code store the data is success context = { 'time': timezone.now() } # render email text email_html_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.html', context) email_plaintext_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.txt', context) msg = EmailMultiAlternatives( # title: "{title}".format(title="Inventory updated"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: "email@email.com" ) msg.attach_alternative(email_html_message, "text/html") try: msg.send() except Exception as e: raise serializers.ValidationError({'error':"The email can't be sent"}) return Response({'info':'Inventory successfully updated'}, status=status.HTTP_200_OK) tests.py def test_successfully_update_inventory(self): data = {'product1': 500, 'product2': 200} response = self.client.post(reverse('inventory:update-inventory'), data, format='json') stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.getLogger().info(response) # Prints The email can't be sent Any thoughts about this? Thanks in advance -
Categories and Subcategories showing products for the parent and children
Im doing a ecommerce website with django and I have a problem with categories and subcategories. This are my models: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True) title = models.CharField(max_length= 200, null = True) slug = models.SlugField(max_length=200, null = True) ordering = models.IntegerField(default = 0) class Product(models.Model): name = models.CharField(max_length = 255, null = True) slug = models.SlugField(max_length=200) category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE) parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True) brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE) description = models.TextField(blank = True, null = True) price = models.FloatField(null = True) disccount = models.BooleanField(default = False) disccount_price = models.FloatField(blank = True, null = True) And this is my view: def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.filter(parent = None) context = { 'category': category, 'products' : products } return render(request, 'category_detail.html', context) Okay so what I want to do is if I click the parent category I want to show all the products that their children have and If I click a Children I want to show only the products that he has. So i don't know how to do … -
Pass parameter to cursor.execute in Django
I have the following view definition Django def getEiNumberByFeatures(request): # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the nick name from the client side. id = request.GET.get("id", None) sqlQuery = """SELECT names FROM Costumer WHERE id = %s """ cursor.execute(sqlQuery, (id)) eiNumbers = cursor.fetchall() context = {"EiNumber": eiNumbers} return JsonResponse(context, status=200) I am getting the following error pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000') Have somebody any idea why this can happens? Even when I am sending the parameter -
Помогите написать Permission django rest framework для бана пользователя
Если пользователь забанен тогда он не сможет смотреть PostDetailAPIView. Нужно написать Permission - IsBanned Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') name = models.CharField(max_length=50) bio = models.TextField(max_length=2000, blank=True, default='') avatar = models.ImageField(upload_to='media', null=True, blank=True) is_moderator = models.BooleanField(default=False, verbose_name=("moderator")) is_ban = models.BooleanField(default=False) is_mute = models.BooleanField(default=False) Views.py class PostDetailAPIView(generics.RetrieveAPIView): queryset = Topic.objects.all() serializer_class = PostDetailSerializer permission_classes = [IsBanned] -
Utilise AJAX & javascript to create a toast with Djangos messaging framework
I have followed a tutorial to utilise AJAX to validate an input field before attempting to submit. I have it working on my django built site; however, I have been using toasts to alert the user to other actions and did not want to get way from this. $("#id_hub_name").focusout(function (e) { e.preventDefault(); // get the hubname var hub_name = $(this).val(); // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'validate_hubname' %}", data: {"hub_name": hub_name}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("You cannot create a hub with same hub name"); var hubName = $("#id_hub_name"); hubName.val("") hubName.focus() } }, error: function (response) { console.log(response) } }) }) This is my current JS, I want to change the alert function to use toasts instead. In my base.html I use the following to listen for toasts and create them. {% if messages %} <div class="message-container"> {% for message in messages %} {% with message.level as level %} {% if level == 40 %} {% include 'includes/toasts/toast_error.html' %} {% elif level == 30 %} {% include 'includes/toasts/toast_warning.html' %} {% elif level == 25 %} {% include 'includes/toasts/toast_success.html' %} {% else %} {% include 'includes/toasts/toast_info.html' %} {% endif … -
Dependent drop down box in form for every submit render chart, how to update new value in chartjs dataset?
I am working on Django project I write the code for dependent drop down box that can be get values and passed to the backend to call the API/JSON to fetch that data in chartjs, but here if I click submit the chart will appear, for the next time I will select zero value or any other value so the chart is disappeared or new values comes but if I overlay the mouse its showing old data also and new data also, how to update only new values. here is my code HTML: <form id ="new_form" name="new_form" method="POST"> {% csrf_token %} <label for="Question_type">Question Types:</label> <select id="qt_it" name = "select_question_type"> <option value="{{question}}">ALL</option> {% for qt in question %} <option value="{{qt.id}}">{{qt.question_type}}</option> {% endfor %} </select> <label for="Certificate">Certificate:</label> <select id="Certificate" name = "select_certificate"> <option disabled selected = "true"> -- Select certificate -- </option> {% for certificate in certifi %} <option value="{{certificate.id}}">{{certificate.certification_name}} {{certificate.certification_year}}</option> {% endfor %} </select> <label for="state">State:</label> <select id="state_id" data-district-url="{% url 'Dashboard:load_district' %}" name = "select_state"> <option disabled selected = "true"> -- Select State -- </option> {% for state in states %} <option value="{{state.id}}" >{{state.state_name}}</option> {% endfor %} </select> <label for="district">District:</label> <select id="district_id" data-taluk-url="{% url 'Dashboard:load_taluk' %}" name = "select_district"> <option disabled … -
How can I write more columns than defined in header?
I am using Datatables jQuery plugin and I have the following columns in html: <tbody> <td class="test1">elem1</td> <td class="test2" style="display: none;">elem2</td> </tbody> I activate one or the other column from jQuery ( always one ). Problem is that 'datatables' plugin yells error because num of columns from tbody is not equal with num of columns from thead (1 in my case 'cause I only want one to display). Is there a workaround for defining more columns than specified in the header and pass validation ? I am writing the html thought Django's template language. For showing columns I use somthing like this: <select onchange="selectChange(this.value)"> <option>test1</option> <option>test2</option> </select> function selectChange(val) { $(`[class*="test"]`).hide(); $(`[class="${val}"]`).show(); } -
Using CheckBox in Django FilterSet
I can't seem to find any solutions to this issue.. In my models.py I have a class called Course like this: class Course(models.Model): seats_occupied = models.IntegerField(null=True, default=0) seats_available = models.IntegerField(null=True, default=25) # etc... In my filters.py I have this filter for it: class CourseFilter(django_filters.FilterSet): seats_occupied = django_filters.NumberFilter(field_name='seats_occupied', lookup_expr='lt') At this point, I need to enter a number to see if seats_occupied is less than that number. But I would like to just have a CheckBox or Possibly a multiple choice with "open/full" courses, that will only give me the courses that are not full. Is there a good way to accomplish this? -
Docker Set Up mysql db
I was setting up mysql with docker and I observe that without defining environment in docker-compose.xml, file I am able to run mysql . Is this good or I am going wrong ? my docker-compose.xml is db: image: mysql:5.7 restart: always ports: - "3302:3306" and my settings.py file is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': myproj, 'USER': root, 'PASSWORD': 123123123, 'HOST': 'db', 'PORT': 3306, } } I didn't enter any environment in xml file . If even I do its working same . -
How to serve local CSS files in my Django-Dash-Plotly app
I need to add CSS to my project to enable it to stop conflicting with Bootstrap CSS. I have the exact problem this person is having with fixed columns. The solution is to add this CSS snippet somewhere in my directory: .dash-spreadsheet .row { flex-wrap: nowrap; } My only problem is, I'm an extreme novice when it comes to styling files and I feel completely lost on where to add this snippet into my Django-Dash project. I've read the documentation from Django-Dash for local files Also looked at Dash-Plotly official documentation for adding CSS ... and I'm still confused on where to add the code snippet. For anyone wondering I've tuned my django settings.py to fit the Django-Dash requirements, according to documentation. Here is how my Django project is set-up: app.py is my Dash app that is within my home Django app. stockbuckets folder is the main project folder that holds my settings.py file. I see I am also meant to add serve_locally = True as an in app argument or global variable for DASH_PLOTLY in settings.py. Either method I use just gets my project stuck in HTTP GET... trying to find the local files I'm assuming? Would greatly appreciate … -
Getting data from Shopify to Django
I have an Inventory App that was built in django and I want to extract the data from Shopify to my web app. Basically I want to get the customers info from shopify and show it to my Django app table. How to do this ? Any tips? -
how to use json data in django orm filter
I use in query filter in **kwargs but output query set is None. My code is below: kwargs={"category":["v1","v2","v3"],"tags":["t1","t2"]} obj.filter(**kwargs ) -
Django, Docker and traefik shows 404 on deploy but no error logs - using django-cookiecutter
I recently decided to move my website to use docker along with the template that django-cookiecutter with the goal in mind of easy deployment and easy to setup environments. Localy the project runs fine and I can access the website through the ip address of the virtualmachine on port 8000. But when deploying it to DO with the production.yml file it does not fail, the build and up both run successfull. But when I try access the ip of my droplet I get a 404. The only error that I get is from traefik, SSL related and I don't think this is causing the 404. traefik_1 | time="2020-10-07T16:47:26Z" level=error msg="Unable to obtain ACME certificate for domains \"bgan.be,www.bgan.be\": unable to generate a certificate for the domains [bgan.be www.bgan.be]: error: one or more domains had a problem:\n[bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://bgan.be/.well-known/acme-challenge/4AvrIU9r8F3PwtyrK_6yq8fwHc4CgiHeT_4Vk5Yo0G4 [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n[www.bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://www.bgan.be/.well-known/acme-challenge/gToGrbtaQN5SBFyArzNz8r1SQx8QSB2Wax3_CqzYXCk [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n" providerName=letsencrypt.acme routerName=web-secure-router@file rule="Host(`bgan.be`) || Host(`www.bgan.be`)" Would anyone have any suggestions on why this is happening? been stuck on this for 3 days now and have tried to … -
Why my django server is not running after changing BASE_DIR?
I am getting the following error in Git bash. $ python manage.py run Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\website\website\website\settings.py", line 72, in <module> 'NAME': BASE_DIR / 'db.sqlite3', TypeError: unsupported operand type(s) for /: 'str' and 'str' When I am trying to run the server it shows this. Can anyone please explain it? -
Django: Save forms cleaned_data with foreign key as session items
I've got a ModelForm with a number of attributes - in the CreateView form_valid method I'm trying to save a users form inputs as session data (which I check for in the get_initial method if they visit the form again) ModelForm: class OrgForm(forms.ModelForm): """Form definition for a Org.""" class Meta: """Meta definition for OrgForm.""" model = Org fields = ( "full_name", "short_name", "feature", "state", "email", ) View: class OrgCreateView(CreateView): "CreateView for OrgForm" model = Org form_class = OrgForm success_url = "/home/" def form_valid(self, form): response = super().form_valid(form) # Set the form data to session variables responses = {} for k, v in form.cleaned_data.items(): responses[k] = v self.request.session["org_form_data"] = responses return super().form_valid(form) def get_initial(self): initial = super(OrgCreateView, self).get_initial() # Check for any existing session data # This is present if they had filled this out # and then came back again later to fill out again if "org_form_data" in self.request.session: # They have data - loop through and fill it out for key, value in self.request.session["org_form_data"]: initial[key] = value return initial Model: class Org(models.Model): """Model definition for Org.""" full_name = models.CharField(max_length=150) short_name = models.CharField(max_length=25, blank=True, null=True) state = models.CharField(max_length=50) is_active = models.BooleanField(default=False) feature = models.ForeignKey(Feature, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) last_updated … -
DJANGO: Need help in implementation of price filtering of items through HTML <FORM>
I wanted to add buttons to select between ASC or DSC order of viewing items. I added a radio button to select between ascending order of price and descending order of price of items to be shown. I know how to sort the list of the hat items in descending or ascending order in views.py but I don't know what condition to use and how to change the order through the form in the html code. I'm new to this and this is my first project in DJANGO. I know I have to get some POST input through the form and use that variable in the condition in views.py but I don't know how. Thankyou. relevant part of views.py file: def head_wear(request): if(#whatconditionhere): hat_list=models.Hat.objects.order_by('price') else: hat_list = models.Hat.objects.order_by('-price') stuff_for_frontend = { 'hat_list': hat_list, } return render(request, 'AUM/head_wear.html',stuff_for_frontend) relevant part of head_wear.html <form class="form-inline" action="#"> <div class="col s4 offset-s4"> <p> <label> <input class="with-gap" name="group1" type="radio" checked /> <span style="color:white;">Ascending</span> </label> </p> </div> <div class="col s4 offset-s4"> <p> <label style="padding-left:150%;"> <input class="with-gap" name="group1" type="radio" /> <span style="color:white;">Descending</span> </label> </p> </div> </form> urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('head_wear',views.head_wear,name='head_wear'), path('shirt_wear',views.shirt_wear,name='shirt_wear'), path('pant_wear',views.pant_wear,name='pant_wear'), path('watch_wear',views.watch_wear,name='watch_wear'), path('shoe_wear',views.shoe_wear,name='shoe_wear'), … -
Django Rest Auth - Facebook Login Access Token
I trying to make a django rest authentication system. I use the dj-rest-auth. I successfully made the app to register and login local user ( with email & password). Now i would like to sign up users with Facebook. I follow all the introductions from the dj-rest-auth docs https://dj-rest-auth.readthedocs.io/en/latest/. I follow other introductions to setup the admin page and the Facebook For Developers stuff and finally i got this(picture). Then i found the access token manualy from my facebook profile and successfully I register a user(my profile) on my app. My problem is that i want to Sign Up with facebook directly like all other applications like this "Continue As"(picture) and i couldn't found how to do this. I would like to make an API for this because i would like to make a React-Native frontend. Thank you all for your time :) !! In my settings.py in INSTALLED_APPS : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter', ] My urls.py : from django.contrib import admin from django.urls import path, include from .views import FacebookLogin, FacebookConnect urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/facebook/', FacebookLogin.as_view(), name='fb_login'), path('dj-rest-auth/facebook/connect/', … -
how to make summation between two similar object instead of creating a new object? django
i try to make a system for a storage , sometimes it happen two similar objects are entry in two different time , i have summation the quantity of both and looks like one object instead of two different object for example i've entry this data one week ago name=mouse , qnt=20 , price=20 and today i add a new collection of mouse (the same mouse as before) name=mouse , qnt=10 , price=15 i have to whenever i face similar problem it automatically summation quantities =(30) and price = ((20+15)/2) instead of creating a new object to the second mouse object this is my model this is the Products model class Products(models.Model): name = models.CharField(max_length=20,unique=True) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) def __str__(self): return self.name this is the Collections model class Collections(models.Model): name = models.ForeignKey(Products, on_delete=models.CASCADE) qnt = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3,null=True,blank=True) i dont need to create new object to the same product as exist in collection , i have to just summation the quantities ?! is it possible ?thanks -
How to solve issue corb (cross origin read block) in django python?
In my Django application I get an error Cross Origin Read Blocking, I have searched an internet that says it is the version problem of Chrome, so I have tried Internet Explorer, Microsoft Edge I still get same error I have installed pip install django-cors-headers and add it to settings.py file INSTALLED_APPS = [ ... 'corsheaders', ... ] and also MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', ... but when I reload the page the result is same. I want to add a picture to my website from google pictures. Here is the result chrome console shows **Cross-Origin Read Blocking (CORB)** blocked cross-origin response https://en.wikipedia.org/wiki/The_Terminator with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. Here is the result from Microsoft Edge Cross-Origin Read Blocking (CORB) blocked cross-origin response https://en.wikipedia.org/wiki/The_Terminator with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details. I am using Django version 3.1.2, Python 3.7.9 -
Where is the css .fieldWrapper class defined? (Django? Bootstrap?)
I have some HTML code in a Django app (with Bootstrap) that has a .fieldWrapper CSS class. I searched for this class in Google, in the Django docs, and in the Bootstrap docs. In the Django docs, I see it being used in examples, but I don't see it documented anywhere. Where is the .fieldWrapper class defined? (and optionally, where is the documentation for it?) -
How to Send Email from Django
I am taking a tutorial for Django, but stuck at sending email from Django. I am working on Django's built in django.contrib.auth password reset views, it works fine, but doesn;t actually sends any email. For Testing purpose, I am using below code example to send email, but it gives error which I don't know where to resolve. (env1) C:\Users\crm>python manage.py shell Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'email1@gmail.com', ... ['email2@gmail.com'], ... fail_silently=False, ... ) Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 51, in send_mail connection = connection or get_connection( File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line …