Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flask: make persistent variable for web app
Is it possible to have a persistent variable in Flask? I mean a variable that will be same for all users using the web app, This variable need to be able to be changed by the admin via POST request in their panel. var_example_api_url = "API_END_POINT" var_example_api_key = "API_KEY" Please help, thank you in advance! -
Maximum recursion depth exceeded in my Django signal
I have the following Django signal which basically triggers the signal to increase the points of my previous records in my postgres db by 5 when a new record is saved, but my Django signal saves the changes to 1 previous record and I get the error RecursionError: Maximum recursion depth exceeded # models.py from django.db.models.signals import post_save class Task(models.Model): .... def update_points(sender, instance, **kwargs): qs = Task.objects.filter(status='Active') for task in qs: task.points = task.points + 5 task.save() What am I doing wrong? I am using the .save() method to save the updated records in my db after a new record has been inserted. -
flask or django make simple weblog [closed]
I want to make a simple website with one of the python frameworks (Django or Flask). but I don't know which one is better my weblog gonna be simple I just post some article. pleas help me to find a better answer -
why is showing '<groups' with the symbol '<'
When i type http://127.0.0.1:8000/groups/ to the browser, I get NoReverseMatch at /groups/ and' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/groups/ Django Version: 2.2.5 Python Version: 3.8.0 Installed Applications: ['groups', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\User\Desktop\fullstack\django\simplesocialatom\simplesocial\templates\base.html, error at line 12 ' 4 : 5 : 6 : Star Social 7 : 8 : 9 : 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20 : 21 : 22 : Traceback: File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\urls\base.py" in reverse 75. extra, resolver = resolver.namespace_dict[ns] During handling of the above exception (' File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\core\handlers\base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\core\handlers\base.py" in _get_response 143. response = response.render() File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\response.py" in rendered_content 83. content = template.render(context, self._request) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\base.py" in render 171. return self._render(context) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\User\Anaconda3\envs\simplesocialenv\lib\site-packages\django\template\loader_tags.py" in render 150. return compiled_parent._render(context) File … -
how fix this collectstatics error in django?
when i run python manage.py runserver FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\Users\dato\Desktop\web\static' i have C:\Users\dato\Desktop\web\home\static STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_ROOT = "/home/dato/web/static" STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
user types in django
in my web application a user belongs to a client or a company. I try to implement that so: class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=255, unique=True) client = models.ForeignKey('client.Client', null=True, blank=True, on_delete=models.CASCADE) company = models.ForeignKey('company.Company', null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin @property def is_company(self): if self.company: return True return False @property def is_client(self): if self.company: return True return False def save(self, *args, **kwargs): if self.client and self.company: raise ValidationError("Test") super(User, self).save(*args, **kwargs) I need these differentiation because a company can maintained multiple clients and a client and a company can have multiple users. But is that the best way to implement this? I have read that i can't create multiple user classes in django, so i must implement this functionality in only one user class.. -
Large Models causing MemoryError and other errors when listed in admin site
I have the following model: class TemplateModel(models.Model): def __str__(self): return "{0} - Template - {1} - {2}".format(self.id, str(self.self.field2).upper(), str(self.self.field3)) def __lt__(self, other): return self.id < other.id # primary key id = models.FloatField(primary_key=True, blank=True) # other small fields field2 = models.CharField('abbreviation', max_length=10, default=None, editable=False) field3 = models.CharField(max_length=100, default=None, editable=False) field4 = models.TextField(null=True, blank=True, default=None, editable=False) # very large field, up to 100MB large json_data = models.TextField(editable=False) When I try to view this model in the admin console (I can view the listing for all of the various models in my project, a list of objects that I can then click and edit from there), I sometimes (inconsistently) get MemoryErrors or JSONDecodeErrors. The request also takes a long time to complete. This makes me think that the backend is loading the json_data field completely every time, which takes a lot of memory and is in this case completely unnecessary. My attempted solution was to follow the advice of this answer and add the following method to the model: def get_queryset(self, request): qs = super(TemplateCollection, self).get_queryset(request) # tell Django to not retrieve json_data field from DB qs = qs.defer('json_data') return qs but this didn't fix the problem. Ideally I would just stop json_data … -
In Django URLS, the URL map r'^.*$' doesn't load all of my react-router pages
I am working on a project that involves React-Router-Dom and Django URLS. In my urlpatterns, the string url(r'^.*$', views.index), doesn't load all of my pages,( It works on some, but for others it gives a 404) even though everywhere I've looked says this should have solved my problem. Is there something else I could use to load all of my react-router pages, or is my problem coming from somewhere else? Just to clarify, the types of urls that DO load properly are ones like /settings, and the ones that DON'T load properly are like /settings/about. urls.py from django.contrib import admin from django.urls import include, path, re_path from django.conf.urls import include, url from backend import views urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('backend.urls')), url(r'^.*$', views.index), ] index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import LoginIndex from './login_index'; import Settings from './settings'; import About from './about'; import * as serviceWorker from './serviceWorker'; import { Route, Link, BrowserRouter as Router } from 'react-router-dom'; const routing = ( <Router> <div> <Route exact path="/" component={App} /> <Route path="/login_index" component={LoginIndex} /> <Route exact path="/settings" component={Settings} /> <Route path="/settings/about" component={About} /> </div> </Router> ) ReactDOM.render(routing, document.getElementById('root', 'login_index', 'settings')); serviceWorker.unregister(); -
Django webserver automatically shuts off on local server when I try to access the admin section
I'm a noob trying to learn Django for the first time, I created a project in a virtualenv on Windows 10. It worked well in the beginning where I was able to login to the admin section after running '''python manage.py runserver''' But now when I run the same command I'm able to see the Django landing page but as soon as I try to hit http://localhost:8000/admin/ or http://127.0.0.1:8000/admin the server automatically disconnects and I get the "This site can’t be reached" error on Chrome. I tried changing the port number by running python manage.py runserver 0.0.0.0:8001 but it didn't work. I tried to check if the port (8000) is currently in use by running the cmd (as an admin) netstat -a -b but couldn't find any issues. The server just quits without any error message -
Passing the image attribute of a model in a function in Django
I have a function called detectFace(input_file), where the input file is an Image. I want to render the results via views.py on a template but could not find a way to do it. The image will be uploaded via the template and will run on the detectFace(input_file). something like this:- def detectFace(input_file): """Operation on input_file """ pass Now in views.py I am trying to creating something like this def face_recog(request): context = ?? return render(request, 'templates/face.html', context) I want to know those question marks. How should I proceed? -
Formatting of change message used when logging changes to a django field
I'm quite new to Django, and are trying to write my own logging function to log changes made when editing fields, similar to the "History" in Django admin. The plan is to use it to log changes all over the site, independently of the model. Ultimately I'm struggling to get the message itself to say "field changed from old_value to new_value". Logging manager and model: class ChangeLogManager(models.Manager): use_in_migration = True def log_update(user, content_type, object_id, content_object, changes, date_of_change): return self.model.objects.create( user = user, content_type = content_type, object_id = object_id, content_object = content_object, changes = changes, date_of_change = date_of_change, ) class ChangeLog(models.Model): user = models.ForeignKey(User, related_name = 'changed_by', on_delete = models.CASCADE) content_type = models.ForeignKey(ContentType, models.SET_NULL, verbose_name = _('content type'), blank = True, null = True,) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') changes = models.TextField(_('changes'), blank = True) date_of_change = models.DateTimeField(_('change time'), default = timezone.now, editable = False,) objects = ChangeLogManager() class Meta: verbose_name = _('Change log entry') verbose_name_plural = _('Change log entries') def get_changes(self): #? I've tried reading the source code of Django's logging, but as I'm quite new, I'm struggling to figure out what's going on. The logging message does also not include the functionality of logging what the old … -
Django CMS - Multilanguage setup translates plugins in edit mode
I am using django-cms version 3.7.1 with multilanguage setup. Default and admin user language is set to english 'en', second one is German 'de'. Everything is running ok (url, editing content for each language), except one detail - admin user language is set to English, so toolbar menu is always English, but when i switch to edit page content in deutch, plugin modal window with editor show german translation for buttons etc. Is that supposed to work that way? Now plugin text is always changing according to page language (if i add spanish for example, button will be in spanish). I need plugins to have text in language admin user have in own settings. In this case always English.. even when editing German page. Does anyone know how to achieve this? Thanks Screenshot how it look like in browser -
Data failed to import in Django models
I am trying to upload data using Django's import-export. The export works just fine but I have been unable to import from the frontend even though the import function works just well via the default admin dashboard. Anyone with the desire to help? views.py: def data_upload(request): if request.method == 'POST': country_resource = CountryResource() dataset = Dataset() new_countries = request.FILES['datafile'] imported_data = dataset.load(new_countries.read()) result = country_resource.import_data(dataset, dry_run=True) if not result.has_errors(): country_resource.import_data(dataset, dry_run=False) return render(request, 'chainedModels/setup.html') form: {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="datafile"> <button type="submit">Upload</button> </form> {% endblock %} P.S: I also noticed that "imported_data" is being greyed out in views. When I hovered it, a popup message that "local variable 'imported_data' is not used" was displayed -
DRF Serializer manipulating with third party app over REST API
As a picture is worth a thousand words, let's do it this way. So, I am trying to manipulate with Third party application over the REST CRUD API. Now, I would like to use Django Rest API routers and all the benefits that it will bring to my app. To use routers I will have to use ViewSets. Instead of models I am using just simple python class since I do not have to store any data (perhaps this is not needed at all?). The question is, how to create Serializers that will transform complicated json data that is coming from Third party service, transform it and send it to Fronted. But when I change data on Frontend app to propagate changes and update Third party app. So far I have this: urls.py router.register(r'applications', ApplicationViewSet, base_name='application') models.py class Application(object): def __init__(self, name, color): self.name = name self.color = color serializers.py class ApplicationSerializer(serializers.Serializer): name = serializers.CharField(max_length=256) #color = ??? How to transform and serialize dict value to field ? views.py class ApplicationViewSet(ViewSet): def create(self, request): # I guess that this logic should be handled by serializes as well?. name = request.data.get('name') color = request.data.get('color') result = third_party_service.create_application(request, name) app = Application(**result) … -
Why MySQL creating indexes for Foreign key during table updation
It is given in documentation that when you add a foreign key using alter table command then MySQL does not create an index for foreign key and you need to create it manually. https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html The foreign key can be self referential (referring to the same table). When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first. But I added a foreign-key in the table using alter table command and it is creating index along with constraint. ALTER TABLE `pharmaceuticals_dosage` ADD CONSTRAINT `pharmaceuticals_dosa_as_needed_reason_cod_2ac978bf_fk_human_api` FOREIGN KEY (`as_needed_reason_code_id`) REFERENCES `human_api_code` (`id`); I assume that MySQL official documentation should not be wrong, So any reason why it is creating index? PS: Above Query is created by Django migration -
MySQL not creating indexes for foreign key
I read that InnoDB automatically creates indexes for Foreign-key. Does MySQL Workbench automatically create indexes for foreign keys? Does MySQL index foreign key columns automatically? https://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html But some of my foreign keys do not have the index in the table. Check pharmaceutical_id foreign-key field. It does not have an index. | pharmaceuticals_pharmaceuticalcode | CREATE TABLE `pharmaceuticals_pharmaceuticalcode` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code_id` int(11) NOT NULL, `pharmaceutical_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `pharmaceuticals_pharmaceuticalco_pharmaceutical_id_5ae1e77e_uniq` (`pharmaceutical_id`,`code_id`), KEY `pharmaceuticals_phar_code_id_a7de9505_fk_human_api` (`code_id`), CONSTRAINT `pharmaceuticals_phar_code_id_a7de9505_fk_human_api` FOREIGN KEY (`code_id`) REFERENCES `human_api_code` (`id`), CONSTRAINT `pharmaceuticals_phar_pharmaceutical_id_04c18462_fk_pharmaceu` FOREIGN KEY (`pharmaceutical_id`) REFERENCES `pharmaceuticals_pharmaceutical` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=202770 DEFAULT CHARSET=utf8 COLLATE=utf8_bin | I have added unique-together constraint on pharmaceutical_id and code_id which may caused the not creation of separate index for pharmaceutical_id because MySQL manage these index in B-Tree fashion and index of unique-together key can be used for it. Check 6th point of restriction and condition on https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are the first columns in the same order. Hidden columns that InnoDB adds to an index are also considered (see Section 14.6.2.1, … -
Django Elastic search filter not working properly. how to solve it?
what is different between "terms" and "match" ?. how to filter if the word contains white space ?. when i run elasticsearch with django on local system using following filters s = s.filter('match',text="sometext") s = s.filter("match_phrase", author="author123") s = s.filter("term", author="author 312") it run smoothly. my elasticsearch version elasticsearch-7.4.0 but when i run following filter on aws elasticsearch it produce following error RequestError(400, 'parsing_exception', 'Failed to parse') but s = s.filter("terms", author="author 312") run without error another two filter not working -
Django Authenticate always returns None with correct credentials also
I was creating a login and registration page for my project and was using the Django MySQL database for login and creating users the signup was done correctly but the login function is not working for me. PS: The is_active is Set True but still this is not working With all correct info, it shows None. I have given all the necessary parts of the file and codes I tried everything but nothing seems to work also tried some of the solutions listed on StackOverflow but still, nothing worked for me. from django.shortcuts import render, redirect from .models import Description from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def index(request): d = Description.objects.all() return render(request,'index.html',{'des':d}) def signup(request): if request.method == 'POST': first_name = request.POST['first'] last_name = request.POST['last'] user_name = request.POST['user'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] if pass1 == pass2: if User.objects.filter(email=email).exists(): print("Email taken") elif User.objects.filter(username=user_name).exists(): print("Username taken") else: user = User.objects.create_user(username = user_name, first_name=first_name,last_name=last_name, password=pass1, email=email) user.save() print("User created") else: print("Password Not Matching") return redirect('/') else: return render(request,'signup.html') def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] print(email,password) user = authenticate(request, email=email, password=password) … -
Is there any way I can avoid iterating over a query set with single value?
I get a queryset object every time i want some data from models. So when i say, "items = Items.object.get(value=value)" I get -- "<QuerySet [<Item-name>]>" I have to iterate through the queryset object to get the data and I do that with "items[0]" Is there any way I can avoid this? -
How to resolve custom tags interfering with reverse matching
urls.py urlpatterns = [ path('', index, name='index'), path('login/', login, name='login'), path('logout/', logout, name='logout'), path('register/', register, name='register'), path('jewels/', index, name='jewel_projects'), path('bootcamp/', index, name='bootcamp_projects'), path('all_projects/', index, name='all_projects'), path('view_project/<int:project_id>', view_project, name='view_project'), path('demo_project/<str:project_slug>', demo_project, name='demo_project'), path('view_image/<int:image_id>', view_image, name='view_image'), path('view_projects_page/<int:page_id>', view_projects_page, name='view_projects_page'), ] custom_tags.py: from django import template from apps.portfolio.models import Page register = template.Library() @register.simple_tag def get_pages(): return {'pages': Page.objects.all()} base.html (template) {% load static %} {% load custom_tags %} {% get_pages as pages %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Pearako</title> </head> <body> <div class="container-fluid"> <div id="header"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">Pearako</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% for page in pages %} <li class="nav-item"> <a class="nav-link" href="{% url 'view_projects_page' page_id=page.id %}">{{ page.name}}</a> </li> {% endfor %} </ul> When I run with things like this, I get this error: Reverse for 'view_projects_page' with keyword arguments '{'page_id': ''}' not found. 1 pattern(s) tried: ['view_projects_page\\/(?P<page_id>[0-9]+)$'] However, if I remove '{% get_pages as pages %}' from the template, everything works fine, except, of course, I cannot call the tag I need. How can I implement this so calling the custom tag does not interfere with the reverse matching? -
Django Rest Framework could not impot six from django utils (Django3)
Im using Django 3.0, I'm aware that django3 no more supports django.utils.six module, but this is a different case. Turns out that JSONField modeltype is dependent on this package. Im trying to create JSONField like this : models.py: from django.db import models from django.conf import settings from jsonfield import JSONField class Bubble(models.Model): name = models.CharField(max_length = 255) username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) information = JSONField(default = None,null = True) This is the exception i get: ImportError: cannot import name 'six' from 'django.utils' (C:\Users\jime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\__init__.py) Now is this post i saw that the issue is occured with a package named corsheaders . In this case, how im going to create a JSONField in django3.0 ? Thanks for the help. -
Receive response from django channel consumer in view using channel_layers
I am using Django channels and have a simple consumer with async def websocket_connect(self, event): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def websocket_receive(self, event): message = event.get('text') await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): print("------------In Chat Msg------") message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) async def websocket_disconnect(self, message): I have a View to implement HTTP POST request/response.I wanted to send POST data send to one of my consumer instances using channel using simple code : def home (request): channel_layer = get_channel_layer() listen_channel_name = async_to_sync(channel_layer.new_channel)() async_to_sync(channel_layer.group_send)( **chat_name**,//is same as group name {"type": "chat_message", "message": "my_msg"} ) I am able to send HTTP request data to consumer instance using above code.Now i want to return the response from consumer to view using below code in view.py def home (request): ...//above mentioned received_msg = channel_layer.receive(listen_channel_name)//ISSUE but it does not works as accepted.received_msg is always "" I also want to know that is it the best way to integrate DRF and Django channel. -
I getting issues with mysqlclient installation on windows
I have already installed Microsoft Visual C++ 14.0. Please check the below error and guide me. Python Version: 3.7.0 PIP Version: 19.3.1 Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\Sun e-soft\PycharmProjects\Django\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\SUNE-S~1\AppData\Local\Temp\ \pip-install-devlowov\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\SUNE-S~1\AppData\Local\Temp\pip-install-devlowov\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'ope n'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\SUNE-S~1\AppData\Local\Te mp\pip-record-5fft4z1g\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Sun e-soft\PycharmProjects\Django\venv\include\site\python3.7\mysqlc lient' cwd: C:\Users\SUNE-S~1\AppData\Local\Temp\pip-install-devlowov\mysqlclient\ Complete output (26 lines): C:\Python\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\Sun e-soft\PycharmProjects\Django\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users … -
Slack Events API: Events are posted (multiple times) for responses of own bot user
I seem to have a problem when responding to incoming messages via the Slack Events API (im.message event) When a user (in this case UQ364CBPF) sends a message to my App Home, the events API correctly posts an event to my backend (=first line in the logs below). I respond to the event with an HTTP 200 OK, and in my code (see below), I trigger a response from my Bot User. This response is sent correctly in Slack. But: after that, the events API keeps posting events that my own bot user has posted a message in this channel... Also, where the events are usually posted only 3 times, these events just keep being posted non-stop. Even though the bot user only sent one response message in Slack. User UQ364CBPF has posted message: I'm typing a message to my Slack bot. in DQ5FF35N2 of channel type: im [26/Dec/2019 15:16:30] "POST /slack/events/ HTTP/1.1" 200 0 User UQ5529KTR has posted message: Thank you for your message! We will get back to you soon! in DQ5FF35N2 of channel type: im [26/Dec/2019 15:16:32] "POST /slack/events/ HTTP/1.1" 200 0 User UQ5529KTR has posted message: Thank you for your message! We will get back to … -
Deleting test data on Django test
I have a Django app and i trying to create test of API requests and can't delete the data creates during tests. The Add Product request create register on Product table and a register on Stock table My Test Class: class TestSaleBuyRequest(TestCase): def setUp(self): self.BASE_URL = 'http://localhost:8000/api/' token = json.loads(requests.post(f'{self.BASE_URL}auth/', data={ "username":"user", "password":"pass"} ).text)['token'] self.headers={"Authorization":f"token {token}"} def test_create_products(self): self.product_1 = json.loads(requests.post( f'{self.BASE_URL}product/', data={ "name":"_TEST_PRODUCT NAME", "brand":"_TEST_PRODUCT BRAND", "unit":"_TEST_PRODUCT UNIT"}, headers=self.headers ).text) self.product_2 = json.loads(requests.post( f'{self.BASE_URL}product/', data={ "name":"_TEST_PRODUCT NAME2", "brand":"_TEST_PRODUCT BRAND2", "unit":"_TEST_PRODUCT UNIT2"}, headers=self.headers ).text) expected_1 = { "name":"_TEST_PRODUCT NAME", "brand":"_TEST_PRODUCT BRAND", "unit":"_TEST_PRODUCT UNIT", "response":{ "status":200 } } result_1 = { "name":self.product_1["name"], "brand":self.product_1["brand"], "unit":self.product_1["unit"], "response":{ "status":self.product_1["response"]["status"] } } expected_2 = { "name":"_TEST_PRODUCT NAME2", "brand":"_TEST_PRODUCT BRAND2", "unit":"_TEST_PRODUCT UNIT2", "response":{ "status":200 } } result_2 = { "name": self.product_2["name"], "brand": self.product_2["brand"], "unit": self.product_2["unit"], "response":{ "status":self.product_2["response"]["status"] } } self.assertEqual(expected_1, result_1) self.assertEqual(expected_2, result_2) I create a delete function: def delete_data_tests(): print('INICIANDO DELETE') delete_ids = Product.objects.filter(name__icontains='_TEST_') cont = delete_ids print('Aquivos de testes encontrados', len(delete_ids)) for prod in delete_ids: print('\nTRYING DELETE PROD:',prod.id) Stock.objects.filter(product=prod).delete() print('VERIFICANDO REMANESCENTES') print('Aquivos de testes encontrados', len(Product.objects.filter(name__icontains='_TEST_'))) return delete_ids.delete() print('\nFINALIZADO') But when I run this function inside test.py the Product.objects.filter(name__icontains='TEST') return 0 results. OBS: The function works when I run her outside of test.py